text
stringlengths
10
2.72M
package securities_trading_platform; import java.awt.BorderLayout; import java.awt.Font; import java.awt.GridLayout; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.table.TableCellRenderer; import securities_trading_platform.gui.button.ButtonEditor; import securities_trading_platform.gui.button.ButtonRenderer; import securities_trading_platform.gui.column.ColumnBackgroundRenderer; import securities_trading_platform.gui.column.CustomTableRenderer; import securities_trading_platform.gui.spinner.SpinnerEditor; import securities_trading_platform.gui.table.TablePortfolio; import securities_trading_platform.gui.table.TableTrading; import securities_trading_platform.gui.table.TableTransactions; /* * This class creates 3 tables on the event-dispatching thread. * * I haven't used a SwingWorker class (for the JTable tableTrading) as a background thread * because it can be instantiated, at the same time, only 10 times maximum (for that table * I need more instances). BTW this is not mentioned in the documentation (On 9th July * I have reported this bug). * * @author Zoran Bosanac * @version 1, 29. May 2016. * * Important note: starting on 22nd of July, problems with the Yahoo server became very often. * At the moment there are no other sources of stock data for free (Google finance doesn't have * it and to get stock data directly from the stock markets, Reuters or Bloomberg - that would * be costly endeavor). Because of that, this program sometimes is not fully operational. * Please accept my apology, but at the moment I don't have any other option. */ public class MainClass { public static TableTrading modelTrading = new TableTrading(); public static JTable tableTrading = new JTable(modelTrading); public static Font font = new Font(null, Font.PLAIN, 15); /** * Create the GUI and show it. For thread safety, * this method should be invoked from the * event-dispatching thread. */ private static void createAndShowGUI() { // We can run the following method, but it is not necessary // System.out.println("Created GUI on EDT? "+ // javax.swing.SwingUtilities.isEventDispatchThread()); TablePortfolio modelPortfolio = new TablePortfolio(); TableTransactions modelTransactions = new TableTransactions(); JTable tablePortfolio = new JTable(modelPortfolio); JTable tableTransactions = new JTable(modelTransactions); // This method enables rows sorting. For the rows in which are numbers, it doesn't work well, // so this should be improved in the next version tableTrading.setAutoCreateRowSorter(true); tablePortfolio.setAutoCreateRowSorter(true); tableTransactions.setAutoCreateRowSorter(true); // Will set font for all cells in table except column names tableTrading.setFont(font); tablePortfolio.setFont(font); tableTransactions.setFont(font); // Will set font only for all column names tableTrading.getTableHeader().setFont(font); tablePortfolio.getTableHeader().setFont(font); tableTransactions.getTableHeader().setFont(font); // Will prevent table to resize column width tableTrading.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); tablePortfolio.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); tableTransactions.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); // Will set width of a particular column tableTrading.getColumnModel().getColumn(0).setPreferredWidth(200); tableTrading.getColumnModel().getColumn(1).setPreferredWidth(80); tableTrading.getColumnModel().getColumn(2).setPreferredWidth(100); tableTrading.getColumnModel().getColumn(3).setPreferredWidth(90); tableTrading.getColumnModel().getColumn(4).setPreferredWidth(90); tableTrading.getColumnModel().getColumn(5).setPreferredWidth(80); tableTrading.getColumnModel().getColumn(6).setPreferredWidth(100); tableTrading.getColumnModel().getColumn(7).setPreferredWidth(80); tableTrading.getColumnModel().getColumn(8).setPreferredWidth(80); tableTrading.getColumnModel().getColumn(9).setPreferredWidth(130); tableTrading.getColumnModel().getColumn(10).setPreferredWidth(130); tablePortfolio.getColumnModel().getColumn(0).setPreferredWidth(200); tablePortfolio.getColumnModel().getColumn(1).setPreferredWidth(80); tablePortfolio.getColumnModel().getColumn(2).setPreferredWidth(100); tablePortfolio.getColumnModel().getColumn(3).setPreferredWidth(100); tablePortfolio.getColumnModel().getColumn(4).setPreferredWidth(130); tableTransactions.getColumnModel().getColumn(0).setPreferredWidth(200); tableTransactions.getColumnModel().getColumn(1).setPreferredWidth(80); tableTransactions.getColumnModel().getColumn(2).setPreferredWidth(100); tableTransactions.getColumnModel().getColumn(3).setPreferredWidth(100); tableTransactions.getColumnModel().getColumn(4).setPreferredWidth(130); tableTransactions.getColumnModel().getColumn(5).setPreferredWidth(130); // Will set height of all rows in table tableTrading.setRowHeight(20); tablePortfolio.setRowHeight(20); tableTransactions.setRowHeight(20); // We need this to change text color of the 6th column tableTrading.getColumnModel().getColumn(5).setCellRenderer(new CustomTableRenderer()); // This will set the background for the 7th column which is the only editable column (except buttons, which // are 8th and 9th column) TableCellRenderer defaultRenderer = tableTrading.getDefaultRenderer(Object.class); TableCellRenderer rend = new ColumnBackgroundRenderer(defaultRenderer); tableTrading.setDefaultRenderer(Object.class, rend); // Will set spinner in the 7th column tableTrading.getColumnModel().getColumn(6).setCellEditor(new SpinnerEditor()); // Will set button in the 8th column // In the class TableTrading, method isCellEditable should return true for that column tableTrading.getColumnModel().getColumn(7).setCellRenderer(new ButtonRenderer()); tableTrading.getColumnModel().getColumn(7).setCellEditor(new ButtonEditor(new JCheckBox(), tableTrading, modelTransactions)); // Will set button in the 9th column // In the class TableTrading, method isCellEditable should return true for that column tableTrading.getColumnModel().getColumn(8).setCellRenderer(new ButtonRenderer()); tableTrading.getColumnModel().getColumn(8).setCellEditor(new ButtonEditor(new JCheckBox(), tableTrading, modelTransactions)); // Create and set up the window JFrame frame = new JFrame("Securities trading platform"); JLabel label1 = new JLabel("This is just a trading simulation, so you can freely click on any buy or sell button."); JLabel label2 = new JLabel("Settings: 1-click button. Meaning: user needs to just once press buy or sell button " + "for the virtual transaction to be realized."); JLabel label3 = new JLabel("Minimum transaction is 1.000 stocks or value of 1.000,00 €. Maximum transaction is " + "1.000.000 stocks or value of 10.000.000,00 €."); JLabel label4 = new JLabel("Short selling is not allowed. Meaning: for example if you have 0 stocks of Siemens " + "in your portfolio, then you can't sell Siemens, first you need to buy it."); JLabel label5 = new JLabel("Often, there is a problem with the Yahoo's server. Thats the reason why buying or " + "selling value is calculated so slowly (because new price is lagging), or even the whole row is empty for a " + "few seconds (because data is lagging"); JLabel label6 = new JLabel("Info: every transaction will be saved in the database (Postgres, local) and in the tables: " + "portfolio and transactions."); JLabel label7 = new JLabel("Just an info: trading hours for most of the major European stock markets are between 09:00 " + "- 17:30 CET. Yahoo finance publishes data with 15 minutes delay."); JLabel label8 = new JLabel("This is just a small piece of the real securities trading platform. It can be further upgraded."); JPanel panel = new JPanel(new GridLayout(0, 1)); panel.add(label1); panel.add(label2); panel.add(label3); panel.add(label4); panel.add(label5); panel.add(label6); panel.add(label7); panel.add(label8); frame.add(panel, BorderLayout.SOUTH); // This is for the tabs JTabbedPane tabbedPane = new JTabbedPane(); tabbedPane.addTab("Trading", new JScrollPane(tableTrading)); tabbedPane.addTab("Portfolio", new JScrollPane(tablePortfolio)); tabbedPane.addTab("Transactions", new JScrollPane(tableTransactions)); frame.add(tabbedPane, BorderLayout.CENTER); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Sets this window to the full screen size frame.setExtendedState(frame.getExtendedState() | JFrame.MAXIMIZED_BOTH); // Display the window frame.pack(); frame.setVisible(true); MySwingWorker sw = new MySwingWorker(modelPortfolio); sw.execute(); } public static void main(String[] args) { // Schedule a job for the event-dispatching thread: // creating and showing this application's GUI javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); for (int i = 0; i < TableTrading.rowNamesLength; i++) { // Create and start threads new Thread(new MyRunnable(TableTrading.rowNames[i], i, modelTrading)).start(); } } }
package com.insta.entities; // Generated Aug 2, 2015 3:40:21 PM by Hibernate Tools 4.3.1 import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * InstaImageLikes generated by hbm2java */ @Entity @Table(name = "insta_image_likes", schema = "public") public class InstaImageLikes implements java.io.Serializable { private long imageLikesId; private InstaImage instaImage; private int likesNumber; private long userId; private Date ratingCreatedDate; public InstaImageLikes() { } public InstaImageLikes(long imageLikesId, InstaImage instaImage, int likesNumber, long userId, Date ratingCreatedDate) { this.imageLikesId = imageLikesId; this.instaImage = instaImage; this.likesNumber = likesNumber; this.userId = userId; this.ratingCreatedDate = ratingCreatedDate; } @Id @Column(name = "image_likes_id", unique = true, nullable = false) public long getImageLikesId() { return this.imageLikesId; } public void setImageLikesId(long imageLikesId) { this.imageLikesId = imageLikesId; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "image_id", nullable = false) public InstaImage getInstaImage() { return this.instaImage; } public void setInstaImage(InstaImage instaImage) { this.instaImage = instaImage; } @Column(name = "likes_number", nullable = false) public int getLikesNumber() { return this.likesNumber; } public void setLikesNumber(int likesNumber) { this.likesNumber = likesNumber; } @Column(name = "user_id", nullable = false) public long getUserId() { return this.userId; } public void setUserId(long userId) { this.userId = userId; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "rating_created_date", nullable = false, length = 29) public Date getRatingCreatedDate() { return this.ratingCreatedDate; } public void setRatingCreatedDate(Date ratingCreatedDate) { this.ratingCreatedDate = ratingCreatedDate; } }
//Pass a pointer (reference) back to the current object public class ThisKeyword3 { private SomeClass anotherObject = new SomeClass(); //classe aleatória //anotherObject -> SomeClass #2nd public static void main(String[] args) { ThisKeyword3 anObject = new ThisKeyword3(); //anObject -> ThisKeyword3 #1st anObject.methodTwo(); } public void methodTwo() { anotherObject.someMethod(this); //anotherObject -> anObject; anObject.var -> anotherObject #3rd } //anotherObject (e) }
/* * Sonar Flex Plugin * Copyright (C) 2010 SonarSource * dev@sonar.codehaus.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.plugins.flex; import org.sonar.api.Extension; import org.sonar.api.Plugin; import org.sonar.api.Properties; import org.sonar.api.Property; import org.sonar.plugins.flex.cobertura.FlexCoberturaSensor; import org.sonar.plugins.flex.colorizer.FlexColorizerFormat; import org.sonar.plugins.flex.cpd.FlexCpdMavenPluginHandler; import org.sonar.plugins.flex.cpd.FlexCpdMavenSensor; import org.sonar.plugins.flex.flexmetrics.FlexMetricsMavenPluginHandler; import org.sonar.plugins.flex.flexmetrics.FlexMetricsSensor; import org.sonar.plugins.flex.flexpmd.*; import org.sonar.plugins.flex.squid.FlexNoSonarFilter; import org.sonar.plugins.flex.squid.FlexSquidSensor; import org.sonar.plugins.flex.surefire.FlexMojosMavenPluginHandler; import org.sonar.plugins.flex.surefire.FlexSurefireSensor; import java.util.ArrayList; import java.util.List; @Properties({ @Property( key = FlexPlugin.FILE_SUFFIXES_KEY, defaultValue = FlexPlugin.FILE_SUFFIXES_DEFVALUE, name = "File suffixes", description = "Comma-separated list of suffixes for files to analyze. To not filter, leave the list empty.", global = true, project = true) }) public class FlexPlugin implements Plugin { static final String FILE_SUFFIXES_KEY = "sonar.flex.file.suffixes"; static final String FILE_SUFFIXES_DEFVALUE = "as"; public String getKey() { return "flex"; } public String getName() { return "Flex"; } public String getDescription() { return "Analysis of Flex projects"; } public List<Class<? extends Extension>> getExtensions() { List<Class<? extends Extension>> list = new ArrayList<Class<? extends Extension>>(); list.add(FlexColorizerFormat.class); list.add(Flex.class); list.add(FlexNoSonarFilter.class); list.add(FlexSourceImporter.class); list.add(FlexCpdMavenSensor.class); list.add(FlexCpdMavenPluginHandler.class); list.add(FlexMetricsMavenPluginHandler.class); list.add(FlexMetricsSensor.class); list.add(FlexPmdSensor.class); list.add(FlexPmdMavenPluginHandler.class); list.add(FlexPmdRuleRepository.class); list.add(DefaultFlexProfile.class); list.add(FlexPmdProfileExporter.class); list.add(FlexPmdProfileImporter.class); list.add(FlexSurefireSensor.class); list.add(FlexMojosMavenPluginHandler.class); list.add(FlexCoberturaSensor.class); list.add(FlexSquidSensor.class); return list; } }
package com.study.hystrix.service; import org.springframework.stereotype.Service; import java.util.*; /** * リモートインターフェース */ @Service public class QueryServiceRemoteCall { /** * 単一処理 * @param code * @return */ public HashMap<String, Object> queryCommodityByCode(String code) { try { Thread.sleep(50L); } catch (InterruptedException e) { e.printStackTrace(); } HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put("commodityId", new Random().nextInt(999999999)); hashMap.put("code", code); hashMap.put("phone", "huawei"); hashMap.put("isOk", "true"); hashMap.put("price","4000"); return hashMap; } /** * 一括処理 * * @param codes * @return */ public List<Map<String, Object>> queryCommodityByCodeBatch(List<String> codes) { // 不支持批量查询 http://moviewapi.com/query.do?id=10001 --> {code:10001, star:xxxx.....} // http://moviewapi.com/query.do?ids=10001,10002,10003,10004 --> [{code:10001, star///}, {...},{....}] List<Map<String, Object>> result = new ArrayList<>(); for (String code : codes) { HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put("commodityId", new Random().nextInt(999999999)); hashMap.put("code", code); hashMap.put("phone", "huawei"); hashMap.put("isOk", "true"); hashMap.put("price","4000"); result.add(hashMap); } return result; } }
package usantatecla.mastermind.models; import java.util.ArrayList; import java.util.List; class GameMemento { private List<ProposedCombination> proposedCombinations; public GameMemento(List<ProposedCombination>proposedCombinations) { this.proposedCombinations = new ArrayList<>(); for (ProposedCombination proposedCombination : proposedCombinations) { this.proposedCombinations.add(proposedCombination.copy()); } } public List<ProposedCombination> getProposedCombinations() { return proposedCombinations; } public void setProposedCombinations(List<ProposedCombination> proposedCombinations) { this.proposedCombinations = proposedCombinations; } public List<Result> getResults(SecretCombination secretCombination) { List<Result> results = new ArrayList<>(); for(ProposedCombination proposedCombination : proposedCombinations){ results.add(secretCombination.getResult(proposedCombination)); } return results; } }
package com.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import com.model.Product; import com.util.StringUtil; public class ProductDao { public int productAdd(Connection con,Product product)throws Exception{ String sql="insert into t_product values(null,?,?,?,?,?)"; PreparedStatement pstmt=con.prepareStatement(sql); pstmt.setString(1, product.getProductName()); pstmt.setString(2,product.getProductTime()); pstmt.setFloat(3, product.getPrice()); pstmt.setString(4, product.getProductDesc()); pstmt.setInt(5, product.getProductTypeId()); return pstmt.executeUpdate(); } public int productAddIntoCar(Connection con,Product product)throws Exception{ String sql="insert into t_productchosen values(null,?,?,?,?,?)"; PreparedStatement pstmt=con.prepareStatement(sql); pstmt.setString(1, product.getProductName()); pstmt.setString(2,product.getProductTime()); pstmt.setFloat(3, product.getPrice()); pstmt.setString(4, product.getProductDesc()); pstmt.setInt(5, product.getProductTypeId()); return pstmt.executeUpdate(); } //如果是罗列的话,只需con就行了 public ResultSet productList(Connection con,Product product)throws Exception{ StringBuffer sb=new StringBuffer("select * from t_product p,t_productType pt where p.productTypeId=pt.id "); if(StringUtil.isNotEmtpty(product.getProductName())){ sb.append(" and p.productName like '%"+product.getProductName()+"%'"); }//查询语句的经典算法, 设置数据文件的搜索路径append if(StringUtil.isNotEmtpty(product.getProductTime())){ sb.append(" and p.productTime like '%"+product.getProductTime()+"%'"); }//查询语句的经典算法, 设置数据文件的搜索路径append if(product.getProductTypeId()!=-1){ sb.append(" and p.productTypeId ="+product.getProductTypeId()); }//查询语句的经典算法, 设置数据文件的搜索路径append PreparedStatement pstmt=con.prepareStatement(sb.toString()); return pstmt.executeQuery(); } public ResultSet productChosenList(Connection con)throws Exception{ String sql="select * from t_productchosen p,t_productType pt where p.productTypeId=pt.id "; PreparedStatement pstmt=con.prepareStatement(sql); return pstmt.executeQuery(); } public int productDelete(Connection con,String id)throws Exception{ String sql="delete from t_product where id=?"; PreparedStatement pstmt=con.prepareStatement(sql); pstmt.setString(1, id); return pstmt.executeUpdate(); } public int productChosenDelete(Connection con,String id)throws Exception{ String sql="delete from t_productchosen where id=?"; PreparedStatement pstmt=con.prepareStatement(sql); pstmt.setString(1, id); return pstmt.executeUpdate(); } public int productModify(Connection con,Product product)throws Exception{ String sql="update t_product set productName=?,productTime=?,price=?,productDesc=?,productTypeId=? where id=?"; PreparedStatement pstmt=con.prepareStatement(sql); pstmt.setString(1, product.getProductName()); pstmt.setString(2, product.getProductTime()); pstmt.setFloat(3, product.getPrice()); pstmt.setString(4, product.getProductDesc()); pstmt.setInt(5, product.getProductTypeId()); pstmt.setInt(6, product.getId()); return pstmt.executeUpdate(); } public boolean getProductByProductTypeId(Connection con,String productTypeId)throws Exception{ String sql="select * from t_product where productTypeId=?"; PreparedStatement pstmt=con.prepareStatement(sql); pstmt.setString(1, productTypeId); ResultSet rs=pstmt.executeQuery(); return rs.next(); } }
package com.twu.model; import com.twu.infrastructure.ManageBooks; public class Book { private double index; private String title; private String author; private int publicationYear; private boolean available; public Book(double index, String title, String author, int publicationYear, boolean available) { this.index = index; this.title = title; this.author = author; this.publicationYear = publicationYear; this.available = available; ManageBooks.addBookToList(this); } public String getTitle() { return title; } public String getAuthor() { return author; } public int getPublicationYear() { return publicationYear; } public boolean getAvailable() { return available; } public void setIndex(double newIndex) { this.index = newIndex; } public void setAvailable(boolean availabilty) { this.available = availabilty; } }
package com.travelportal.domain.rooms; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import play.db.jpa.JPA; @Entity @Table(name="free_stay") public class FreeStay { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @Column(name="type_free_stay") private String typeFreeStay; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTypeFreeStay() { return typeFreeStay; } public void setTypeFreeStay(String typeFreeStay) { this.typeFreeStay = typeFreeStay; } public static List<FreeStay> getFreeStay() { return JPA.em().createQuery("select c.typeFreeStay from FreeStay c ").getResultList(); } public static FreeStay getFreeStayByName(String name) { return (FreeStay) JPA.em() .createQuery("select c from FreeStay c where c.typeFreeStay = ?1") .setParameter(1, name).getSingleResult(); } }
package org.christophe.marchal.redis.client.jedis.utils; //---------------------------------------------------------- //Compute square root of large numbers using Heron's method //---------------------------------------------------------- import java.math.*; public class BigSquareRoot { private static BigDecimal ZERO = new BigDecimal ("0"); private static BigDecimal ONE = new BigDecimal ("1"); private static BigDecimal TWO = new BigDecimal ("2"); public static final int DEFAULT_MAX_ITERATIONS = 50; public static final int DEFAULT_SCALE = 10; private BigDecimal error; private int iterations; private boolean traceFlag; private int scale = DEFAULT_SCALE; private int maxIterations = DEFAULT_MAX_ITERATIONS; //--------------------------------------- // The error is the original number minus // (sqrt * sqrt). If the original number // was a perfect square, the error is 0. //--------------------------------------- public BigDecimal getError () { return error; } //------------------------------------------------------------- // Number of iterations performed when square root was computed //------------------------------------------------------------- public int getIterations () { return iterations; } //----------- // Trace flag //----------- public boolean getTraceFlag () { return traceFlag; } public void setTraceFlag (boolean flag) { traceFlag = flag; } //------ // Scale //------ public int getScale () { return scale; } public void setScale (int scale) { this.scale = scale; } //------------------- // Maximum iterations //------------------- public int getMaxIterations () { return maxIterations; } public void setMaxIterations (int maxIterations) { this.maxIterations = maxIterations; } //-------------------------- // Get initial approximation //-------------------------- private static BigDecimal getInitialApproximation (BigDecimal n) { BigInteger integerPart = n.toBigInteger (); int length = integerPart.toString ().length (); if ((length % 2) == 0) { length--; } length /= 2; BigDecimal guess = ONE.movePointRight (length); return guess; } //---------------- // Get square root //---------------- public BigDecimal get (BigInteger n) { return get (new BigDecimal (n)); } public BigDecimal get (BigDecimal n) { // Make sure n is a positive number if (n.compareTo (ZERO) <= 0) { throw new IllegalArgumentException (); } BigDecimal initialGuess = getInitialApproximation (n); trace ("Initial guess " + initialGuess.toString ()); BigDecimal lastGuess = ZERO; BigDecimal guess = new BigDecimal (initialGuess.toString ()); // Iterate iterations = 0; boolean more = true; while (more) { lastGuess = guess; guess = n.divide(guess, scale, BigDecimal.ROUND_HALF_UP); guess = guess.add(lastGuess); guess = guess.divide (TWO, scale, BigDecimal.ROUND_HALF_UP); trace ("Next guess " + guess.toString ()); error = n.subtract (guess.multiply (guess)); if (++iterations >= maxIterations) { more = false; } else if (lastGuess.equals (guess)) { more = error.abs ().compareTo (ONE) >= 0; } } return guess; } //------ // Trace //------ private void trace (String s) { if (traceFlag) { System.out.println (s); } } //---------------------- // Get random BigInteger //---------------------- public static BigInteger getRandomBigInteger (int nDigits) { StringBuffer sb = new StringBuffer (); java.util.Random r = new java.util.Random (); for (int i = 0; i < nDigits; i++) { sb.append (r.nextInt (10)); } return new BigInteger (sb.toString ()); } }
package com.slort.model; // Generated by MyEclipse Persistence Tools import java.util.Date; import java.util.Set; /** * Flota generated by MyEclipse Persistence Tools */ public class Flota extends AbstractFlota implements java.io.Serializable { // Constructors /** default constructor */ public Flota() { } /** minimal constructor */ public Flota(Integer codUnidad) { super(codUnidad); } /** full constructor */ public Flota(Integer codUnidad, Byte activo, String userYahoo, String passwYahoo, String nombre, String apellido, String domicilio, String codPostal, String localidad, String telefono, String cargo, String email, Date fechaAlta, Date fechaBaja, String cuit, String licencia, Date fechaModif, Byte fleliminado, Set reservas, Set ubicacionreals, Set historicoubicaciondetalles,String consumerKeyYahoo,String consumerSecretYahoo) { super(codUnidad, activo, userYahoo, passwYahoo, nombre, apellido, domicilio, codPostal, localidad, telefono, cargo, email, fechaAlta, fechaBaja, cuit, licencia, fechaModif, fleliminado, reservas, ubicacionreals, historicoubicaciondetalles,consumerKeyYahoo,consumerSecretYahoo); } }
package org.mge.general; public class OuterClass { private int a = 10; class InnerClass extends OuterClass{ private int b = 20; void showInner() { System.out.println("Outer.a=" + OuterClass.this.a); } } void shouOuter() { InnerClass in = new InnerClass(); System.out.println(in.b); } } class OuterInner { public static void main(String[] args) { OuterClass o = new OuterClass(); o.shouOuter(); OuterClass.InnerClass in = o.new InnerClass(); in.showInner(); } }
package heap; import array.Array; public class MaxHeap<E extends Comparable<E>> { private Array<E> date; public MaxHeap() { this.date = new Array<>(); } public MaxHeap(int capacity) { this.date = new Array<>(capacity); } public MaxHeap(E [] arr) { this.date = date; } private int parent(int index){ return (index - 1) / 2; } private int leftChild(int index){ return index * 2 + 1; } private int rightChild(int index){ return index * 2 + 2; } private void siftDown(int index){ if (index >= date.getSize() - 1) return; int left = leftChild(index); int right = rightChild(index); if(date.get(index).compareTo(date.get(left)) < 0){ date.swap(index, left); siftDown(left); }else { if(date.get(index).compareTo(date.get(right)) < 0){ //swap date.swap(index, right); siftDown(right); }else return; } } }
package com.cloudera.oryx.common.lang; import java.io.Closeable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sun.rmi.runtime.Log; public class JVMUtils { private static final Logger log = LoggerFactory.getLogger(JVMUtils.class); private static final OryxShutdownHook SHUTDOWN_HOOK = new OryxShutdownHook(); private JVMUtils() {} public static void closeAtShutdown(Closeable closeable) { if (SHUTDOWN_HOOK.addCloseable(closeable)) { try { Runtime.getRuntime().addShutdownHook(new Thread(SHUTDOWN_HOOK, "OryxShutdownHookThread")); } catch (IllegalStateException ise) { log.warn("Cant close {} at shutdown since it's in progress", closeable); } } } }
package com.company.domains; import com.company.exceptions.snakeNotFoundException; import java.util.HashMap; public class Snake { int id=0; HashMap<Integer,Pair> snakes; public Snake(){ snakes=new HashMap<>(); id=0; } public void addSnake(int start,int end){ snakes.put(id,new Pair(start,end)); id++; } public void deleteSnake(int id) throws snakeNotFoundException { if(snakes.get(id)==null)throw new snakeNotFoundException("Snake id not found"); snakes.remove(id); } public HashMap<Integer,Pair> getSnakeList(){ return snakes; } }
package mop.test.java.backend.utilities; import java.io.File; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; public class FileTest { @Test public void testFileExistsReturnsTrue() { boolean fileExists = mop.main.java.backend.utilities.File.exists("src/mop/test/resources/ReadonlyTestConfig.xml"); assertTrue(fileExists); } @Test public void testFileExistsReturnsFalse() { boolean fileExists = mop.main.java.backend.utilities.File.exists("src/mop/test/resources/UnknownFile.xml"); assertFalse(fileExists); } @Test public void testTryGetExistingFileReturnsFile() { File file = mop.main.java.backend.utilities.File.tryGet("src/mop/test/resources/ReadonlyTestConfig.xml"); assertNotNull(file); } @Test public void testTryGetInvalidFilePathReturnsNull() { File file = mop.main.java.backend.utilities.File.tryGet("src/mop/test/resource/UnknownFile.xml"); assertNull(file); } }
/* Nazlee Yahia p1200800 */ public class partieb { public static void main(String[] args) { char poste[] = {'A', 'P', 'O', 'P', 'A', 'P', 'A', 'P'}; int nbCafe[] = {3, 1, 5, 1, 2, 1, 0, 3}; int age[] = {25, 18, 23, 20, 50, 24, 52, 29}; int n = 8; int intr[] = new int[4]; float floatr[] = new float[2]; imprime(poste,nbCafe,age,n); analyse(poste,nbCafe,age,n,intr,floatr); swap(poste,nbCafe,age,n); resultat(intr,floatr); imprime(poste,nbCafe,age,n); } public static void resultat(int[] intr, float[] floatr) { System.out.println("\n\nNombre de programmeurs: "+ intr[0]); System.out.println("Nombre de secretaires: "+intr[1]); System.out.println("Consommation minimal de cafe des programmeurs: "+intr[2]); System.out.println("Age maximal des analystes: "+intr[3]); System.out.println("Consommation moyenne de cafe des programmeurs: "+floatr[0]); System.out.println("Age moyen de tout les employes: "+floatr[1]); System.out.println("\n"); } public static void swap(char[] poste, int [] nbCafe, int[] age, int n) { int i = 0; int j = 0; int tempint; char tempchar; for (i = 0; i < n; ++i) { for (j = i + 1; j < n; ++j) { if (age[i] > age[j]) { tempint = age[i]; age[i] = age[j]; age[j] = tempint; tempint = nbCafe[i]; nbCafe[i] = nbCafe[j]; nbCafe[j] = tempint; tempchar = poste[i]; poste[i] = poste[j]; poste[j] = tempchar; } } } return; } public static void imprime(char[] poste, int [] nbCafe, int[] age, int n) { int i = 0; for(i = 0; i < n; i++){ System.out.println("Poste: "+poste[i]+"\tnbCafe: "+nbCafe[i]+"\tAge: "+age[i]); } return; } public static void analyse(char[] poste, int [] nbCafe, int[] age, int n, int[] intr, float[] floatr) { int deux = 0, trois = 0, quatre = 10, cinq = 0; float six = 0, sept = 0; int i =0; for(i = 0; i < n; i++){ switch(poste[i]){ case 'A': if(age[i]>cinq){ cinq = age[i]; } break; case 'O': break; case 'P': deux = deux + 1; if(nbCafe[i] < quatre){ quatre = nbCafe[i]; } six += nbCafe[i]; break; case 'S': trois = trois +1; break; } sept += age[i]; } six = six / deux; sept = sept / n; intr[0] = deux; intr[1] = trois; intr[2] = quatre; intr[3] = cinq; floatr[0] = six; floatr[1] = sept; return; } } /*Resultat Poste: A nbCafe: 3 Age: 25 Poste: P nbCafe: 1 Age: 18 Poste: O nbCafe: 5 Age: 23 Poste: P nbCafe: 1 Age: 20 Poste: A nbCafe: 2 Age: 50 Poste: P nbCafe: 1 Age: 24 Poste: A nbCafe: 0 Age: 52 Poste: P nbCafe: 3 Age: 29 Nombre de programmeurs: 4 Nombre de secretaires: 0 Consommation minimal de cafe des programmeurs: 1 Age maximal des analystes: 52 Consommation moyenne de cafe des programmeurs: 1.5 Age moyen de tout les employes: 30.125 Poste: P nbCafe: 1 Age: 18 Poste: P nbCafe: 1 Age: 20 Poste: O nbCafe: 5 Age: 23 Poste: P nbCafe: 1 Age: 24 Poste: A nbCafe: 3 Age: 25 Poste: P nbCafe: 3 Age: 29 Poste: A nbCafe: 2 Age: 50 Poste: A nbCafe: 0 Age: 52 */
/** * Copyright (C) 2012 Jacob Scott <jascottytechie@gmail.com> * Description: ( TODO ) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.jascotty2.countdownsync.client; import java.util.HashMap; import java.util.Map; public class ClientList { private final Map<String, ClientData> list = new HashMap<String, ClientData>(); public ClientData[] getList() { return list.values().toArray(new ClientData[0]); } public void addClient(String nick) { list.put(nick, new ClientData(nick)); } public void addClient(ClientData c) { if (c != null) { list.put(c.nick, c); } } public void removeClient(String nick) { list.remove(nick); } public ClientData getClient(String nick) { return list.get(nick); } public ClientData getClient(int index) { if (index < 0 || index >= list.size()) { throw new IndexOutOfBoundsException("Index out of bounds: " + index); } return list.values().toArray(new ClientData[0])[index]; } public void clear() { list.clear(); } public int size() { return list.size(); } }
package org.fhcrc.honeycomb.metapop.coordinate; import org.fhcrc.honeycomb.metapop.coordinate.Coordinate; /** * Created on 10 Apr, 2013. * @author Adam Waite * @version $Rev: 1925 $, $Date: 2013-04-12 11:26:27 -0700 (Fri, 12 Apr 2013) $ * */ public interface CoordinateProvider { int getMaxRow(); int getMaxCol(); Coordinate getCoordinate(); }
package com.example.guanghuili.checkesandchess.ChessPractice; //import Piece; import java.util.ArrayList; import java.util.List; public class King extends Piece { private List<Point> moves = new ArrayList<>(); public King(Boolean isBlack, int row, int column){ super(isBlack,row,column); this.row = row; this.column = column; } public int[][] getDirections(){ int[][] x = {{1,1,1},{1,0,1},{1,1,1}}; return x; } //************************************************************************* //This method will let us check if the king is in danger(Checked) //************************************************************************* public boolean isChecked(Piece board[][]) { //Check up for (int i = row + 1; i < 8; i++) { if (board[i][column] == null) continue; else if (board[i][column].isBlack() == this.isBlack()) break; else { if ((board[i][column] instanceof Rook) || (board[i][column] instanceof Queen)) return true; else break; } } //Check down for (int i = row - 1; i >= 0; i--) { if (board[i][column] == null) continue; else if (board[i][column].isBlack() == this.isBlack()) break; else { if ((board[i][column] instanceof Rook) || (board[i][column] instanceof Queen)) return true; else break; } } //check right for (int i = column + 1; i < 8; i++) { if (board[row][i] == null) continue; else if (board[row][i].isBlack() == this.isBlack()) break; else { if ((board[row][i] instanceof Rook) || (board[row][i] instanceof Queen)) return true; else break; } } //check left for (int i = column - 1; i >= 0; i--) { if (board[row][i] == null) continue; else if (board[row][i].isBlack() == this.isBlack()) break; else { if ((board[row][i] instanceof Rook) || (board[row][i] instanceof Queen)) return true; else break; } } //************************************************************************* //still needs to check diagonal, knights, kings, and pawns //************************************************************************* //Check right-down int tempColumn = column + 1; int tempRow = row - 1; while (tempColumn < 8 && tempRow >= 0) { if (board[tempColumn][tempRow] == null) { tempColumn++; tempRow--; } else if (board[tempColumn][tempRow].isBlack() == this.isBlack()) break; else { if (board[tempColumn][tempRow] instanceof Bishop || board[tempColumn][tempRow] instanceof Queen) return true; else break; } } //check left-up tempColumn = column - 1; tempRow = row + 1; while (tempColumn >= 0 && tempRow < 8) { if (board[tempColumn][tempRow] == null) { tempColumn--; tempRow++; } else if (board[tempColumn][tempRow].isBlack() == this.isBlack()) break; else { if (board[tempColumn][tempRow] instanceof Bishop || board[tempColumn][tempRow] instanceof Queen) return true; else break; } } //check left-down tempColumn = column - 1; tempRow = row - 1; while (tempColumn >= 0 && tempRow >= 0) { if (board[tempColumn][tempRow] == null) { tempColumn--; tempRow--; } else if (board[tempColumn][tempRow].isBlack() == this.isBlack()) break; else { if (board[tempColumn][tempRow] instanceof Bishop || board[tempColumn][tempRow] instanceof Queen) return true; else break; } } //check right-up tempColumn = column + 1; tempRow = row + 1; while (tempColumn < 8 && tempRow < 8) { if (board[tempColumn][tempRow] == null) { tempColumn++; tempRow++; } else if (board[tempColumn][tempRow].isBlack() == this.isBlack()) break; else { if (board[tempColumn][tempRow] instanceof Bishop || board[tempColumn][tempRow] instanceof Queen) return true; else break; } } //************************************************************************* //still needs to check knights and pawns //************************************************************************* int columnPos[] = {column + 1, column + 1, column + 2, column + 2, column - 1, column - 1, column - 2, column - 2}; int rowPos[] = {row-2, row+2, row-1, row+1, row-2, row+2, row-1, row+1}; for (int i = 0; i < 8; i++){ if ((columnPos[i] >= 0 && columnPos[i] < 8 && rowPos[i] >= 0 && rowPos[i] < 8)) { if (board[columnPos[i]][rowPos[i]] != null && board[columnPos[i]][rowPos[i]].isBlack() != this.isBlack() && (board[columnPos[i]][rowPos[i]] instanceof Knight)) { return true; } } } //************************************************************************* //pawns //************************************************************************* if(this.isBlack()){ if((row + 1) < 8){ if(column - 1 >= 0){ if(board[row+1][column - 1] != null){ if(board[row+1][column - 1] instanceof Pawn && !(board[row+1][column - 1].isBlack())){ return true; } } } if(column+1 < 8){ if(board[row+1][column + 1] != null){ if(board[row+1][column + 1] instanceof Pawn && !(board[row+1][column + 1].isBlack())){ return true; } } } } } else{ if((row - 1) >= 0){ if(column - 1 >= 0){ if(board[row+1][column - 1] != null){ if(board[row+1][column - 1] instanceof Pawn && (board[row+1][column - 1].isBlack())){ return true; } } } if(column+1 < 8){ if(board[row+1][column + 1] != null){ if(board[row+1][column + 1] instanceof Pawn && (board[row+1][column + 1].isBlack())){ return true; } } } } } return false; } @Override public List getMoves(Piece[][] board) { moves.clear(); moves = new ArrayList<>(); if(column == 0){ if(row == 0){ right(board); bottomRight(board); bottom(board); } else if(row == 7){ up(board); upperRight(board); right(board); } else{ up(board); upperRight(board); right(board); bottomRight(board); bottom(board); } } else if(column == 7){ if(row == 0){ left(board); bottomLeft(board); bottom(board); } else if(row == 7){ up(board); upperLeft(board); left(board); } else{ up(board); upperLeft(board); left(board); bottomLeft(board); bottom(board); } } else{ if(row == 0){ left(board); bottomLeft(board); bottom(board); bottomRight(board); right(board); } else if(row == 7){ left(board); upperLeft(board); up(board); upperRight(board); right(board); } else{ left(board); upperLeft(board); up(board); upperRight(board); right(board); bottomLeft(board); bottomRight(board); bottom(board); bottomLeft(board); } } return moves; } public void left(Piece[][] board){ //left if(board[row][column - 1] == null || board[row][column - 1].isBlack() != this.isBlack()){ moves.add(new Point(row, column - 1)); } } public void upperLeft(Piece[][]board){ //upper left if(board[row - 1][column - 1] == null || board[row - 1][column - 1].isBlack() != this.isBlack()){ moves.add(new Point(row - 1, column - 1)); } } public void up(Piece[][]board){ //up if(board[row - 1][column] == null || board[row - 1][column].isBlack() != this.isBlack()){ moves.add(new Point(row - 1, column)); } } public void upperRight(Piece[][]board){ //upper right if(board[row - 1][column + 1] == null || board[row - 1][column + 1].isBlack() != this.isBlack()){ moves.add(new Point(row - 1, column + 1)); } } public void right(Piece[][]board){ //right if(board[row][column + 1] == null || board[row][column + 1].isBlack() != this.isBlack()){ moves.add(new Point(row, column + 1)); } } public void bottomRight(Piece[][]board){ //bottom right if(board[row + 1][column + 1] == null || board[row + 1][column + 1].isBlack() != this.isBlack()){ moves.add(new Point(row + 1, column + 1)); } } public void bottom(Piece[][]board){ //bottom if(board[row + 1][column] == null || board[row + 1][column].isBlack() != this.isBlack()){ moves.add(new Point(row + 1, column)); } } public void bottomLeft(Piece[][]board){ //bottom left if(board[row + 1][column - 1] == null || board[row + 1][column - 1].isBlack() != this.isBlack()){ moves.add(new Point(row + 1, column - 1)); } } }
package id3; import shared.*; /* Driver class, used to create,initialize,run inducers */ /** Basic Driver class used to interface the ID3Inducer. * @author James Louis Created implementation. */ public class Driver { /** The main driving function. * @param args Command line arguments. The first argument should be the path to the data * files to be used for training and testing. They should have the same path * name. The second and third options are optional. The second option sets the * log level to the given integer number. The default is 0. The third value is * a boolean variable associated with how categories are displayed. */ public static void main(String[] args) { //try{ ID3Inducer id3 = new ID3Inducer("ID3"); if(args.length < 1) { System.err.print("Error - file base path required."); System.exit(1); } if(args.length == 2) { id3.set_log_level(Integer.parseInt(args[1])); GlobalOptions.logLevel = Integer.parseInt(args[1]); } else { id3.set_log_level(0); GlobalOptions.logLevel = 0; } if(args.length == 3) { AugCategory.MLCBinaryDisplay = Boolean.valueOf(args[2]).booleanValue(); } if(args.length > 3) { System.err.print("Error - Too many arguments."); System.exit(1); } //}catch(Exception e){e.printStackTrace();} InstanceList traindata = new InstanceList(args[0],".names",".data"); // InstanceList traindata = new InstanceList(args[0]); InstanceList testdata = new InstanceList(args[0],".names",".test"); // InstanceList copy = new InstanceList(testdata); boolean[] bitstring = {false, true, false, false}; // InstanceList newtraindata = traindata.project(bitstring); // InstanceList newtestdata = testdata.project(bitstring); // System.out.println("Displaying projected data."); // newtraindata.display(false); //Sets the unknown edge generation option. False indicates no unknown edges. id3.set_unknown_edges(false); System.out.println("The probability of error is: "+id3.train_and_test(traindata,testdata)); //Testing of CHC functions. // System.out.println("The probability of error is: "+id3.project_train_and_test(traindata,testdata,bitstring)); // System.out.println("The probability of error is: "+id3.project_train_and_test_files(args[0],bitstring)); id3.display_struct(); System.out.println("The number of nodes is: " + id3.num_nontrivial_nodes()); System.out.println("The number of leaves is: " + id3.num_nontrivial_leaves()); ID3Inducer blah = new ID3Inducer("Blah"); } }
package com.sunzequn.sdfs.ui; import com.sunzequn.sdfs.file.FileMeta; import com.sunzequn.sdfs.node.NodeInfo; import com.sunzequn.sdfs.rmi.ClientTimeThread; import com.sunzequn.sdfs.rmi.RemoteClient; import com.sunzequn.sdfs.utils.FileUtil; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.UnknownHostException; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.util.List; import static java.lang.Thread.sleep; /** * Created by sloriac on 16-12-19. */ public class UserClientListener implements ActionListener { private JScrollPane upperPanel; private JTextField portTextField; private JButton connectButton; private JLabel infoLabel; private ClientTimeThread clientTimeThread; private int totalUserNum = 0; public UserClientListener(JScrollPane upperPanel, JTextField portTextField, JButton connectButton, JLabel infoLabel) { this.upperPanel = upperPanel; this.portTextField = portTextField; this.connectButton = connectButton; this.infoLabel = infoLabel; } @Override public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); try { switch (command) { case "连接": handleConnectButton(); break; case "登录": handleLoginButton(); break; case "退出": handleExitButton(); break; default: connectButton.setText("连接"); infoLabel.setText("连接已终止"); break; } } catch (Exception ex) { ex.printStackTrace(); infoLabel.setText("连接失败,请重试!"); } } private void handleConnectButton() throws RemoteException { String port = portTextField.getText(); if (!port.equals("") && port.contains(":")) { infoLabel.setText("参数错误,请重试!"); //链接leader请求分配数据节点 RemoteClient remoteClient = new RemoteClient(port); //获得数据节点 String node = null; try { node = remoteClient.getNode(); } catch (Exception e) { e.getCause(); return; } if (node == null) { infoLabel.setText("没有数据节点可用"); return; } totalUserNum = remoteClient.getTotalUserNum(); DataNodeUrl.dataNodeUrl = node; display(remoteClient, port.split(":")[0]); connectButton.setText("登录"); } else { infoLabel.setText("参数错误,请重试!"); } } private void handleLoginButton() throws RemoteException, UnknownHostException, MalformedURLException, NotBoundException { String port = portTextField.getText(); if (!port.equals("") && port.contains(":")) { RemoteClient remoteClient = new RemoteClient(DataNodeUrl.dataNodeUrl); //获取ip注册一下 String ip = remoteClient.getIp(); ip = InetAddress.getLocalHost().getHostAddress(); clientTimeThread.stop(); infoLabel.setText("本地: " + ip + ", 您是系统第" + totalUserNum + "位用户"); List<FileMeta> files = remoteClient.getFiles(); showFiles(files); new Thread(() -> { while (true) { List<FileMeta> files1 = null; try { files1 = remoteClient.getFiles(); if (files1 != null) { showFiles(files1); } Thread.sleep(1000); } catch (Exception e) { e.getCause(); return; } } }).start(); connectButton.setText("退出"); } else { infoLabel.setText("参数错误,请重试!"); } } private void display(RemoteClient remoteClient, String ip) throws RemoteException { clientTimeThread = new ClientTimeThread(remoteClient, infoLabel, ip); clientTimeThread.start(); } private void handleExitButton() { if (DataNodeUrl.dataNodeUrl == null) return; RemoteClient remoteClient = new RemoteClient(DataNodeUrl.dataNodeUrl); remoteClient.exit(); connectButton.setText("连接"); clientTimeThread.stop(); infoLabel.setText(""); } private void showFiles(List<FileMeta> files) { JPanel jPanel = new JPanel(); jPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); jPanel.setLayout(new BoxLayout(jPanel, BoxLayout.Y_AXIS)); for (FileMeta file : files) { JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); JLabel jLabel = new JLabel(); jLabel.setText(FileUtil.getFixedLenString(file.getName() + " " + file.getTimestamp(), 50, ' ')); JButton fileButton = new JButton(); fileButton.setText("下 载"); fileButton.addActionListener(new DownloadListener(upperPanel, file)); panel.add(jLabel); panel.add(fileButton); jPanel.add(panel); } upperPanel.setViewportView(jPanel); } }
package com.uwetrottmann.trakt5.services; import com.uwetrottmann.trakt5.entities.AccessToken; import com.uwetrottmann.trakt5.entities.AccessTokenRefreshRequest; import com.uwetrottmann.trakt5.entities.AccessTokenRequest; import com.uwetrottmann.trakt5.entities.ClientId; import com.uwetrottmann.trakt5.entities.DeviceCode; import com.uwetrottmann.trakt5.entities.DeviceCodeAccessTokenRequest; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.POST; public interface Authentication { @POST("oauth/token") Call<AccessToken> exchangeCodeForAccessToken( @Body AccessTokenRequest tokenRequest ); @POST("oauth/token") Call<AccessToken> refreshAccessToken( @Body AccessTokenRefreshRequest refreshRequest ); /** * Generate new codes to start the device authentication process. * The {@code device_code} and {@code interval} will be used later to poll for the {@code access_token}. * The {@code user_code} and {@code verification_url} should be presented to the user. * @param clientId Application Client Id */ @POST("oauth/device/code") Call<DeviceCode> generateDeviceCode( @Body ClientId clientId ); /** * Use the {@code device_code} and poll at the {@code interval} (in seconds) to check if the user has * authorized you app. Use {@code expires_in} to stop polling after that many seconds, and gracefully * instruct the user to restart the process. * <b>It is important to poll at the correct interval and also stop polling when expired.</b> * * When you receive a {@code 200} success response, save the {@code access_token} so your app can * authenticate the user in methods that require it. The {@code access_token} is valid for 3 months. * Save and use the {@code refresh_token} to get a new {@code access_token} without asking the user * to re-authenticate. * @param deviceCodeAccessTokenRequest Device Code */ @POST("oauth/device/token") Call<AccessToken> exchangeDeviceCodeForAccessToken( @Body DeviceCodeAccessTokenRequest deviceCodeAccessTokenRequest ); }
package jp.co.sakamoto.androidproject.framework.dagger; import android.content.Context; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import jp.co.sakamoto.androidproject.AndroidApplication; @Module class AppModule { @Singleton @Provides Context provideContext(AndroidApplication application) { return application.getApplicationContext(); } }
import java.util.TimeZone; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class BackgroudTask implements ServletContextListener { private ExecutorService executor; public void contextInitialized(ServletContextEvent event) { executor = Executors.newSingleThreadExecutor(); TimeZone.setDefault(TimeZone.getTimeZone("IST")); System.out.println("thread started...."); executor.submit(new BGTask()); } public void contextDestroyed(ServletContextEvent event) { executor.shutdown(); System.out.println("thread stopped!!!"); } }
package com.company.blog.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class MvcConfig implements WebMvcConfigurer { public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/Authorization").setViewName("HomeHTML/authorization"); registry.addViewController("/AdminHome").setViewName("AdminHTML/adminHome"); registry.addViewController("/StaffAccount").setViewName("StaffHTML/staffAccount"); registry.addViewController("/MyAccount").setViewName("ClientHTML/myAccount"); } } /* */ /* package com.company.blog.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class MvcConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/login").setViewName("login"); registry.addViewController("/news").setViewName("news"); } } */
package com.ybg.rbac.resources.domain; import java.io.Serializable; @SuppressWarnings("serial") public class SysColorI implements Serializable { private Integer id; private String colorclass; // 颜色 private String description; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getColorclass() { return colorclass; } public void setColorclass(String colorclass) { this.colorclass = colorclass; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String toString() { return "SysColorI [id=" + id + ", colorclass=" + colorclass + ", description=" + description + "]"; } }
package org.ubiquity; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; /** * Factory for the different kinds of common collections. * Implementing this interface allows you to choose the implementations. * * Date: 24/04/12 * * @author François LAROCHE */ public interface CollectionFactory { /** * Create a new List * @param <T> the type of objects that can be added to the list * @return a new list, for objects of type T */ <T> List <T> newList(); /** * Create a new set * @param <T> the type of objects that can be added to the set * @return a new set, for objects of type T */ <T> Set<T> newSet(); /** * Creates a new map * * @param <K> the type associated to the keys * @param <T> the type associated to the objects * @return a new map */ <K,T> Map<K,T> newMap(); /** * Default collection creation * @param <T> the type of elments to store in the collection * @return a new Collection for objects of type T */ <T>Collection<T> newCollection(); }
package pe.oranch.restaurantroky.request; import com.android.volley.Response; import com.android.volley.toolbox.StringRequest; import java.util.HashMap; import java.util.Map; import pe.oranch.restaurantroky.Config; /** * Created by Daniel on 02/11/2017. */ public class UpdateComidasRequest extends StringRequest { private static final String ACTUALIZAR_COMIDAS_REQUEST_URL= Config.APP_API_URL + Config.ACTUALIZA_COMIDAS; private Map<String,String> params; public UpdateComidasRequest(int estado, int comida, Response.Listener<String> listener){ super(Method.POST, ACTUALIZAR_COMIDAS_REQUEST_URL,listener,null); params = new HashMap<>(); params.put ("tay_asoc_estado",estado+""); params.put ("tay_asoc_tipc_id",comida+""); } @Override public Map<String, String> getParams() { return params; } }
package com.tencent.mm.plugin.game.ui; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.game.a.b; import com.tencent.mm.plugin.game.model.v; class GameCenterBaseUI$1 implements Runnable { final /* synthetic */ GameCenterBaseUI jVk; GameCenterBaseUI$1(GameCenterBaseUI gameCenterBaseUI) { this.jVk = gameCenterBaseUI; } public final void run() { GameCenterBaseUI.a(this.jVk); if (this.jVk.jVe) { GameCenterBaseUI.b(this.jVk); ((b) g.l(b.class)).aSi(); v.aUa(); } } }
package de.unitrier.st.soposthistory.gt.GroundTruthApp; import de.unitrier.st.soposthistory.gt.util.GTLogger; import net.miginfocom.swing.MigLayout; import org.sotorrent.posthistoryextractor.blocks.CodeBlockVersion; import org.sotorrent.posthistoryextractor.blocks.TextBlockVersion; import org.sotorrent.posthistoryextractor.gt.PostBlockLifeSpan; import org.sotorrent.posthistoryextractor.gt.PostBlockLifeSpanVersion; import org.sotorrent.posthistoryextractor.history.Posts; import org.sotorrent.posthistoryextractor.version.PostVersion; import org.sotorrent.posthistoryextractor.version.PostVersionList; import javax.swing.*; import javax.swing.event.MouseInputAdapter; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.io.File; import java.io.FilenameFilter; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.List; import java.util.logging.Level; class ButtonsAndInstructionsPanel extends JPanel { private GroundTruthCreator groundTruthCreator; /***** Swing components *****/ private JButton buttonRequestSpecialPost = new JButton("request post"); private JTextField textFieldRequestSpecialPost = new JTextField(""); private JButton buttonRequestRandomPost = new JButton("random post"); private JButton buttonLoadPost = new JButton("load post"); private JButton buttonSaveAllAndCloseThisVersion = new JButton("save/close"); private JButton buttonResetAll = new JButton("reset all/start"); private JButton buttonNext = new JButton("next"); private JButton buttonBack = new JButton("back"); private JPanel buttonsIntern = new JPanel(new MigLayout()); private JButton buttonSwitchConnectionDisplayMode = new JButton("switch link GUI"); private JButton buttonAddComment = new JButton("add comment"); private JButton buttonRemoveComment = new JButton("remove comment"); private JScrollPane savedCommentsScrollPane; private JLabel labelSavedComments = new JLabel(""); static LinkedList<String> comments = new LinkedList<>(); private static final Color tooltipColor = new Color(255, 255, 150); /***** Internal variables *****/ Robot bot = null; /***** Constructor *****/ ButtonsAndInstructionsPanel(GroundTruthCreator groundTruthCreator) { this.setLayout(new MigLayout()); this.groundTruthCreator = groundTruthCreator; this.getButtonsAndInstructionsOnPanel(); this.setToolTips(); this.setListenersToButtons(); this.buttonNext.setFocusable(false); // https://stackoverflow.com/a/8074326 this.buttonBack.setFocusable(false); // https://stackoverflow.com/a/8074326 try { bot = new Robot(); } catch (AWTException e) { e.printStackTrace(); } paintCommentPanel(); } /***** Methods *****/ private void getButtonsAndInstructionsOnPanel(){ textFieldRequestSpecialPost.setColumns(10); // https://stackoverflow.com/questions/14805124/how-to-set-the-height-and-the-width-of-a-textfield-in-java buttonsIntern.add(buttonRequestSpecialPost); buttonsIntern.add(textFieldRequestSpecialPost, "wrap"); buttonsIntern.add(buttonRequestRandomPost); buttonsIntern.add(buttonLoadPost, "wrap"); buttonsIntern.add(buttonSwitchConnectionDisplayMode, "wrap"); buttonsIntern.add(buttonResetAll); buttonsIntern.add(buttonSaveAllAndCloseThisVersion, "wrap"); buttonsIntern.add(buttonBack); buttonsIntern.add(buttonNext); buttonsIntern.setLocation(groundTruthCreator.mainPanel.getWidth()/2, groundTruthCreator.mainPanel.getHeight()/2); this.add(buttonsIntern); JLabel instructionsLabel = new JLabel( "<html>" + "<head/>" + "<body>" + "<ul>" + "<li>If you click at a block b (text blocks are blue, code blocks are orange) of one version you mark b</li>" + "<li>If you click this (now pink) block again you umark it.</li>" + "<li>If a block is marked and you click another block of the opposite version<br>" + "you create a link between blocks of two versions.</li>" + "<li>If you click 'next' but there are some blocks left unmarked (orange) those blocks will be set as new/deleted.</li>" + "</ul>" + "</body>" + "</html>."); instructionsLabel.setFont(new Font("courier new", Font.PLAIN, 12)); JPanel instructionsPanel = new JPanel(); instructionsPanel.setBackground(new Color(205, 255, 220)); instructionsPanel.add(instructionsLabel); this.add(instructionsPanel); JPanel commentsContainer = new JPanel(new MigLayout( "", "[grow]", "[][grow]")); commentsContainer.setPreferredSize(new Dimension(GroundTruthCreator.WIDTH*100/1000, GroundTruthCreator.HEIGHT*150/1000)); savedCommentsScrollPane = new JScrollPane(labelSavedComments, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); savedCommentsScrollPane.getViewport().setBackground(Color.WHITE); // https://stackoverflow.com/a/18362310 savedCommentsScrollPane.setOpaque(true); commentsContainer.add(buttonAddComment); commentsContainer.add(buttonRemoveComment, "wrap"); commentsContainer.add(savedCommentsScrollPane, "grow, span 2"); this.add(commentsContainer); } private void setToolTips(){ ToolTipManager.sharedInstance().setDismissDelay(Integer.MAX_VALUE); // https://stackoverflow.com/questions/1190290/set-the-tooltip-delay-time-for-a-particular-component-in-java-swing UIManager.put("ToolTip.background", tooltipColor); // https://stackoverflow.com/questions/7807411/how-to-change-the-background-color-of-a-jtooltip-using-nimbus-lookandfeel buttonRequestRandomPost.setToolTipText("A random post from stack overflow will be displayed."); buttonLoadPost.setToolTipText("Loads a post with its set links"); buttonSwitchConnectionDisplayMode.setToolTipText("Switch the gui for block links from egdes to films"); buttonAddComment.setToolTipText("Add a comment to block e.g. because of multiple choices."); buttonRemoveComment.setToolTipText("Remove a comment by choosing its id."); buttonRequestSpecialPost.setToolTipText("Requests the post with the id on the right."); textFieldRequestSpecialPost.setToolTipText("You can enter here the id of the post you want to work with. Request it with the button 'request post.'"); buttonSaveAllAndCloseThisVersion.setToolTipText("Your links will be saved and this post will be closed."); buttonResetAll.setToolTipText("Your links of this post will be reset. Then you can start it from beginning again."); buttonNext.setToolTipText("The next two versions of this post will be shown."); buttonBack.setToolTipText("The previous two versions of this post will be shown."); } void setEnablingOfNextAndBackButton(){ buttonResetAll.setEnabled(groundTruthCreator.postVersionList != null); buttonSaveAllAndCloseThisVersion.setEnabled( groundTruthCreator.postVersionList != null && !(groundTruthCreator.currentLeftVersion + 1 < groundTruthCreator.postVersionList.size() - 1) ); buttonNext.setEnabled( groundTruthCreator.postVersionList != null && groundTruthCreator.currentLeftVersion + 1 != groundTruthCreator.postVersionList.size() - 1 ); buttonBack.setEnabled( groundTruthCreator.postVersionList != null && groundTruthCreator.currentLeftVersion != 0 ); } void actionButtonNext(){ if(!buttonNext.isEnabled()) return; if(groundTruthCreator.allCreatedBlockPairsByClicks.get(groundTruthCreator.currentLeftVersion).size() < Math.min( groundTruthCreator.postVersionList.get(groundTruthCreator.currentLeftVersion).getPostBlocks().size(), groundTruthCreator.postVersionList.get(groundTruthCreator.currentLeftVersion+1).getPostBlocks().size())){ // https://stackoverflow.com/a/1395844 Object[] options = {"Yes", "No"}; int procedure = JOptionPane.showOptionDialog( null, "There are still some text and/or code blocks that are NOT linked yet.\n" + "Blocks on the left side will be marked as last blocks.\n" + "Blocks on the right side will be marked as new appearing blocks.\n" + "Do you wish to continue and compare next two version?", "More blocks could be linked", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); if(procedure != JOptionPane.YES_OPTION) return; } if (groundTruthCreator.currentLeftVersion + 1 < groundTruthCreator.postVersionList.size() - 1) { groundTruthCreator.currentLeftVersion++; groundTruthCreator.unmarkLastClickedBlock(); setEnablingOfNextAndBackButton(); groundTruthCreator.displayCurrentTwoVersionsAndNavigator(); } scrollUpToTop(); } void actionButtonBack(){ if(!buttonBack.isEnabled()) return; if (groundTruthCreator.currentLeftVersion > 0) { groundTruthCreator.currentLeftVersion--; groundTruthCreator.unmarkLastClickedBlock(); setEnablingOfNextAndBackButton(); groundTruthCreator.displayCurrentTwoVersionsAndNavigator(); } scrollUpToTop(); } private void scrollUpToTop(){ groundTruthCreator.scrollPaneIncludingMainPanel.getVerticalScrollBar().setValue(0); // https://stackoverflow.com/a/291753 } private void loadPost(int postId){ try { groundTruthCreator.dispose(); System.gc(); groundTruthCreator.postVersionList = PostVersionList.readFromCSV(GroundTruthCreator.path, postId, Posts.ANSWER_ID); groundTruthCreator = new GroundTruthCreator( groundTruthCreator.postVersionList, GroundTruthCreator.WIDTH, GroundTruthCreator.HEIGHT, GroundTruthCreator.LOCATION); comments.clear(); setEnablingOfNextAndBackButton(); paintCommentPanel(); groundTruthCreator.displayCurrentTwoVersionsAndNavigator(); }catch (Exception e) { JOptionPane.showMessageDialog(null, "Failed to load post with post-id " + groundTruthCreator.postVersionList.getFirst().getPostId()); System.exit(0); } } private void setListenersToButtons(){ buttonNext.addMouseListener(new MouseInputAdapter() { @Override public void mouseReleased(MouseEvent e) { super.mouseReleased(e); actionButtonNext(); } }); buttonBack.addMouseListener(new MouseInputAdapter() { @Override public void mouseReleased(MouseEvent e) { super.mouseReleased(e); actionButtonBack(); } }); buttonResetAll.addMouseListener(new MouseInputAdapter() { @Override public void mouseReleased(MouseEvent e) { super.mouseReleased(e); if(!buttonResetAll.isEnabled()) return; loadPost(groundTruthCreator.postVersionList.get(0).getPostId()); } }); buttonRequestSpecialPost.addMouseListener(new MouseInputAdapter() { @Override public void mouseReleased(MouseEvent e) { super.mouseReleased(e); int requestedPostId = Integer.parseInt(textFieldRequestSpecialPost.getText()); loadPost(requestedPostId); } }); buttonRequestRandomPost.addMouseListener(new MouseInputAdapter() { @Override public void mouseReleased(MouseEvent e) { super.mouseReleased(e); File file = new File(GroundTruthCreator.path.toString()); File[] allPostVersionListsInFolder = file.listFiles(new FilenameFilter() { //https://stackoverflow.com/questions/4852531/find-files-in-a-folder-using-java public boolean accept(File dir, String name) { return !name.contains("completed") && name.endsWith(".csv"); } }); File[] allCompletedPostVersionListsInFolder = file.listFiles(new FilenameFilter() { // https://stackoverflow.com/questions/4852531/find-files-in-a-folder-using-java public boolean accept(File dir, String name) { return name.contains("completed") && name.endsWith(".csv"); } }); LinkedList<Integer> postVersionListCandidatesThatNeedToBeDone = new LinkedList<>(); for (File tmpCsvFile : allPostVersionListsInFolder) { int tmpPostId_postVersionLists = Integer.parseInt(tmpCsvFile.toString().substring(17, tmpCsvFile.toString().length() - 4)); boolean fileIsAlreadyCompleted = false; for (File tmpCompletedCsvFile : allCompletedPostVersionListsInFolder) { int tmpPostId_completed = Integer.parseInt(tmpCompletedCsvFile.toString().substring(16 + 11, tmpCompletedCsvFile.toString().length() - 4)); if (tmpPostId_postVersionLists == tmpPostId_completed) { fileIsAlreadyCompleted = true; break; } } if (!fileIsAlreadyCompleted) postVersionListCandidatesThatNeedToBeDone.add(tmpPostId_postVersionLists); } if(postVersionListCandidatesThatNeedToBeDone.isEmpty()){ GTLogger.logger.log(Level.INFO, "All post version lists has been linked."); JOptionPane.showMessageDialog(null, "All post version lists has been linked."); return; } Collections.shuffle(postVersionListCandidatesThatNeedToBeDone); loadPost(postVersionListCandidatesThatNeedToBeDone.getFirst()); } }); buttonAddComment.addMouseListener(new MouseInputAdapter() { // https://stackoverflow.com/a/6555051 http://home.wlu.edu/~lambertk/BreezySwing/radiobuttons.html @Override public void mouseReleased(MouseEvent e) { super.mouseReleased(e); if(groundTruthCreator.postVersionList == null){ JOptionPane.showMessageDialog(null, "You need to select a post version list first."); return; } JPanel dialog = new JPanel(new MigLayout()); JComboBox<String> leftOrRightVersion = new JComboBox<>(); JComboBox<Integer> positionOfBlock = new JComboBox<>(); positionOfBlock.addItem(1); final int[] version = {0}; final Integer[] lastSelectedItem = {1}; leftOrRightVersion.addItem("left"); leftOrRightVersion.addItem("right"); dialog.addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseMoved(MouseEvent e) { super.mouseMoved(e); lastSelectedItem[0] = (Integer)positionOfBlock.getSelectedItem(); version[0] = (Objects.equals(leftOrRightVersion.getSelectedItem(), "left")) ? groundTruthCreator.currentLeftVersion : groundTruthCreator.currentLeftVersion + 1; positionOfBlock.removeAllItems(); for(int i = 0; i<groundTruthCreator.postVersionList.get(version[0]).getPostBlocks().size(); i++){ positionOfBlock.addItem(i+1); } if(lastSelectedItem[0] != null)positionOfBlock.setSelectedItem(lastSelectedItem[0]); } }); JTextField comment = new JTextField(20); dialog.add(new JLabel("side:")); dialog.add(leftOrRightVersion); dialog.add(Box.createHorizontalStrut(5)); // a spacer dialog.add(new JLabel("position:")); dialog.add(positionOfBlock); dialog.add(Box.createHorizontalStrut(5)); // a spacer dialog.add(new JLabel("comment:")); dialog.add(comment); int procedure = JOptionPane.showConfirmDialog(null, dialog, "Please side and position of block", JOptionPane.OK_CANCEL_OPTION); int positionOfBlockToAddComment = (int)positionOfBlock.getSelectedItem(); if(comment.getText().equals("")){ JOptionPane.showMessageDialog(null, "You need to enter a comment in the field 'comment.'"); return; } String newComment = "vers: " + (version[0] +1) + " | " + "pos: " + positionOfBlockToAddComment + " | " + "<font color=\"gray\">" + comment.getText() + "</font>"; if(procedure == JOptionPane.YES_OPTION && !comments.contains(newComment)){ comments.add(newComment); paintCommentPanel(); } } }); buttonRemoveComment.addMouseListener(new MouseInputAdapter() { @Override public void mouseReleased(MouseEvent e) { super.mouseReleased(e); JComboBox<Integer> commentIds = new JComboBox<>(); for(int i=0; i<comments.size(); i++){ commentIds.addItem(i+1); } JPanel myPanel = new JPanel(); // https://stackoverflow.com/a/6555051 myPanel.add(new JLabel("delete a comment by choosing its id:")); myPanel.add(commentIds); int result = JOptionPane.showConfirmDialog( null, myPanel, "Delete Comment", JOptionPane.OK_CANCEL_OPTION); if (result == JOptionPane.OK_OPTION) { comments.remove((int)commentIds.getSelectedItem()-1); paintCommentPanel(); } } }); buttonLoadPost.addMouseListener(new MouseInputAdapter() { @Override public void mouseReleased(MouseEvent e) { super.mouseReleased(e); Integer requestedPostId = null; try { requestedPostId = Integer.parseInt(textFieldRequestSpecialPost.getText()); }catch (Exception ignored){ return; } Integer finalRequestedPostId = requestedPostId; File file = null; File[] postVersionList = null; File[] completedCSV = null; try { file = new File(GroundTruthCreator.path.toString()); postVersionList = file.listFiles((dir, name) -> name.matches(finalRequestedPostId + "\\.csv")); // //https://stackoverflow.com/questions/4852531/find-files-in-a-folder-using-java completedCSV = file.listFiles((dir, name) -> name.matches("completed_" + finalRequestedPostId + "\\.csv")); // //https://stackoverflow.com/questions/4852531/find-files-in-a-folder-using-java }catch (Exception ignored){ JOptionPane.showMessageDialog(null, "the files completed_" + requestedPostId + ".csv and " + requestedPostId + ".csv both needs to be in same folder postVersionLists."); return; } if(postVersionList == null || completedCSV == null || postVersionList.length == 0 || completedCSV.length == 0){ JOptionPane.showMessageDialog(null, "the files completed_" + requestedPostId + ".csv and " + requestedPostId + ".csv both needs to be in same folder postVersionLists."); return; } loadPost(requestedPostId); Path pathToCSV = FileSystems.getDefault().getPath("postVersionLists", completedCSV[0].getName()); List<String> lines = Toolkit.parseLines(pathToCSV.toString()); lines.sort((o1, o2) -> { StringTokenizer tokens_o1 = new StringTokenizer(o1, "; "); int postId_o1 = Integer.valueOf(tokens_o1.nextToken().replaceAll("\"", "")); int postHistoryId_o1 = Integer.valueOf(tokens_o1.nextToken().replaceAll("\"", "")); int postBlockTypeId_o1 = Integer.valueOf(tokens_o1.nextToken().replaceAll("\"", "")); int localId_o1 = Integer.valueOf(tokens_o1.nextToken().replaceAll("\"", "")); Integer predLocalId_o1 = null; Integer succLocalId_o1 = null; try { predLocalId_o1 = Integer.valueOf(tokens_o1.nextToken().replaceAll("\"", "")); } catch (Exception e1) { } try { succLocalId_o1 = Integer.valueOf(tokens_o1.nextToken().replaceAll("\"", "")); } catch (Exception e1) { } StringTokenizer tokens_o2 = new StringTokenizer(o2, "; "); int postId_o2 = Integer.valueOf(tokens_o2.nextToken().replaceAll("\"", "")); int postHistoryId_o2 = Integer.valueOf(tokens_o2.nextToken().replaceAll("\"", "")); int postBlockTypeId_o2 = Integer.valueOf(tokens_o2.nextToken().replaceAll("\"", "")); int localId_o2 = Integer.valueOf(tokens_o2.nextToken().replaceAll("\"", "")); Integer predLocalId_o2 = null; Integer succLocalId_o2 = null; try { predLocalId_o2 = Integer.valueOf(tokens_o2.nextToken().replaceAll("\"", "")); } catch (Exception e1) { } try { succLocalId_o2 = Integer.valueOf(tokens_o2.nextToken().replaceAll("\"", "")); } catch (Exception e1) { } if (postHistoryId_o1 != postHistoryId_o2) return postHistoryId_o1 - postHistoryId_o2; else return localId_o1 - localId_o2; }); Integer version = 0; Integer lastPostHistoryId = null; for(String line : lines){ StringTokenizer tokens = new StringTokenizer(line, ";"); int postId = Integer.valueOf(tokens.nextToken().replaceAll("\"", "").replaceAll("\\s+", "")); int postHistoryId = Integer.valueOf(tokens.nextToken().replaceAll("\"", "").replaceAll("\\s+", "")); int postBlockTypeId = Integer.valueOf(tokens.nextToken().replaceAll("\"", "").replaceAll("\\s+", "")); int localId = Integer.valueOf(tokens.nextToken().replaceAll("\"", "").replaceAll("\\s+", "")); Integer predLocalId = null; Integer succLocalId = null; try { predLocalId = Integer.valueOf(tokens.nextToken().replaceAll("\"", "").replaceAll("\\s+", "")); }catch (Exception e1){} try { succLocalId = Integer.valueOf(tokens.nextToken().replaceAll("\"", "").replaceAll("\\s+", "")); }catch (Exception e1){} String comment = tokens.nextToken(); comment = comment.substring(1,comment.length()-1); if(comment.length() > 1){ comment = "vers: " + (version+1) + " | " + "pos: " + localId + " | " + "<font color=\"gray\">" + comment + "</font>"; comments.add(comment); } if(lastPostHistoryId != null && postHistoryId > lastPostHistoryId) version++; if(succLocalId != null){ groundTruthCreator.allAutomaticSetBlockPairs.get(version).add( new BlockPair( null, null, postBlockTypeId == 1, localId-1, succLocalId-1)); } lastPostHistoryId = postHistoryId; } } }); buttonSwitchConnectionDisplayMode.addMouseListener(new MouseInputAdapter() { @Override public void mouseReleased(MouseEvent e) { super.mouseReleased(e); if(groundTruthCreator.linkConnectionDisplayMode == GroundTruthCreator.LinkConnectionDisplayModes.edges) groundTruthCreator.linkConnectionDisplayMode = GroundTruthCreator.LinkConnectionDisplayModes.films; else if(groundTruthCreator.linkConnectionDisplayMode == GroundTruthCreator.LinkConnectionDisplayModes.films) groundTruthCreator.linkConnectionDisplayMode = GroundTruthCreator.LinkConnectionDisplayModes.edges; groundTruthCreator.versionEdgesPanel.removeAll(); groundTruthCreator.versionEdgesPanel.validate(); groundTruthCreator.versionEdgesPanel.repaint(); } }); buttonSaveAllAndCloseThisVersion.addMouseListener(new MouseInputAdapter() { @Override public void mouseReleased(MouseEvent e) { super.mouseReleased(e); if(!buttonSaveAllAndCloseThisVersion.isEnabled()) return; Object[] options = {"Yes", "No"}; int procedure = JOptionPane.showOptionDialog( null, "Saving will close this post version list. Continue?", "Finish linking?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); if(procedure != JOptionPane.YES_OPTION) return; groundTruthCreator.currentLeftVersion = 0; // extracts links from clicked block pair edges for(int i = 0; i<groundTruthCreator.allCreatedBlockPairsByClicks.size(); i++){ for(int j = 0; j<groundTruthCreator.allCreatedBlockPairsByClicks.get(i).size(); j++){ byte postBlockTypeId = groundTruthCreator.allCreatedBlockPairsByClicks.get(i).get(j).clickedBlockIsInstanceOfTextBlockVersion ? TextBlockVersion.postBlockTypeId : CodeBlockVersion.postBlockTypeId; PostVersion leftPostVersion = groundTruthCreator.postVersionList.get(i); int leftVersion = i+1; int leftLocalId = groundTruthCreator.allCreatedBlockPairsByClicks.get(i).get(j).leftBlockPosition+1; PostVersion rightPostVersion = groundTruthCreator.postVersionList.get(i+1); int rightVersion = i+2; int rightLocalId = groundTruthCreator.allCreatedBlockPairsByClicks.get(i).get(j).rightBlockPosition+1; PostBlockLifeSpanVersion leftBlockLifeSpanSnapshot = new PostBlockLifeSpanVersion( leftPostVersion.getPostId(), leftPostVersion.getPostHistoryId(), postBlockTypeId, //leftVersion, leftLocalId ); PostBlockLifeSpanVersion rightBlockLifeSpanSnapshot = new PostBlockLifeSpanVersion( rightPostVersion.getPostId(), rightPostVersion.getPostHistoryId(), postBlockTypeId, //rightVersion, rightLocalId ); boolean leftSnapshotfoundInAChain = false; for(int k = 0; k<groundTruthCreator.blockLifeSpansExtractedFromClicks.size(); k++){ if(groundTruthCreator.blockLifeSpansExtractedFromClicks.get(k).getLast().equals(leftBlockLifeSpanSnapshot)){ groundTruthCreator.blockLifeSpansExtractedFromClicks.get(k).add(rightBlockLifeSpanSnapshot); leftSnapshotfoundInAChain = true; break; } } if(!leftSnapshotfoundInAChain){ PostBlockLifeSpan newBlockLifeSpan = new PostBlockLifeSpan(leftPostVersion.getPostId(), postBlockTypeId); newBlockLifeSpan.add(leftBlockLifeSpanSnapshot); newBlockLifeSpan.add(rightBlockLifeSpanSnapshot); groundTruthCreator.blockLifeSpansExtractedFromClicks.add(newBlockLifeSpan); } } } // handles blocks that were not clicked //if(groundTruthCreator.postVersionList != null) for(int i=0; i<groundTruthCreator.postVersionList.size(); i++){ for(int j=0; j<groundTruthCreator.postVersionList.get(i).getPostBlocks().size(); j++){ int postId = groundTruthCreator.postVersionList.get(i).getPostBlocks().get(j).getPostId(); byte postBlockTypeId = groundTruthCreator.postVersionList.get(i).getPostBlocks().get(j) instanceof TextBlockVersion ? TextBlockVersion.postBlockTypeId : CodeBlockVersion.postBlockTypeId; PostBlockLifeSpanVersion tmpBlockLifeSpanSnapshot = new PostBlockLifeSpanVersion( groundTruthCreator.postVersionList.get(i).getPostId(), groundTruthCreator.postVersionList.get(i).getPostHistoryId(), postBlockTypeId, // i+1, j+1 ); boolean tmpBlockLifeSpanSnapshotHasBeenFound = false; for(int k = 0; k<groundTruthCreator.blockLifeSpansExtractedFromClicks.size(); k++){ for(int l = 0; l<groundTruthCreator.blockLifeSpansExtractedFromClicks.get(k).size(); l++) { if (Objects.equals(groundTruthCreator.postHistoryIdToVersion.get(groundTruthCreator.blockLifeSpansExtractedFromClicks.get(k).get(l).getPostHistoryId()), groundTruthCreator.postHistoryIdToVersion.get(tmpBlockLifeSpanSnapshot.getPostHistoryId())) && groundTruthCreator.blockLifeSpansExtractedFromClicks.get(k).get(l).getLocalId() == tmpBlockLifeSpanSnapshot.getLocalId()) { tmpBlockLifeSpanSnapshotHasBeenFound = true; break; } } } if(!tmpBlockLifeSpanSnapshotHasBeenFound){ PostBlockLifeSpan tmpBlockLifeSpan = new PostBlockLifeSpan( postId, postBlockTypeId ); tmpBlockLifeSpan.add(tmpBlockLifeSpanSnapshot); groundTruthCreator.blockLifeSpansExtractedFromClicks.add(tmpBlockLifeSpan); } } } // groundTruthCreator.postVersionList = new PostVersionList(); groundTruthCreator.versionLeftPanel.removeAll(); groundTruthCreator.versionRightPanel.removeAll(); groundTruthCreator.versionEdgesPanel.removeAll(); groundTruthCreator.versionLeftPanel.validate(); groundTruthCreator.versionLeftPanel.repaint(); groundTruthCreator.versionRightPanel.validate(); groundTruthCreator.versionRightPanel.repaint(); groundTruthCreator.versionEdgesPanel.validate(); groundTruthCreator.versionEdgesPanel.repaint(); groundTruthCreator.navigatorAtBottomLabel.validate(); groundTruthCreator.navigatorAtBottomLabel.repaint(); labelSavedComments.setText(""); savedCommentsScrollPane.validate(); savedCommentsScrollPane.repaint(); groundTruthCreator.blockLifeSpansExtractedFromClicks.sort((PostBlockLifeSpan b1, PostBlockLifeSpan b2) -> { if (groundTruthCreator.postHistoryIdToVersion.get(b1.getFirst().getPostHistoryId()) < groundTruthCreator.postHistoryIdToVersion.get(b2.getFirst().getPostHistoryId())) { return -1; } else if (groundTruthCreator.postHistoryIdToVersion.get(b1.getFirst().getPostHistoryId()) > groundTruthCreator.postHistoryIdToVersion.get(b2.getFirst().getPostHistoryId())) { return 1; } else { return Integer.compare(b1.getFirst().getLocalId(), b2.getFirst().getLocalId()); } }); groundTruthCreator.exportBlockLinksToCSV(Paths.get(GroundTruthCreator.path.toString(), "completed_" + groundTruthCreator.blockLifeSpansExtractedFromClicks.getFirst().getFirst().getPostId() + ".csv")); groundTruthCreator.postVersionList = null; comments.clear(); groundTruthCreator.displayCurrentTwoVersionsAndNavigator(); setEnablingOfNextAndBackButton(); } }); } void paintCommentPanel(){ StringBuilder text = new StringBuilder("<html></head><body>"); for(int i=0; i<comments.size(); i++){ text.append("<font color=\"orange\">").append(i + 1).append("</font>").append("): ").append(comments.get(i).replace("\"", "")).append("<br>"); } text.append("</body></html>"); labelSavedComments.setText(text.toString()); labelSavedComments.validate(); labelSavedComments.repaint(); //savedCommentsScrollPane.validate(); //savedCommentsScrollPane.repaint(); } }
package com.demo.domain; import com.demo.domain.builder.GitRepoBuilder; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import java.util.Arrays; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyLong; public class GitRepoServiceTest { @InjectMocks private GitRepoService gitRepoService; @Mock private GitHubClient gitHubClient; @Mock private GitRepoRepository gitRepoRepository; @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void whenCallLoadGitReposForLanguagesThenLoadRepositories() { List languages = Arrays.asList("java", "kotlin", "go", "python", "c++"); Mockito.when(gitHubClient.findGitRepoByLanguages(languages)).thenReturn(getMockReposTestHelper()); Mockito.when(gitRepoRepository.checkIfExistById(anyLong())).thenReturn(false); List<GitRepo> repos = gitRepoService.loadGitReposForLanguages(languages); assertThat(repos).hasSize(2); assertThat(repos.get(0).getId()).isEqualTo(2L); assertThat(repos.get(0).getDescription()).isEqualTo("Java Repository"); assertThat(repos.get(0).getFullName()).isEqualTo("Java Repo"); assertThat(repos.get(0).getName()).isEqualTo("Java"); assertThat(repos.get(0).getUrl()).isEqualTo("java.com.br"); assertThat(repos.get(1).getId()).isEqualTo(3L); assertThat(repos.get(1).getDescription()).isEqualTo("Python Repository"); assertThat(repos.get(1).getFullName()).isEqualTo("Python Repo"); assertThat(repos.get(1).getName()).isEqualTo("Python"); assertThat(repos.get(1).getUrl()).isEqualTo("python.com.br"); } private List getMockReposTestHelper() { GitRepo javaRepo = GitRepoBuilder.of() .id(2L) .description("Java Repository") .fullName("Java Repo") .name("Java") .url("java.com.br") .build(); GitRepo pythonRepo = GitRepoBuilder.of() .id(3L) .description("Python Repository") .fullName("Python Repo") .name("Python") .url("python.com.br") .build(); return Arrays.asList(javaRepo, pythonRepo); } }
/** * DNet eBusiness Suite * Copyright: 2010-2013 Nan21 Electronics SRL. All rights reserved. * Use is subject to license terms. */ package net.nan21.dnet.module.bd.presenter.impl.attr.model; import net.nan21.dnet.core.api.annotation.Ds; import net.nan21.dnet.core.api.annotation.DsField; import net.nan21.dnet.core.api.annotation.SortField; import net.nan21.dnet.core.presenter.model.AbstractTypeWithCodeLov; import net.nan21.dnet.module.bd.domain.impl.attr.AttributeSubSet; @Ds(entity = AttributeSubSet.class, sort = {@SortField(field = AttributeSubSetLov_Ds.f_code)}) public class AttributeSubSetLov_Ds extends AbstractTypeWithCodeLov<AttributeSubSet> { public static final String f_attributeSetId = "attributeSetId"; @DsField(join = "left", path = "attributeSet.id") private String attributeSetId; public AttributeSubSetLov_Ds() { super(); } public AttributeSubSetLov_Ds(AttributeSubSet e) { super(e); } public String getAttributeSetId() { return this.attributeSetId; } public void setAttributeSetId(String attributeSetId) { this.attributeSetId = attributeSetId; } }
package spring_mvcForms; import org.springframework.jdbc.core.RowMapper; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; public final class StudentRowMapper implements RowMapper<Student> { public Student mapRow(ResultSet rs, int rowNum) throws SQLException { // TODO Auto-generated method stub Student student=new Student(); student.setFirstName(rs.getString(1)); student.setLastName(rs.getString(2)); student.setCountry(rs.getString(3)); student.setFavouriteLanguage(rs.getString(4)); //student.setOperatingSystems(rs.getString(5).toString()); return student; } }
import java.util.ArrayList; import java.util.List; public class Sprint { private int begin; private int end; private String name; private User user; private List<Task> taskList; public Sprint(int begin, int end, String name,User user) { super(); this.begin = begin; this.end = end; this.name = name; this.user = user; taskList = new ArrayList<>(); } public List<Task> getTaskList() { return taskList; } public void addToSprint(Task task,User user){ if(this.user.getId()==user.getId()) this.taskList.add(task); else System.out.println("You cannot add tasks to the sprint not created by you"); } public void removeFromSprint(Task task,User user){ if(this.user.getId()==user.getId()) this.taskList.remove(task); else System.out.println("You cannot remove tasks from the sprint not created by you"); } @Override public String toString() { return "Sprint [begin=" + begin + ", end=" + end + ", name=" + name +"]"; } }
package com.tw.wallet; import com.tw.wallet.exceptions.AmountInWalletExceededException; public class Wallet { private final Money amountInWallet; public Wallet() { amountInWallet = new Money(); } public void put(Money money) { amountInWallet.add(money); } public void take(Money takeAmount) throws AmountInWalletExceededException { if (amountInWallet.amount < takeAmount.amount * takeAmount.currencyType.multiplier) { throw new AmountInWalletExceededException("Wallet does not have enough balance"); } amountInWallet.take(takeAmount); } public double total(CurrencyType currencyType) { return amountInWallet.amount / currencyType.multiplier; } }
package org.rebioma.client; import com.google.gwt.user.client.rpc.IsSerializable; public class UserExistedException extends Exception implements IsSerializable { public UserExistedException() { this(null); } public UserExistedException(String msg) { super(msg); } }
static int countingValleys(int n, String s) { int Down = 0; int valleys = 0; for(int i=0;i<s.length();i++) { if(s.charAt(i) == 'U'){ Down -= 1; if(Down == 0) valleys++; } else if(s.charAt(i) == 'D') Down += 1; } return valleys; }
package edu.buet.cse.spring.ch03.v4; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import edu.buet.cse.spring.ch03.v4.model.Performer; public class App { public static void main(String[] args) { ApplicationContext appContext = new ClassPathXmlApplicationContext("/edu/buet/cse/spring/ch03/v4/spring-beans.xml"); Performer kenny = appContext.getBean("kenny", Performer.class); kenny.perform(); } }
/** * Test scenario that uses constants (object refs) in rules. */ package test.nz.org.take.compiler.scenario5;
import com.google.common.base.Function; import io.github.bonigarcia.wdm.WebDriverManager; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.FluentWait; import org.openqa.selenium.support.ui.Wait; import org.testng.Assert; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import static java.util.concurrent.TimeUnit.SECONDS; public class RegisterLogin { WebDriver driver; @BeforeTest public void LaunchUrl() { WebDriverManager.chromedriver().setup(); driver = new ChromeDriver(); driver.get("https://qa-frontend.revitsone.com/register"); driver.manage().deleteAllCookies(); driver.manage().window().maximize(); } @AfterTest public void CloseBrowser() { driver.quit(); } @Test(dataProvider = "getRegisterData") public void RegisterUser(String firstname,String MiddleName,String LastName,String PhoneNumber,String email,String Pword,String CName) throws InterruptedException { Thread.sleep(5000); String title=driver.findElement(By.xpath("//div[@class='register-right']/h2")).getText(); Assert.assertEquals(title,"Register"); WebElement FName= driver.findElement(By.xpath("//label[text()='First Name']/following-sibling::input")); FName.clear(); Thread.sleep(1000); FName.sendKeys(firstname); WebElement MName= driver.findElement(By.xpath("//label[text()='Middle Name']/following-sibling::input")); MName.clear(); Thread.sleep(1000); MName.sendKeys(MiddleName); WebElement LName= driver.findElement(By.xpath("//label[text()='Last Name']/following-sibling::input")); Thread.sleep(1000); LName.clear(); LName.sendKeys(LastName); WebElement PNumber= driver.findElement(By.xpath("//label[text()='Phone Number']/following-sibling::input")); Thread.sleep(1000); PNumber.clear(); PNumber.sendKeys(PhoneNumber); WebElement mail= driver.findElement(By.xpath("//label[text()='Email']/following-sibling::input")); Thread.sleep(1000); mail.clear(); mail.sendKeys(email); WebElement Password= driver.findElement(By.xpath("//label[text()='Password']/following-sibling::input")); Thread.sleep(1000); Password.clear(); Password.sendKeys(Pword); WebElement ConPassword= driver.findElement(By.xpath("//label[text()='Confirm Password']/following-sibling::input")); Thread.sleep(1000); ConPassword.clear(); ConPassword.sendKeys(Pword); WebElement CompanyName= driver.findElement(By.xpath("//label[text()='Company Name']/following-sibling::input")); Thread.sleep(1000); CompanyName.clear(); CompanyName.sendKeys(CName); WebElement AcceptCheckBox= driver.findElement(By.xpath("//input[@type='checkbox' and @class = 'ant-checkbox-input']")); Thread.sleep(1000); AcceptCheckBox.click(); Thread.sleep(1000); WebElement StartUsingRevitBtn= driver.findElement(By.xpath("//button[@type='button']")); StartUsingRevitBtn.click(); Thread.sleep(3000); Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(60, SECONDS).pollingEvery(1, SECONDS).ignoring(NoSuchElementException.class); WebElement Message = wait.until(new Function<WebDriver, WebElement>() { public WebElement apply(WebDriver driver) { return driver.findElement(By.xpath("//div[@class='ant-message']/span/div")); } }); System.out.println("Message displayed is "+Message.getText()); } @DataProvider public Object[][] getRegisterData(){ Object data[][] = ExcelUtils.getTestData("RegisterUser"); return data; } }
package com.fleet.initializr.service; import com.fleet.initializr.entity.Application; /** * @author April Han */ public interface ProjectGeneratorService { void generator(Application application) throws Exception; }
package net.liuzd.spring.boot.v2.mappper; import java.util.ArrayList; import java.util.List; import java.util.Random; import javax.annotation.Resource; import org.apache.ibatis.session.ExecutorType; import org.apache.ibatis.session.SqlSession; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.CollectionUtils; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import net.liuzd.spring.boot.v2.entity.User; import net.liuzd.spring.boot.v2.entity.enums.UserStatusEnum; import net.liuzd.spring.boot.v2.mapper.UserMapper; import net.liuzd.spring.boot.v2.model.UserPage; @RunWith(SpringJUnit4ClassRunner.class) // @Transactional 注释打开会自动恢复初始数据(清除插入与更新的数据) @SpringBootTest public class UserMapperTest { @Resource private UserMapper mapper; @Resource(name = "sqlSessionTemplate") private SqlSessionTemplate sqlSessionTemplate; @Test public void testPage() { System.out.println("------ 自定义 xml 分页 ------"); // UserPage selectPage = new UserPage(1, 5).setSelectInt(20); UserPage selectPage = new UserPage(1, 5); UserPage userPage = mapper.selectUserPage(selectPage); Assert.assertSame(userPage, selectPage); System.out.println("总条数 ------> " + userPage.getTotal()); System.out.println("当前页数 ------> " + userPage.getCurrent()); System.out.println("当前每页显示数 ------> " + userPage.getSize()); print(userPage.getRecords()); System.out.println("------ baseMapper 自带分页 ------"); Page<User> page = new Page<>(1, 5); IPage<User> userIPage = mapper.selectPage(page, new QueryWrapper<User>().eq("age", 20)); Assert.assertSame(userIPage, page); System.out.println("总条数 ------> " + userIPage.getTotal()); System.out.println("当前页数 ------> " + userIPage.getCurrent()); System.out.println("当前每页显示数 ------> " + userIPage.getSize()); print(userIPage.getRecords()); } int size = 10001; @Test public void testInserts() { List<User> users = new ArrayList<>(); int bath = 200; int counts = 0; for (int i = 0; i < size; i++) { User user = getUser(i); users.add(user); if (users.size() == bath) { counts += mapper.insertBatch(users); users.clear(); } } long s = System.nanoTime(); if (users.size() > 0) { counts += mapper.insertBatch(users); } long e = System.nanoTime(); // 100条> 37343029 // 200条> 34796082 // 500条 > 33109665 // 1000条>61176433 // 根据实际场景来,如大数据量使用方法三,关键是测试mbatis的批量执行最大边界 System.out.println("users size : " + users.size() + ",insert counts : " + counts + ",用时:" + (e - s)); Assert.assertTrue("批量插入成功", counts > 0); } private User getUser(int i) { User user = new User(); user.setName("原来你也在这里" + i); user.setAge(18 + i); user.setVersion(i); user.setEmail(i + "davidliuzd@sina.com"); user.setStatus(UserStatusEnum.NORMAL); user.setMark(0); return user; } @Test public void testInserts2() { long s = System.nanoTime(); int counts = 0; for (int i = 0; i < size; i++) { User user = getUser(i); Assert.assertTrue(mapper.insert(user) > 0); counts++; } long e = System.nanoTime(); // 366225347844 System.out.println("users size : " + size + ",insert counts : " + counts + ",用时:" + (e - s)); Assert.assertTrue("批量插入成功", counts > 0); } @Test public void testInserts3() { List<User> users = new ArrayList<>(); for (int i = 0; i < size; i++) { User user = getUser(i); users.add(user); } long s = System.nanoTime(); int result = 1; SqlSession batchSqlSession = null; try { batchSqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);// 获取批量方式的sqlsession int batchCount = 1000;// 每批commit的个数 int batchLastIndex = batchCount;// 每批最后一个的下标 String statement = "net.liuzd.spring.boot.v2.mapper.UserMapper.insertBatch"; for (int index = 0; index < size;) { if (batchLastIndex >= size) { batchLastIndex = size; result = result * batchSqlSession.insert(statement, users.subList(index, batchLastIndex)); batchSqlSession.commit(); System.out.println("index:" + index + " batchLastIndex:" + batchLastIndex); break;// 数据插入完毕,退出循环 } else { result = result * batchSqlSession.insert(statement, users.subList(index, batchLastIndex)); batchSqlSession.commit(); System.out.println("index:" + index + " batchLastIndex:" + batchLastIndex); index = batchLastIndex;// 设置下一批下标 batchLastIndex = index + (batchCount - 1); } } batchSqlSession.commit(); } finally { batchSqlSession.close(); } long e = System.nanoTime(); // 6007770095 System.out.println("users size : " + users.size() + ",insert counts : " + size + ",用时:" + (e - s)); } @Test public void testInsert() { User user = getUser(new Random().nextInt(100)); Assert.assertTrue(mapper.insert(user) > 0); // 成功直接拿会写的 ID System.err.println("\n插入成功 ID 为:" + user.getId()); } @Test public void testSaveOne() { User user = getUser(new Random().nextInt(100)); Assert.assertTrue(mapper.saveOne(user) > 0); // 成功直接拿会写的 ID System.err.println("\n插入成功 ID 为:" + user.getId()); } @Test public void testSelect() { System.out.println(mapper.selectById(1L)); } @Test public void testDelAll() { mapper.deleteAll(); } private <T> void print(List<T> list) { if (!CollectionUtils.isEmpty(list)) { list.forEach(System.out::println); } } @Test public void bDelete() { // 更新字段:deleted 为1 Assert.assertTrue(mapper.deleteById(3L) > 0); Assert.assertTrue(mapper.delete(new QueryWrapper<User>().lambda().eq(User::getName, "Jack")) > 0); } @Test public void cUpdate() { Assert.assertTrue(mapper.update(new User().setName("Jack"), new UpdateWrapper<User>().lambda().set(User::getAge, 3).eq(User::getId, 2)) > 0); } @Test public void dSelect() { Assert.assertEquals("test1@baomidou.com", mapper.selectById(1L).getEmail()); User user = mapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getId, 2)); Assert.assertEquals("Jack", user.getName()); Assert.assertTrue(22 == user.getAge()); } /** * @author 2019年3月19日 上午11:38:49 * @Title: testUpdateByIdSucc * @Description:乐观锁 void */ @Test public void testUpdateByIdSucc() { User user = new User(); user.setAge(18); user.setEmail("test@baomidou.com"); user.setName("optlocker"); user.setVersion(1); user.setStatus(UserStatusEnum.NORMAL); mapper.insert(user); Long id = user.getId(); User userUpdate = new User(); userUpdate.setId(id); userUpdate.setAge(19); userUpdate.setVersion(1); Assert.assertEquals("Should update success", 1, mapper.updateById(userUpdate)); Assert.assertEquals("Should version = version+1", 2, userUpdate.getVersion().intValue()); } }
package com.Appthuchi.Appqlthuchi.moder; public class LoaiThu { public String tenLoaiThu; public int maLoaiThu; public String getTenLoaiThu() { return tenLoaiThu; } public void setTenLoaiThu(String tenLoaiThu) { this.tenLoaiThu = tenLoaiThu; } public int getMaLoaiThu() { return maLoaiThu; } public void setMaLoaiThu(int maLoaiThu) { this.maLoaiThu = maLoaiThu; } @Override public String toString() { return getTenLoaiThu(); } }
/* * 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 wickersoft.root; import com.earth2me.essentials.Essentials; import com.griefcraft.lwc.LWCPlugin; import com.sk89q.worldguard.WorldGuard; import com.sk89q.worldguard.protection.regions.RegionContainer; import java.io.File; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.regex.Pattern; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.block.BlockFace; import org.bukkit.entity.Entity; /** * * @author Dennis */ public class Storage { public static final BlockFace[] CARDINAL_FACES = {BlockFace.NORTH, BlockFace.WEST, BlockFace.SOUTH, BlockFace.EAST}; public static final HashMap<String, String> INFO_SIGNS = new HashMap<>(); public static final HashMap<String, String> LANGUAGE_ALIASES = new HashMap<>(); public static final HashMap<String, Petition> PETITIONS = new HashMap<>(); public static final HashMap<Pattern, String> SHORTCUTS = new HashMap<>(); public static final HashSet<Entity> VEHICLES = new HashSet<>(); public static final HashMap<String, String> WARN_IPS = new HashMap<>(); public static final Random RANDOM = new Random(); public static final String[] KNOWN_LANGCODES = { "en", "de", "da", "sv", "no", "fr", "es" }; public static String UNDERCOVER_CHAT_FORMAT; public static String SHADOWMUTE_SEE_CHAT_FORMAT; public static String MYMEMORY_TRANSLATED_NET_API_KEY; public static String GOOGLE_MAPS_API_KEY; public static String BAN_APPEAL_MESSAGE; public static boolean INV_SAVE_AUTO_OVERWRITE; public static int MAX_SLURP_RANGE; public static int DEFAULT_SLURP_RANGE; public static int TRANSLATION_TIMEOUT; public static long XRAY_WARN_TIME; public static long MAX_DEATH_INV_AGE_MILLIS; public static boolean DEBUG; public static MessageDigest md5; public static final Essentials essentials = (Essentials) Bukkit.getPluginManager().getPlugin("Essentials"); private static RegionContainer worldguard; public static final LWCPlugin lwc = (LWCPlugin) Bukkit.getPluginManager().getPlugin("LWC"); public static void loadData() { YamlConfiguration fc = YamlConfiguration.read(new File(Root.instance().getDataFolder(), "config.yml")); UNDERCOVER_CHAT_FORMAT = ChatColor.translateAlternateColorCodes('&', fc.getString("undercover-chat-format", "<%1$s> %2$s")); SHADOWMUTE_SEE_CHAT_FORMAT = ChatColor.translateAlternateColorCodes('&', fc.getString("shadowmute-see-chat-format", "&8<&8%1$s> &8%2$s")); MYMEMORY_TRANSLATED_NET_API_KEY = fc.getString("mymemory-translated-net-api-key", ""); GOOGLE_MAPS_API_KEY = fc.getString("google-maps-api-key", ""); BAN_APPEAL_MESSAGE = fc.getString("ban-appeal-message", ""); MAX_SLURP_RANGE = fc.getInt("max-slurp-range", 100); DEFAULT_SLURP_RANGE = fc.getInt("default-slurp-range", 16); TRANSLATION_TIMEOUT = fc.getInt("translation-timeout", 2000); INV_SAVE_AUTO_OVERWRITE = fc.getBoolean("inv-save-auto-overwrite", true); XRAY_WARN_TIME = fc.getInt("xray-warn-time-millis", 900000); MAX_DEATH_INV_AGE_MILLIS = fc.getLong("max-death-inventory-age-days", 14) * 86400 * 1000; DEBUG = fc.getBoolean("debug", false); List<YamlConfiguration> shortcuts = fc.getSectionList("shortcuts"); SHORTCUTS.clear(); shortcuts.forEach((map) -> { if (map.containsKey("replace") && map.containsKey("with") && map.get("replace") instanceof String && map.get("with") instanceof String) { SHORTCUTS.put(Pattern.compile((String) map.get("replace")), (String) map.get("with")); } }); INFO_SIGNS.clear(); YamlConfiguration.read(new File(Root.instance().getDataFolder(), "infosigns.yml")).forEach( (key, value) -> { if (value instanceof String) { INFO_SIGNS.put(key, (String) value); } }); PETITIONS.clear(); YamlConfiguration petitionData = YamlConfiguration.read(new File(Root.instance().getDataFolder(), "petitions.yml")); petitionData.keySet().forEach((key) -> { List<String> signatures = petitionData.getList(key, String.class); PETITIONS.put(key, new Petition(key, signatures)); }); } public static void saveData() { YamlConfiguration yaml = YamlConfiguration.emptyConfiguration(); PETITIONS.forEach( (name, petition) -> { yaml.put(name, petition.getSignatures()); }); try { yaml.save(new File(Root.instance().getDataFolder(), "petitions.yml")); } catch (IOException ex) { ex.printStackTrace(); } yaml.clear(); INFO_SIGNS.forEach( (name, value) -> { yaml.put(name, value); }); try { yaml.save(new File(Root.instance().getDataFolder(), "infosigns.yml")); } catch (IOException ex) { ex.printStackTrace(); } } public static RegionContainer getWorldguard() { if(worldguard == null) { return (worldguard = WorldGuard.getInstance().getPlatform().getRegionContainer()); } else { return worldguard; } } static { try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { } LANGUAGE_ALIASES.put("english", "en"); LANGUAGE_ALIASES.put("german", "de"); LANGUAGE_ALIASES.put("danish", "da"); LANGUAGE_ALIASES.put("swedish", "sv"); LANGUAGE_ALIASES.put("norwegian", "no"); LANGUAGE_ALIASES.put("french", "fr"); LANGUAGE_ALIASES.put("spanish", "es"); } }
package unitserver; import tools.Unit; import java.io.Serializable; import java.util.HashMap; import java.util.Map; /** * Created by troy on 07.10.2016. * Bean ready + * Класс наследуюется от HashMap<String, Unit> * где в качестве ключа выступает уникальное имя Юнита, а в качестве значение экземпляр класса Unit * * Данный класс является набором всех зарегестрированных в системе имен юнитов (ключи мапы), * а также кешем всех последних значений все зарегестрированных в системе юнитов */ public class UnitMap extends HashMap<String, Unit> implements Serializable { /** * Constructs an empty <tt>HashMap</tt> with the default initial capacity * (16) and the default load factor (0.75). */ public UnitMap() { } /** * * @return метод возвращает экземпляр себя (может быть использованно для серелизации) */ protected UnitMap getUnitMap(){ return this; } /** * Associates the specified value with the specified key in this map. * If the map previously contained a mapping for the key, the old * value is replaced. * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value associated with <tt>key</tt>, or * <tt>null</tt> if there was no mapping for <tt>key</tt>. * (A <tt>null</tt> return can also indicate that the map * previously associated <tt>null</tt> with <tt>key</tt>.) */ @Override public Unit put(String key, Unit value) { synchronized (UnitMap.class){ return super.put(key, value); } } /** * Copies all of the mappings from the specified map to this map. * These mappings will replace any mappings that this map had for * any of the keys currently in the specified map. * * @param m mappings to be stored in this map * @throws NullPointerException if the specified map is null */ @Override public void putAll(Map<? extends String, ? extends Unit> m) { synchronized (UnitMap.class) { super.putAll(m); } } /** * Removes the mapping for the specified key from this map if present. * * @param key key whose mapping is to be removed from the map * @return the previous value associated with <tt>key</tt>, or * <tt>null</tt> if there was no mapping for <tt>key</tt>. * (A <tt>null</tt> return can also indicate that the map * previously associated <tt>null</tt> with <tt>key</tt>.) */ @Override public Unit remove(Object key) { synchronized (UnitMap.class) { return super.remove(key); } } /** * Removes all of the mappings from this map. * The map will be empty after this call returns. */ @Override public void clear() { synchronized (UnitMap.class){ super.clear(); } } @Override public boolean remove(Object key, Object value) { synchronized (UnitMap.class){ return super.remove(key, value); } } @Override public boolean replace(String key, Unit oldValue, Unit newValue) { synchronized (UnitMap.class){ return super.replace(key, oldValue, newValue); } } @Override public Unit replace(String key, Unit value) { synchronized (UnitMap.class) { return super.replace(key, value); } } @Override public String toString() { return "UnitMap" + super.toString(); } /** * Compares the specified object with this map for equality. Returns * <tt>true</tt> if the given object is also a map and the two maps * represent the same mappings. More formally, two maps <tt>m1</tt> and * <tt>m2</tt> represent the same mappings if * <tt>m1.entrySet().equals(m2.entrySet())</tt>. This ensures that the * <tt>equals</tt> method works properly across different implementations * of the <tt>Map</tt> interface. * * @param o object to be compared for equality with this map * @return <tt>true</tt> if the specified object is equal to this map * @implSpec This implementation first checks if the specified object is this map; * if so it returns <tt>true</tt>. Then, it checks if the specified * object is a map whose size is identical to the size of this map; if * not, it returns <tt>false</tt>. If so, it iterates over this map's * <tt>entrySet</tt> collection, and checks that the specified map * contains each mapping that this map contains. If the specified map * fails to contain such a mapping, <tt>false</tt> is returned. If the * iteration completes, <tt>true</tt> is returned. */ @Override public boolean equals(Object o) { return super.equals(o); } /** * Returns the hash code value for this map. The hash code of a map is * defined to be the sum of the hash codes of each entry in the map's * <tt>entrySet()</tt> view. This ensures that <tt>m1.equals(m2)</tt> * implies that <tt>m1.hashCode()==m2.hashCode()</tt> for any two maps * <tt>m1</tt> and <tt>m2</tt>, as required by the general contract of * {@link Object#hashCode}. * * @return the hash code value for this map * @implSpec This implementation iterates over <tt>entrySet()</tt>, calling * {@link Entry#hashCode hashCode()} on each element (entry) in the * set, and adding up the results. * @see Entry#hashCode() * @see Object#equals(Object) * */ @Override public int hashCode() { return super.hashCode(); } }
package com.example.healthmanage.ui.activity.integral.adapter; import androidx.annotation.Nullable; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.example.healthmanage.R; import com.example.healthmanage.ui.activity.integral.response.IntegralDetailResponse; import java.util.List; /** * desc: * date:2021/7/19 9:38 * author:bWang */ public class IntegralDetailAdapter extends BaseQuickAdapter<IntegralDetailResponse.DataBean, BaseViewHolder> { public IntegralDetailAdapter(@Nullable List<IntegralDetailResponse.DataBean> data) { super(R.layout.item_integral_detail,data); } @Override protected void convert(BaseViewHolder helper, IntegralDetailResponse.DataBean item) { helper.setText(R.id.tv_integral_date,item.getCreateTime()); if (item.getType()==0){ helper.setText(R.id.tv_integral_content,"+"+item.getValue()); helper.setText(R.id.tv_integral_title,item.getChangeReason()); }else { helper.setText(R.id.tv_integral_content,"-"+item.getValue()); helper.setText(R.id.tv_integral_title,"兑换商品:"+item.getChangeReason()); } } }
package com.tarena.shoot; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.util.Arrays; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JPanel; public class shootGame extends JPanel{ public static final int WIDTH = 400; public static final int HEIGHT = 654; public static BufferedImage background; public static BufferedImage start; public static BufferedImage pause; public static BufferedImage gameover; public static BufferedImage airplane; public static BufferedImage bee; public static BufferedImage bullet; public static BufferedImage hero0; public static BufferedImage hero1; public static final int START = 0; public static final int RUNNING = 1; public static final int PAUSE = 2; public static final int GAME_OVER = 3; public int state = START; private Hero hero = new Hero(); private FlyingObject[] flyings = {}; private Bullet[] bullets = {}; /* public shootGame(){ flyings = new FlyingObject[2]; flyings[0] = new Airplane(); flyings[1] = new Bee(); bullets = new Bullet[1]; bullets[0] = new Bullet(100,200); }*/ static{ try{ background = ImageIO.read(shootGame.class.getResource("background.png")); start = ImageIO.read(shootGame.class.getResource("start.png")); pause = ImageIO.read(shootGame.class.getResource("pause.png")); gameover = ImageIO.read(shootGame.class.getResource("gameover.png")); airplane = ImageIO.read(shootGame.class.getResource("airplane.png")); bee = ImageIO.read(shootGame.class.getResource("bee.png")); bullet = ImageIO.read(shootGame.class.getResource("bullet.png")); hero0 = ImageIO.read(shootGame.class.getResource("hero0.png")); hero1 = ImageIO.read(shootGame.class.getResource("hero1.png")); }catch(Exception e){ e.printStackTrace(); } } public FlyingObject nextOne(){//判断下一个飞行物是小蜜蜂还是敌机 Random rand = new Random(); int type = rand.nextInt(20); if(type < 4){ return new Bee(); }else{ return new Airplane(); } } int flyEnteredIndex = 0; //敌人(敌机+小蜜蜂)入场 public void enterAction(){ flyEnteredIndex++; if(flyEnteredIndex%40==0){//每400ms生成一个敌人 FlyingObject one= nextOne(); flyings = Arrays.copyOf(flyings,flyings.length+1); flyings[flyings.length-1] = one; } } public void stepAction(){//飞行物(小蜜蜂+小敌机),子弹走步 hero.step(); for(int i=0;i<flyings.length;i++){ flyings[i].step(); } for(int i=0;i<bullets.length;i++){ bullets[i].step(); } } int shootIndex = 0; public void shootAction(){//发射子弹 shootIndex ++; if(shootIndex%30==0){//每300ms发射一颗子弹 Bullet[] bs = hero.shoot(); bullets = Arrays.copyOf(bullets, bullets.length+bs.length);//数组扩容 /* if(bs.length>1){ bullets[bullets.length-1] = bs[0]; bullets[bullets.length-2] = bs[1]; }else{ bullets[bullets.length-1] = bs[0]; }*/ System.arraycopy(bs, 0, bullets,bullets.length-bs.length, bs.length);//数组的追加 } } public void outOfBoundsAction(){//越界 int index = 0; FlyingObject[] flyingLives = new FlyingObject[flyings.length]; for(int i=0;i<flyings.length;i++){ FlyingObject f = flyings[i]; if(!f.outOfBounds()){//若不越界 flyingLives[index] = f; index++; } } flyings = Arrays.copyOf(flyingLives, index);//不越界的小蜜蜂或敌机放进数组中 index = 0; Bullet[] bulletLives = new Bullet[bullets.length]; for(int i=0;i<bullets.length;i++){ Bullet b = bullets[i]; if(!b.outOfBounds()){ bulletLives[index] = b; index++; } } bullets = Arrays.copyOf(bulletLives,index);//不越界的子弹放进数组中 } public void bangAction(){ for(int i=0;i<bullets.length;i++){ Bullet b = bullets[i]; bang(b); //子弹与敌人碰撞 } } int score = 0; int life = 3; public void bang(Bullet b){ int index = -1; for(int i=0;i<flyings.length;i++){ FlyingObject f = flyings[i]; if(f.shootby(b)){ index = i; break; } } if(index!=-1){ FlyingObject one = flyings[index]; if(one instanceof Enemy){ Enemy e = (Enemy) one; score += e.getScore(); } if(one instanceof Award){ Award a = (Award) one; int type = a.getType(); switch(type){ case Award.DOUBLE_FIRE: hero.addDoubleFire(); break; case Award.LIFE: hero.addLife(); break; } } FlyingObject t = flyings[index]; flyings[index] = flyings[flyings.length-1]; flyings[flyings.length-1] = t; flyings = Arrays.copyOf(flyings, flyings.length-1);//数组缩容 } } public void checkGameOverAction(){ if(isGameOver()){ state = GAME_OVER; } } public boolean isGameOver(){ for(int i=0;i<flyings.length;i++){ FlyingObject f = flyings[i]; if(hero.hit(f)){ hero.subtractLife(); hero.clearDoubleFire(); FlyingObject t = flyings[i]; flyings[i] = flyings[flyings.length-1]; flyings[flyings.length-1] = t; flyings = Arrays.copyOf(flyings, flyings.length-1); } } return hero.getLife()<=0; } public void action(){ MouseAdapter l = new MouseAdapter(){ public void mouseMoved(MouseEvent e){ if(state==RUNNING){ int x = e.getX(); int y = e.getY(); hero.moveTo(x, y); } } public void mouseClicked(MouseEvent e){ switch(state){ case START: state = RUNNING; break; case GAME_OVER: score = 0; hero = new Hero(); flyings = new FlyingObject[0]; bullets = new Bullet[0]; state = START; break; } } public void mouseExited(MouseEvent e){ if(state == RUNNING){ state = PAUSE; } } public void mouseEntered(MouseEvent e){ if(state==PAUSE){ state = RUNNING; } } }; this.addMouseListener(l);//处理鼠标操作事件 this.addMouseMotionListener(l);//处理鼠标滑动事件 Timer timer = new Timer(); int intervel = 10;//时间间隔(以毫秒为单位) timer.schedule(new TimerTask(){ public void run(){ if(state==RUNNING){ enterAction();//敌人(敌机+小蜜蜂)入场 stepAction(); shootAction(); outOfBoundsAction(); bangAction(); checkGameOverAction(); } repaint(); } },intervel,intervel); } public void paint(Graphics g){ g.drawImage(background,0,0,null); paintHero(g); paintFlyingObjects(g); paintBullets(g); paintScoreAndLife(g); paintState(g); } public void paintHero(Graphics g){ g.drawImage(hero.image,hero.x,hero.y,null);//hero.image也可以换成shootGame.hero0程序不出错 } public void paintFlyingObjects(Graphics g){ for(int i=0;i<flyings.length;i++){ FlyingObject f = flyings[i]; g.drawImage(f.image,f.x,f.y,null); } } public void paintBullets(Graphics g){ for(int i=0;i<bullets.length;i++){ Bullet b = bullets[i]; g.drawImage(b.image,b.x,b.y,null); } // g.drawImage(bullets[0].image,bullets[0].x,bullets[0].y,null); } public void paintScoreAndLife(Graphics g){ g.setColor(new Color(0xFF0000));//RGB三原色 g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,24)); g.drawString("SCORE:"+score,10,25); g.drawString("LIFE:"+hero.getLife(), 10, 45); } public void paintState(Graphics g){ switch(state){ case START: g.drawImage(start,0,0,null); break; case PAUSE: g.drawImage(pause,0,0,null); break; case GAME_OVER: g.drawImage(gameover,0,0,null); break; } } public static void main(String[] args) { JFrame frame = new JFrame("日常打ll"); shootGame game = new shootGame(); frame.add(game); frame.setSize(WIDTH,HEIGHT); frame.setAlwaysOnTop(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//点×程序停止运行 frame.setLocationRelativeTo(null); frame.setVisible(true); game.action(); } }
/** * Helios, OpenSource Monitoring * Brought to you by the Helios Development Group * * Copyright 2014, Helios Development Group and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * */ package com.heliosapm.script; import groovy.lang.Script; import java.util.Map; import java.util.concurrent.Callable; import javax.management.ObjectName; import com.heliosapm.jmx.config.Configuration; import com.heliosapm.jmx.execution.ExecutionSchedule; /** * <p>Title: DeployedScript</p> * <p>Description: Represents a compiled script created via JSR 233, the groovy compiler etc.</p> * <p>Company: Helios Development Group LLC</p> * @author Whitehead (nwhitehead AT heliosdev DOT org) * <p><code>com.heliosapm.script.DeployedScript</code></p> * @param <T> The type of the underlying executable script */ public interface DeployedScript<T> extends DeployedScriptMXBean, Callable<T> { /** The config name for the default schedule if a deployment does not provide one */ public static final String DEFAULT_SCHEDULE_PROP = "com.heliosapm.deployment.defaultschedule"; /** The internal config key for the schedule */ public static final String SCHEDULE_KEY = "schedule"; /** The internal config key for the timeout */ public static final String TIMEOUT_KEY = "timeout"; /** The jmx notification type root */ public static final String NOTIF_ROOT = "heliosapm.deployment"; /** The jmx notification type for a status change in the deployment */ public static final String NOTIF_STATUS_CHANGE = NOTIF_ROOT + ".statechange"; /** The jmx notification type for a config change in the deployment */ public static final String NOTIF_CONFIG_CHANGE = NOTIF_ROOT + ".configchange"; /** The jmx notification type for a config change in the deployment */ public static final String NOTIF_RECOMPILE = NOTIF_ROOT + ".recompile"; /** The jmx notification type for a config change in a configuration source */ public static final String NOTIF_CONFIG_MOD = NOTIF_ROOT + ".config.change"; /** The jmx notification type for a new configuration source registration */ public static final String NOTIF_CONFIG_NEW = NOTIF_ROOT + ".config.new"; /** The default schedule if not configured */ public static final int DEFAULT_SCHEDULE = 15; /** The JMX domain for configurations */ public static final String CONFIG_DOMAIN = "com.heliosapm.configuration"; /** The JMX domain for fixtures */ public static final String FIXTURE_DOMAIN = "com.heliosapm.fixture"; /** The JMX domain for services */ public static final String SERVICE_DOMAIN = "com.heliosapm.service"; /** The JMX domain for deployments */ public static final String DEPLOYMENT_DOMAIN = "com.heliosapm.deployment"; /** The JMX domain for data sources */ public static final String DATASOURCE_DOMAIN = "com.heliosapm.datasource"; /** The JMX domain for hot directories */ public static final String HOTDIR_DOMAIN = "com.heliosapm.hotdir"; /** The binding name for the binding */ public static final String BINDING_NAME = "_binding_"; /** * Indicates if the passed text is a comment line for this script's language * @param text The text to test * @return true if the passed text is a comment line for this script's language, false otherwise */ public boolean isCommentLine(String text); /** * Updates the executable * @param executable The executable * @param checksum The checksum of the source file * @param lastModified The last modified timestamp of the deployment */ public void setExecutable(final T executable, long checksum, long lastModified); /** * Performs any initialization required on a new executable */ public void initExcutable(); /** * Marks the deployment as broken * @param errorMessage The compilation error message * @param checksum The [broken] source checksum * @param lastModified The [broken] source last modification timestamp */ public void setFailedExecutable(final String errorMessage, long checksum, long lastModified); /** * Returns the executable deployment * @return the executable deployment */ public T getExecutable(); /** * Returns the local configuration for this deployment * @return the local configuration for this deployment */ public Configuration getConfiguration(); /** * Adds the passed configuration * @param config the incoming config */ public void addConfiguration(Map<String, Object> config); /** * Adds the passed configuration * @param key The config key * @param value The config value */ public void addConfiguration(String key, Object value); /** * Returns the config item with the passed key * @param key The config key to get the config for * @param type The type of the config value * @return the config value or null if not found */ public <E> E getConfig(String key, Class<E> type); // /** // * Triggers a config reload when a config item this deployment depends on changes // * @param dependency The JMX ObjectName of the config item this deployment depends on // * @param changedConfig The new config // */ // public void triggerConfigChange(final ObjectName dependency, final Map<String, Object> changedConfig); /** * Returns the config item with the passed key * @param key The config key to get the config for * @return the config value or null if not found */ public Object getConfig(String key); /** * Returns the status of the deployment * @return the status of the deployment */ public DeploymentStatus getStatus(); /** * Executes the underlying executable script * @return the execution return value */ public Object execute(); /** * Invokes a sub-invocable exposed by the executable * @param name The name of the sub-invocable * @param args The arguments to the sub-invocable * @return the sub-invocable invocation return value */ public Object invoke(String name, Object...args); /** * Makes an invocable call with no arguments and the result (if not null) is string converted * @param name The name of the invocable * @return the return value */ public String callInvocable(String name); /** * Returns the execution schedule for this deployment * @return the execution schedule for this deployment */ public ExecutionSchedule getExecutionSchedule(); /** * Activates the passed execution schedule for this depoyment * @param newSchedule the new execution schedule for this depoyment */ public void setExecutionSchedule(final ExecutionSchedule newSchedule); /** * Returns the JMX ObjectName of the configuration watched by this object * @return the JMX ObjectName of the configuration watched by this object */ public ObjectName getWatchedConfiguration(); }
package eiti.sag.facebookcrawler.accessor.jsoup; import java.util.HashMap; import java.util.Map; public class FacebookAuthCookies { private final String cUser; private final String datr; private final String xs; public FacebookAuthCookies(String cUser, String datr, String xs) { this.cUser = cUser; this.datr = datr; this.xs = xs; } public Map<String, String> asMap() { Map<String, String> map = new HashMap<>(); map.put("c_user", cUser); map.put("datr", datr); map.put("xs", xs); return map; } }
package com.msh; import io.micronaut.runtime.EmbeddedApplication; import io.micronaut.test.annotation.MockBean; import io.micronaut.test.extensions.junit5.annotation.MicronautTest; import jakarta.inject.Inject; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import javax.servlet.http.HttpServletRequest; /** * Created by IntelliJ IDEA. * User: mshaikh4 * Date: 30-08-2021 * Time: 18:05 * Year: 2021 * Project: micronauth-demo * Package: com.msh */ @MicronautTest public class HomeControllerTest { @Inject HomeController homeController; /*@Test void testItWorks() { Assertions.assertTrue(); }*/ }
package single; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; public class CustomerAction { private SessionFactory sessionFactory; public CustomerAction(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public Customer get(long id) { Customer customer = null; Session session = sessionFactory.openSession(); try { Transaction transaction = session.beginTransaction(); customer = (Customer) session.load(Customer.class, id); transaction.commit(); } finally { session.close(); } return customer; } }
package com.infor.models; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "tbl_inforuser") public class InforUser { public InforUser(){} @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "userid") private int userid; @Column(name = "firstname") private String firstname; @Column(name = "lastname") private String lastname; @Column(name = "contactnumber") private String contactnumber; @Column(name = "emailaddress") private String emailaddress; @Column(name = "inforaddress") private String inforaddress; @Column(name = "position") private String position; @Column(name = "username") private String username; @Column(name = "password") private String password; @Column(name = "gender") private String gender; public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public int getUserid() { return userid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public void setUserid(int userid) { this.userid = userid; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getContactnumber() { return contactnumber; } public void setContactnumber(String contactnumber) { this.contactnumber = contactnumber; } public String getEmailaddress() { return emailaddress; } public void setEmailaddress(String emailaddress) { this.emailaddress = emailaddress; } public String getInforaddress() { return inforaddress; } public void setInforaddress(String inforaddress) { this.inforaddress = inforaddress; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } }
package com.trs.om.CustomAuthorization; import com.trs.om.CustomAuthorization.bean.AccessToken; import com.trs.om.CustomAuthorization.bean.UserAuthorizationToken; import com.trs.om.dao.UserGroupDao; import com.trs.om.dao.impl.GenericHibernateDAO; import com.trs.om.generic.GenericQBCService; import com.trs.om.generic.GenericQBCServiceImpl; import com.trs.om.generic.QBCCriterion; import com.trs.om.util.PagedArrayList; import org.hibernate.SessionFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.List; @Service("accessTokenService") public class AccessTokenServiceImpl implements AccessTokenService{ private AccessTokenDao accessTokenDao; public AccessTokenDao getAccessTokenDao() { return accessTokenDao; } @Resource(name = "accessTokenDao") public void setAccessTokenDao(AccessTokenDao accessTokenDao) { this.accessTokenDao = accessTokenDao; } @Override @Transactional public void saveOrUpdate(AccessToken... entitys) { for (AccessToken entity : entitys){ accessTokenDao.makePersistent(entity); } } @Override @Transactional public void delete(Long... longs) { } @Override @Transactional public void deleteByHql(String hql) { } @Override @Transactional public AccessToken findById(Long aLong) { return null; } @Override @Transactional public List<AccessToken> findAll() { return null; } @Override @Transactional public List<AccessToken> findAll(QBCCriterion qbcCriterion) { return this.getAccessTokenDao().findAll(qbcCriterion); } @Override @Transactional public List<AccessToken> findAllNoInit(QBCCriterion qbcCriterions) { return null; } @Override @Transactional public PagedArrayList<AccessToken> findPaged(QBCCriterion qbcCriterion) { return null; } @Override @Transactional public long countRecords(QBCCriterion qbcCriterion) { return 0; } }
package consumer; import org.apache.kafka.clients.consumer.*; import java.util.Arrays; import java.util.Properties; import java.util.concurrent.TimeUnit; /** * @date 2019/9/18 17:07 * @author: <a href=mailto:xuzj@bonree.com>胥智钧</a> * @Description: **/ public class Consumer { private final static String topic = "TEST-XZJ"; public static void main(String[] args) { Consumer.base(topic); } public static void base(String topic) { Properties props = new Properties(); props.put("bootstrap.servers", "192.168.1.51:9092,192.168.1.52:9092,192.168.1.53:9092"); //当前consumer的分组Id props.put(ConsumerConfig.GROUP_ID_CONFIG, "test-xzj-group-1"); //设置自动提交偏移量 props.put("enable.auto.commit", "true"); //设置自动提交的频率 props.put("auto.commit.interval.ms", "1000"); props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); //消费者分区策略 props.put(ConsumerConfig.PARTITION_ASSIGNMENT_STRATEGY_CONFIG, "org.apache.kafka.clients.consumer.RangeAssignor"); KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props); //订阅topic,可以订阅多个"test","test2" consumer.subscribe(Arrays.asList(topic)); try { while (true) { //poll()用来获取消息,参数1000(毫秒)的含义是,当缓冲区中没有可用消息时,以此时间进行轮训等待。当设置为0时,理解返回当前可用的消息或者返回空。 ConsumerRecords<String, String> records = consumer.poll(0); for (ConsumerRecord<String, String> record : records) { System.err.println("offset:" + record.offset() + " key:" + record.key() + " value:" + record.value() + " partition:" + record.partition()); } TimeUnit.SECONDS.sleep(1); } } catch (InterruptedException e) { e.printStackTrace(); } } }
package jupiterpa.masterdata; import java.util.*; import jupiterpa.util.*; import jupiterpa.IMasterDataServer.*; public class MasterData { String type; Map<EID,Object> entries = new HashMap<EID,Object>(); public MasterData(String type) { this.type = type; } public void put(EID key, Object entry) { entries.put(key, entry); } public void remove(EID key) throws MasterDataException { Object entry = entries.remove(key); if (entry == null) { throw new MasterDataException("Entry " + key + "does not exist"); } } public Object get(EID key) { return entries.get(key); } public Collection<Object> getAll() { return entries.values(); } }
package pl.cwanix.opensun.db.controllers; import java.util.List; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import lombok.RequiredArgsConstructor; import pl.cwanix.opensun.db.entities.CharacterEntity; import pl.cwanix.opensun.db.repositories.CharacterEntityRepository; @RestController @RequestMapping("/character") @RequiredArgsConstructor public class CharacterController { private final CharacterEntityRepository characterEntityRepository; @PostMapping(path = "/create", produces = "application/json") public Integer create( @RequestParam("accountId") final int accountId, @RequestParam("name") final String name, @RequestParam("classCode") final int classCode, @RequestParam("heightCode") final int heightCode, @RequestParam("faceCode") final int faceCode, @RequestParam("hairCode") final int hairCode, @RequestParam("slot") final int slot) { return characterEntityRepository.create(accountId, name, classCode, heightCode, faceCode, hairCode, slot); } @DeleteMapping(path = "/delete", produces = "application/json") public Integer delete(@RequestParam("accountId") final int accountId, @RequestParam("slot") final int slot) { return characterEntityRepository.delete(accountId, slot); } @GetMapping(path = "/findByAccountId", produces = "application/json") public List<CharacterEntity> findByAccountId(@RequestParam("accountId") final int accountId) { return characterEntityRepository.findByAccountIdAndDeletedFalse(accountId); } @GetMapping(path = "/findById", produces = "application/json") public CharacterEntity findById(@RequestParam("id") final int id) { return characterEntityRepository.findByIdAndDeletedFalse(id); } @GetMapping(path = "/findByAccountIdAndSlot", produces = "application/json") public CharacterEntity findByAccountIdAndSlot(@RequestParam("accountId") final int accountId, @RequestParam("slot") final int slot) { return characterEntityRepository.findByAccountIdAndSlotAndDeletedFalse(accountId, slot); } @GetMapping(path = "/findFreeSlotByAccountId", produces = "application/json") public Integer findFreeSlotByAccountId(@RequestParam("accountId") final int accountId) { return characterEntityRepository.findFreeSlot(accountId); } @PostMapping(path = "/updatePosition", produces = "application/json") public Integer updatePosition( @RequestParam("id") final int id, @RequestParam("x") final float x, @RequestParam("y") final float y, @RequestParam("z") final float z, @RequestParam("angle") final int angle) { return characterEntityRepository.updatePosition(id, x, y, z, angle); } @PostMapping(path = "/updateStatistics", produces = "application/json") public Integer updateStatistics( @RequestParam("id") final int id, @RequestParam("attributeCode") final byte attributeCode) { return characterEntityRepository.updateStatistics(id, attributeCode); } }
package banyuan.day02.practice02; import java.util.Scanner; /** * @author 陈浩 */ public class P01 { public static void main(String[] args) { System.out.println("请输入数字:"); Scanner in = new Scanner(System.in); int X = in.nextInt(); System.out.println(((X % 2) == 0) ? "偶数" : "奇数"); } }
package tachyon.command; import java.io.IOException; import tachyon.Constants; import tachyon.TachyonURI; import tachyon.conf.CommonConf; import tachyon.util.CommonUtils; /** * Class for convenience methods used by TFsShell. */ public class Utils { /** * Removes Constants.HEADER / Constants.HEADER_FT and hostname:port information from a path, * leaving only the local file path. * * @param path The path to obtain the local path from * @return The local path in string format * @throws IOException */ public static String getFilePath(String path) throws IOException { path = validatePath(path); if (path.startsWith(Constants.HEADER)) { path = path.substring(Constants.HEADER.length()); } else if (path.startsWith(Constants.HEADER_FT)) { path = path.substring(Constants.HEADER_FT.length()); } String ret = path.substring(path.indexOf(TachyonURI.SEPARATOR)); return ret; } /** * Validates the path, verifying that it contains the <code>Constants.HEADER </code> or * <code>Constants.HEADER_FT</code> and a hostname:port specified. * * @param path The path to be verified. * @return the verified path in a form like tachyon://host:port/dir. If only the "/dir" or "dir" * part is provided, the host and port are retrieved from property, * tachyon.master.hostname and tachyon.master.port, respectively. * @throws IOException if the given path is not valid. */ public static String validatePath(String path) throws IOException { if (path.startsWith(Constants.HEADER) || path.startsWith(Constants.HEADER_FT)) { if (!path.contains(":")) { throw new IOException("Invalid Path: " + path + ". Use " + Constants.HEADER + "host:port/ ," + Constants.HEADER_FT + "host:port/" + " , or /file"); } else { return path; } } else { String hostname = System.getProperty("tachyon.master.hostname", "localhost"); String port = System.getProperty("tachyon.master.port", "" + Constants.DEFAULT_MASTER_PORT); if (CommonConf.get().USE_ZOOKEEPER) { return CommonUtils.concat(Constants.HEADER_FT + hostname + ":" + port, path); } return CommonUtils.concat(Constants.HEADER + hostname + ":" + port, path); } } }
package com.takshine.marketing.controller; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.takshine.core.service.CRMService; import com.takshine.marketing.domain.Activity; import com.takshine.marketing.domain.ActivityParticipant; import com.takshine.marketing.domain.Participant; import com.takshine.marketing.domain.SourceObject; import com.takshine.wxcrm.base.common.Constants; import com.takshine.wxcrm.base.common.ErrCode; import com.takshine.wxcrm.base.util.DateTime; import com.takshine.wxcrm.base.util.HttpClient3Post; import com.takshine.wxcrm.base.util.PropertiesUtil; import com.takshine.wxcrm.base.util.StringUtils; import com.takshine.wxcrm.base.util.UserUtil; import com.takshine.wxcrm.base.util.WxUtil; import com.takshine.wxcrm.base.util.cache.RedisCacheUtil; import com.takshine.wxcrm.base.util.runtime.SMSSentThread; import com.takshine.wxcrm.base.util.runtime.ThreadExecute; import com.takshine.wxcrm.base.util.runtime.ThreadRun; import com.takshine.wxcrm.domain.BusinessCard; import com.takshine.wxcrm.message.oauth.AccessToken; import com.takshine.wxcrm.message.userget.UserGet; /** * 参与用户处理类 */ @Controller @RequestMapping("/participant") public class ParticipantController { protected static Logger logger = Logger.getLogger(ParticipantController.class.getName()); // 从sugar系统获取 LOV和 用户 的服务 @Autowired @Qualifier("cRMService") private CRMService cRMService; /** * 验证是否过期 * @param startKey * @param endKey * @return */ public boolean differ(String startKey,String endKey){ int time = Integer.parseInt(PropertiesUtil.getMsgContext("service.time")); //缓存code的开始时间 String startTime = RedisCacheUtil.getString(startKey); String endTime = RedisCacheUtil.getString(endKey); if(StringUtils.isNotNullOrEmptyStr(startTime)&&StringUtils.isNotNullOrEmptyStr(endTime)){ int differTime = Integer.parseInt(StringUtils.getMargin(endTime, startTime)); if(differTime<=time){ return true; }else{ return false; } }else{ return false; } } /** * 报名 * * @param request * @param response * @return * @throws Exception */ @RequestMapping("/save") @ResponseBody public String add(HttpServletRequest request, HttpServletResponse response) throws Exception { // openId publicId String rowid = request.getParameter("activityid"); String opName=request.getParameter("opName"); String opDuty=request.getParameter("opDuty"); String opCompany=request.getParameter("opCompany"); String opSignature=request.getParameter("opSignature"); String opMobile=request.getParameter("opMobile"); String sourceid=request.getParameter("sourceid"); String source=request.getParameter("source"); logger.info("----ParticipantController ---- add ---验证码"); if("1".equals(PropertiesUtil.getMsgContext("service.open"))){ String code = request.getParameter("code"); String value = RedisCacheUtil.getString("Activity_Enlist_MessageCode_"+sourceid+rowid); if(StringUtils.isNotNullOrEmptyStr(value)&&value.contains(",")){ String[] strs = value.split(","); for(String str : strs){ if(code.equals(str)){ if(!differ("Activity_Enlist_MessageCode_StartTime"+sourceid+rowid+"_"+code,"Activity_Enlist_MessageCode_EndTime"+sourceid+rowid+"_"+code)){ return "errorCode"; } } } }else{ if(!differ("Activity_Enlist_MessageCode_StartTime"+sourceid+rowid+"_"+code,"Activity_Enlist_MessageCode_EndTime"+sourceid+rowid+"_"+code)){ return "errorCode"; } } } logger.info("----ParticipantController ---- add ---验证名报参数"); Map<String,String> map = new HashMap<String,String>(); // if(sourceid==null){ // return "-1"; // } if(opName==null||"".equals(opName.trim())){ return "-1"; } if(opMobile==null||"".equals(opMobile.trim())){ return "-1"; } if(StringUtils.isNotNullOrEmptyStr(opName)&&!StringUtils.regZh(opName)){ opName=new String(opName.getBytes("ISO-8859-1"),"UTF-8"); } if(StringUtils.isNotNullOrEmptyStr(opDuty)&&!StringUtils.regZh(opDuty)){ opDuty=new String(opDuty.getBytes("ISO-8859-1"),"UTF-8"); } if(StringUtils.isNotNullOrEmptyStr(opCompany)&&!StringUtils.regZh(opCompany)){ opCompany=new String(opCompany.getBytes("ISO-8859-1"),"UTF-8"); } if(StringUtils.isNotNullOrEmptyStr(opSignature)&&!StringUtils.regZh(opSignature)){ opSignature=new String(opSignature.getBytes("ISO-8859-1"),"UTF-8"); } logger.info("----ParticipantController ---- add ---获取活动信息"); Activity ac = cRMService.getDbService().getActivityService().getActivitySingle(rowid); if(null == ac || "".equals(ac.getId())){ return "-1"; } ActivityParticipant apc= new ActivityParticipant(); apc.setActivityid(rowid); if(!"meet".equals(ac.getType())){ if(cRMService.getDbService().getActivityParticipantService().countObjByFilter(apc)>=ac.getLimit_number()){ return "-1"; } } logger.info("----ParticipantController ---- add ---验证重复报名"); if(StringUtils.isNotNullOrEmptyStr(sourceid)){ //当前用户是否已经报名 apc.setSource(source); apc.setSourceid(sourceid); if(cRMService.getDbService().getActivityParticipantService().countObjByFilter(apc)>0){ return "-1"; } } logger.info("----ParticipantController ---- add ---保存报名信息"); Participant act = new Participant(); act.setOpName(opName); act.setOpMobile(opMobile); act.setOpDuty(opDuty); act.setOpCompany(opCompany); act.setOpSignature(opSignature); // if("WX".equals(source)){ // WxuserInfo wuInfo = new WxuserInfo(); // wuInfo.setParty_row_id(sourceid); // List<?> wuList = wxUserinfoService.findObjListByFilter(wuInfo); // if(null != wuList && wuList.size() > 0){ // wuInfo = (WxuserInfo)wuList.get(0); // } // act.setOpImage(wuInfo.getHeadimgurl()); // }else{ if(StringUtils.isNotNullOrEmptyStr(sourceid)){ SourceObject obj= cRMService.getDbService().getSourceObject2SourceSystemService().getSourceObject(sourceid, null); act.setOpImage(obj.getHeadImageUrl()); } //活动发起人 SourceObject actvityobj = cRMService.getDbService().getSourceObject2SourceSystemService().getSourceObject(ac.getCreateBy(), null); String openId = actvityobj.getOpenId(); // } boolean flag = cRMService.getDbService().getParticipantService().addParticipant(act,rowid,sourceid,source); if (!flag) { return "-1"; } logger.info("----ParticipantController ---- add ---如果不是匿名报名,则同步更新微信"); //如果不是匿名报名,则同步更新微信 if(StringUtils.isNotNullOrEmptyStr(sourceid)){ //报名成功,需同步更新微客用户信息(20150317修改) BusinessCard bc = new BusinessCard(); bc.setPartyId(sourceid); Object obj1 = cRMService.getDbService().getBusinessCardService().findObj(bc); if(null != obj1){ bc = (BusinessCard)obj1; bc.setPhone(opMobile); bc.setCompany(opCompany); bc.setPosition(opDuty); bc.setName(opName); cRMService.getDbService().getBusinessCardService().updateObj(bc); } } request.setAttribute("rowid", rowid); String content = ""; String activityUrl = ""; //发送微信消息通知活动发起人 if("meet".equals(ac.getType())){ content = opName+"报名了您的聚会【"+ac.getTitle()+"】,"; activityUrl = "zjwkactivity/meetdetail?id="+rowid+"&source="+source+"&sourceid="+ac.getCreateBy(); }else{ content = opName+"报名了您的活动【"+ac.getTitle()+"】,"; activityUrl = "zjwkactivity/detail?id="+rowid+"&source="+source+"&sourceid="+ac.getCreateBy(); } logger.info("----ParticipantController ---- add ---微信通知活动发起人,提示有人报名"); cRMService.getWxService().getWxRespMsgService().respCommCustMsgByOpenId(openId,null,null,content,activityUrl); return JSONArray.fromObject(act).toString(); } /** * 同步到联系人 * * @param request * @param response * @return * @throws Exception */ @RequestMapping("/syncContact") @ResponseBody public String syncContact(HttpServletRequest request, HttpServletResponse response) throws Exception { String sourceid=request.getParameter("sourceid"); String source=request.getParameter("source"); String participantid=request.getParameter("participantid"); if(sourceid==null||"".equals(sourceid.trim())||participantid==null||"".equals(participantid.trim())){ throw new Exception("错误编号:"+ErrCode.ERR_CODE_1001001+",错误描述:"+ErrCode.ERR_CODE_1001001_MSG); } Participant pc = (Participant)cRMService.getDbService().getParticipantService().findObjById(participantid); pc.setOrgId(request.getParameter("orgId")); String str= cRMService.getDbService().getParticipant2WkService().syncParticipant2Contact(source,sourceid, pc); return str; } /** * 更新用户 * @param request * @param response * @return * @throws Exception */ @RequestMapping("/updstatus") @ResponseBody public String updstatus(HttpServletRequest request,HttpServletResponse response)throws Exception{ String participantid = request.getParameter("participantid"); String flag = request.getParameter("flag"); String rowId = request.getParameter("actid"); Activity act = cRMService.getDbService().getActivityService().getActivitySingle(rowId); String status = ""; String content = ""; if("Y".equals(flag)){ status = "1"; content = "您报名参加的活动【"+act.getTitle()+"】已通过审核。"; }else if("N".equals(flag)){ status = "0"; content = "对不起,您报名的活动【"+act.getTitle()+"】未通过审核。"; } Participant parti = new Participant(); List<String> idList = new ArrayList<String>(); if(StringUtils.isNotNullOrEmptyStr(participantid)&&participantid.contains(",")){ String[] str = participantid.split(","); for(String id : str){ Participant participant = new Participant(); participant.setStatus(status); participant.setId(id); idList.add(id); parti.setStatus(status); Participant part = cRMService.getDbService().getParticipantService().getParticipantById(participant); /*Map<String, Object> map = new HashMap<String, Object>(); map.put("mobile", part.getOpMobile()); map.put("content",content); map.put("code", "123456"); HttpClient3Post.request(null,map);*/ ThreadRun thread = new SMSSentThread("123456", part.getOpMobile(),content); ThreadExecute.push(thread); } parti.setId_in(idList); } // int s = cRMService.getDbService().getParticipantService().updateStatus(participant); int s = cRMService.getDbService().getParticipantService().updateeBatchStatus(parti); if(s>0){ return "success"; }else{ return "error"; } } /** * 发送短信获取验证码 * @param request * @param response * @return * @throws Exception */ @RequestMapping("/sendMsg") @ResponseBody public String sendMsg(HttpServletRequest request,HttpServletResponse response)throws Exception{ String phoneNumber = request.getParameter("phonenumber"); String code = request.getParameter("code"); String sourceid = request.getParameter("sourceid"); String activityid = request.getParameter("activityid"); logger.info("ParticipantController sendMsg phoneNumber ==>"+phoneNumber); logger.info("ParticipantController sendMsg code ==>"+code); //缓存code的开始时间 RedisCacheUtil.setString("Activity_Enlist_MessageCode_StartTime"+sourceid+activityid+"_"+code, DateTime.currentTimeMillis()+""); String str = RedisCacheUtil.getString("Activity_Enlist_MessageCode_"+sourceid+activityid); if(StringUtils.isNotNullOrEmptyStr(str)){ str = str+","+code; } //缓存到redies RedisCacheUtil.setString("Activity_Enlist_MessageCode_"+sourceid+activityid,str); //缓存code的结束时间 RedisCacheUtil.setString("Activity_Enlist_MessageCode_EndTime"+sourceid+activityid+"_"+code, DateTime.currentTimeMillis()+""); String url = PropertiesUtil.getMsgContext("service.url1"); String content = PropertiesUtil.getMsgContext("message.model1").replace("$$code", code); Map<String, Object> map = new HashMap<String, Object>(); map.put("mobile", phoneNumber); map.put("content",content); map.put("code", code); ActivityParticipant ap = new ActivityParticipant(); ap.setActivityid(activityid); List<Participant> parList = cRMService.getDbService().getParticipantService().getParticipantListByActivity(ap); if(null!=parList&&parList.size()>0){ for(Participant part : parList){ String phonenumber = part.getOpMobile(); if(phonenumber.equals(phoneNumber)){ return "-1"; } } } String result = HttpClient3Post.request(url,map); if(StringUtils.isNotNullOrEmptyStr(result)&&result.equals(code)){ return "0"; }else{ return "1"; } } /** * 报名成功之后,进入报名成功页面 * @param request * @param response * @return * @throws Exception */ @RequestMapping("/msg") public String msg(HttpServletRequest request,HttpServletResponse response)throws Exception{ String username = request.getParameter("username"); String id = request.getParameter("id"); if(StringUtils.isNotNullOrEmptyStr(username)&&!StringUtils.regZh(username)){ username = new String(username.getBytes("ISO-8859-1"),"UTF-8"); } request.setAttribute("partyId", UserUtil.getCurrUser(request).getParty_row_id()); request.setAttribute("filepath","http://"+PropertiesUtil.getAppContext("file.service") + PropertiesUtil.getAppContext("file.service.userpath").replace("/usr", "").replace("/zjftp","")+"/"); String openId = UserUtil.getCurrUser(request).getOpenId(); //获取关注指尖微客的用户列表 AccessToken at = WxUtil.getAccessToken(Constants.APPID, Constants.APPSECRET); UserGet userGet = WxUtil.userGet("", at); for(String openid : userGet.getOpenidlist()){ if(openid.equals(openId)){ request.setAttribute("flag", "already"); } } Activity activity = cRMService.getDbService().getActivityService().getActivitySingle(id); request.setAttribute("activityname", activity.getTitle()); request.setAttribute("type", activity.getType()); request.setAttribute("username", username); return "activity/success_regist"; } public static void main(String[] args) throws UnsupportedEncodingException { String content = PropertiesUtil.getMsgContext("message.model1").replace("$$code", "123123"); String signature = PropertiesUtil.getMsgContext("msg.signature"); String msgmodule = new String((content+signature).getBytes("utf-8"),"utf-8"); System.out.println(msgmodule); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package au.org.ala.spatial.web.services; import au.org.ala.spatial.analysis.scatterplot.Scatterplot; import au.org.ala.spatial.analysis.scatterplot.ScatterplotDTO; import au.org.ala.spatial.analysis.scatterplot.ScatterplotStore; import au.org.ala.spatial.analysis.scatterplot.ScatterplotStyleDTO; import net.sf.json.JSONArray; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; /** * @author Adam */ @Controller public class ScatterplotWSController { private static Logger logger = Logger.getLogger(ScatterplotWSController.class); @RequestMapping(value = {"/ws/scatterplot/new", "/ws/scatterplotlist"}, method = {RequestMethod.POST, RequestMethod.GET}) public @ResponseBody Map envelope(@ModelAttribute ScatterplotDTO desc, @ModelAttribute ScatterplotStyleDTO style, HttpServletRequest req) { Scatterplot scat = new Scatterplot(desc, style, null); ScatterplotStore.addData(scat.getScatterplotDTO().getId(), scat); HashMap<String, Object> map = new HashMap<String, Object>(); if (desc.getLayers() != null && desc.getLayers().length > 2) { //scatterplot list map.put("htmlUrl", scat.getHtmlURL()); map.put("downloadUrl", scat.getDownloadURL()); } else { //scatterplot map.put("missingCount", scat.getScatterplotDataDTO().getMissingCount()); map.put("extents", scat.getScatterplotDataDTO().layerExtents()); map.put("layers", scat.getScatterplotDTO().getLayers()); map.put("imageUrl", scat.getImageURL()); } map.put("id", scat.getScatterplotDTO().getId()); return map; } @RequestMapping(value = "/ws/scatterplot/{id}", method = {RequestMethod.POST, RequestMethod.GET}) public @ResponseBody void update(@PathVariable("id") String id, @RequestParam(value = "minx", required = false) Double minx, @RequestParam(value = "miny", required = false) Double miny, @RequestParam(value = "maxx", required = false) Double maxx, @RequestParam(value = "maxy", required = false) Double maxy, HttpServletRequest req, HttpServletResponse response) { Scatterplot scat = ScatterplotStore.getData(id); if (scat != null && minx != null & miny != null && maxx != null && maxy != null) { scat.annotatePixelBox((int) minx.doubleValue(), (int) miny.doubleValue(), (int) maxx.doubleValue(), (int) maxy.doubleValue()); } try { OutputStream os = response.getOutputStream(); if (req.getRequestURI().toUpperCase().endsWith(".PNG")) { response.setHeader("Cache-Control", "max-age=86400"); //age == 1 day response.setContentType("image/png"); os.write(scat.getAsBytes()); } else { response.setContentType("application/json"); HashMap<String, Object> map = new HashMap<String, Object>(); JSONArray jo = JSONArray.fromObject(scat.getScatterplotStyleDTO().getSelection()); os.write(jo.toString().getBytes()); } os.flush(); os.close(); } catch (IOException e) { logger.error("error in outputting annotated scatterplot image as png", e); } } @RequestMapping(value = "/ws/scatterplot/style/{id}", method = {RequestMethod.POST, RequestMethod.GET}) public @ResponseBody Map style(@PathVariable("id") String id, @ModelAttribute ScatterplotStyleDTO style, HttpServletRequest req) { Scatterplot scat = ScatterplotStore.getData(id); if (scat != null) { scat.reStyle(style , req.getParameter("colourMode") != null , req.getParameter("red") != null , req.getParameter("green") != null , req.getParameter("blue") != null , req.getParameter("opacity") != null , req.getParameter("size") != null , req.getParameter("highlightWkt") != null ); ScatterplotStore.addData(id, scat); } HashMap<String, Object> map = new HashMap<String, Object>(); map.put("scatterplot", scat.getScatterplotDTO()); map.put("style", scat.getScatterplotStyleDTO()); return map; } @RequestMapping(value = "/ws/scatterplot/csv/{id}", method = {RequestMethod.POST, RequestMethod.GET}) public @ResponseBody String csv(@PathVariable("id") String id, HttpServletRequest req) { Scatterplot scat = ScatterplotStore.getData(id); return scat.getCSV(); } }
package com.yash.product_management.dao; import java.util.List; import com.yash.product_management.model.Product; public interface ProductDAO { /** * Returns a list of products * @return */ public List<Product> getAllProducts(); /** * gets the product by id * @param productId * @return */ public Product getProductByid(String productId); /** * used for saving products * @param product * @return */ public int save(Product product); /** * used for updating product details * @param product * @return */ public int update(Product product); /** * deleting a product * @param productId * @return */ public int delete(int productId); }
package enums; public enum PacketCommand { REQUEST_SENSOR_DATA, REQUEST_MODE, REQUEST_CONTROL_PARAMETERS, REQUEST_ROUTE_STATUS, REQUEST_MAP_LOCATION, REQUEST_LATERAL_DISTANCE, REQUEST_CONTROL_DECISION, REQUEST_STOP_LINE_FOUND, REQUEST_PASSED_DISTANCE, REQUEST_TEMPERATURE, SEND_CURRENT_DATETIME, SEND_MAP, SEND_PARAMETERS, SET_MODE, SEND_MAX_SPEED, REQUEST_TURN, SEND_NEW_ROUTE, REQUEST_START_ROUTE, REQUEST_EMERGENCY_STOP, REQUEST_CAMERA_IMAGE, REQUEST_HEARTBEAT, REQUEST_IR_DATA, REQUEST_DISCONNECT, CURRENT_SENSOR_DATA, CURRENT_MODE, CURRENT_CONTROL_PARAMETERS, CURRENT_ROUTE_STATUS, CURRENT_MAP_LOCATION, CURRENT_LATERAL_DISTANCE, CURRENT_CONTROL_DECISION, CURRENT_STOP_LINE_FOUND, CURRENT_PASSED_DISTANCE, CURRENT_TEMPERATURE, CAMERA_IMAGE, DATETIME_ACKNOWLEDGEMENT, MAP_ACKNOWLEDGEMENT, PARAMETERS_ACKNOWLEDGEMENT, MODE_ACKNOWLEDGEMENT, MAX_SPEED_ACKNOWLEDGEMENT, TURN_ACKNOWLEDGEMENT, NEW_ROUTE_ACKNOWLEDGEMENT, START_ROUTE_ACKNOWLEDGEMENT, EMERGENCY_STOP_ACKNOWLEDGEMENT, HEARTBEAT_ACKNOWLEDGEMENT, CURRENT_IR_DATA, DISCONNECT_ACKNOWLEDGEMENT, SERSOR_MODULE_ERROR, CONTROL_MODULE_ERROR, REMOTE_MODULE_COMMUNICATION_ERROR, CENTRAL_MODULE_ERROR; public static final int NUMBER_OF_REMOTE_REQUESTS = 23; public static final int NUMBER_OF_CENTRAL_RESPONSES = 23; public static final int NUMBER_OF_ERRORS = 4; public static final int REMOTE_REQUEST_BASE = 0x00; public static final int CENTRAL_RESPONS_BASE = 0xA0; public static final int ERROR_BASE = 0xD0; public byte code() { int ord = this.ordinal(); // Remote to Central if (ord < NUMBER_OF_REMOTE_REQUESTS) { return (byte)(REMOTE_REQUEST_BASE + ord); } // Central to Remote else if (ord < NUMBER_OF_REMOTE_REQUESTS + NUMBER_OF_CENTRAL_RESPONSES) { return (byte)(CENTRAL_RESPONS_BASE + ord - NUMBER_OF_REMOTE_REQUESTS); } // Errors (Remote to Central) else { return (byte)(ERROR_BASE + ord - (NUMBER_OF_REMOTE_REQUESTS + NUMBER_OF_CENTRAL_RESPONSES)); } } public PacketType getType() { switch (this) { case SEND_CURRENT_DATETIME: case REQUEST_CONTROL_DECISION: case REQUEST_STOP_LINE_FOUND: case REQUEST_PASSED_DISTANCE: case REQUEST_TEMPERATURE: case REQUEST_SENSOR_DATA: case REQUEST_MODE: case REQUEST_CONTROL_PARAMETERS: case REQUEST_ROUTE_STATUS: case REQUEST_MAP_LOCATION: case REQUEST_LATERAL_DISTANCE: case SEND_MAP: case SEND_PARAMETERS: case SET_MODE: case SEND_MAX_SPEED: case REQUEST_TURN: case SEND_NEW_ROUTE: case REQUEST_START_ROUTE: case REQUEST_EMERGENCY_STOP: case REQUEST_CAMERA_IMAGE: case REQUEST_HEARTBEAT: case REQUEST_IR_DATA: case REQUEST_DISCONNECT: return PacketType.REQUEST; case CURRENT_CONTROL_DECISION: case CURRENT_STOP_LINE_FOUND: case CURRENT_PASSED_DISTANCE: case CURRENT_TEMPERATURE: case CURRENT_SENSOR_DATA: case CURRENT_MODE: case CURRENT_CONTROL_PARAMETERS: case CURRENT_ROUTE_STATUS: case CURRENT_MAP_LOCATION: case CURRENT_LATERAL_DISTANCE: case CAMERA_IMAGE: case CURRENT_IR_DATA: return PacketType.DATA; case DATETIME_ACKNOWLEDGEMENT: case MAP_ACKNOWLEDGEMENT: case PARAMETERS_ACKNOWLEDGEMENT: case MODE_ACKNOWLEDGEMENT: case MAX_SPEED_ACKNOWLEDGEMENT: case TURN_ACKNOWLEDGEMENT: case NEW_ROUTE_ACKNOWLEDGEMENT: case START_ROUTE_ACKNOWLEDGEMENT: case EMERGENCY_STOP_ACKNOWLEDGEMENT: case HEARTBEAT_ACKNOWLEDGEMENT: case DISCONNECT_ACKNOWLEDGEMENT: return PacketType.ACKNOWLEDGEMENT; case SERSOR_MODULE_ERROR: case CONTROL_MODULE_ERROR: case REMOTE_MODULE_COMMUNICATION_ERROR: case CENTRAL_MODULE_ERROR: return PacketType.ERROR; default: throw new IllegalStateException("You forgot to add a new type of command in the 'getType' function... (" + this + ")"); } } public static PacketCommand fromByte(byte b) { int ord; if ((b & 0xff) < CENTRAL_RESPONS_BASE) { ord = (b & 0xff); } else if ((b & 0xff) < ERROR_BASE) { ord = (b & 0xff) - CENTRAL_RESPONS_BASE + NUMBER_OF_REMOTE_REQUESTS; } else { ord = (b & 0xff) - ERROR_BASE + NUMBER_OF_REMOTE_REQUESTS + NUMBER_OF_CENTRAL_RESPONSES; } if (ord >= PacketCommand.values().length) throw new IllegalArgumentException("Given byte is out of range. (Ordinal: " + ord + ")"); return PacketCommand.values()[ord]; } }
package com.example.instagram.fragments.like; import android.widget.ImageView; import android.widget.TextView; public class LikeModel { private int imageLikeCircle, imageLike; private String textLike; private long textData; public LikeModel() { } public LikeModel(int imageLikeCircle, int imageLike, String textLike, long textData) { this.imageLikeCircle = imageLikeCircle; this.imageLike = imageLike; this.textLike = textLike; this.textData = textData; } public int getImageLikeCircle() { return imageLikeCircle; } public void setImageLikeCircle(int imageLikeCircle) { this.imageLikeCircle = imageLikeCircle; } public int getImageLike() { return imageLike; } public void setImageLike(int imageLike) { this.imageLike = imageLike; } public String getTextLike() { return textLike; } public void setTextLike(String textLike) { this.textLike = textLike; } public long getTextData() { return textData; } public void setTextData(long textData) { this.textData = textData; } }
package com.halilayyildiz.game.model; import java.util.Map; import com.halilayyildiz.game.mancala.PlayerMove; public interface IGame { String getId(); GameType getType(); int getMaxPlayerCapacity(); boolean isFull(); int addPlayer(IPlayer player); void setActivePlayerId(String playerId); Map<String, IPlayer> getPlayers(); IGameStatus onPlayerMove(PlayerMove playerMove); IGameStatus getStatus(); }
package subjects.sample; import java.util.Stack; /** * @description: 给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。 * <p> * 你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。 * <p> * 示例 1: * <p> * 输入: * Tree 1 Tree 2 * 1 2 * / \ / \ * 3 2 1 3 * / \ \ * 5 4 7 * 输出: * 合并后的树: * 3 * / \ * 4 5 * / \ \ * 5 4 7 * 注意: 合并必须从两个树的根节点开始。 * <p> * <p> * <p> * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/merge-two-binary-trees * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * @author: dsy * @date: 2020/9/20 15:20 */ public class S617 { public TreeNode mergeTrees(TreeNode tree1, TreeNode tree2) { if (tree1 == null) { return tree2; } if (tree2 == null) { return tree1; } tree1.val += tree2.val; tree1.left = mergeTrees(tree1.left, tree2.left); tree1.right = mergeTrees(tree1.right, tree2.right); return tree1; } public static TreeNode mergeTrees2(TreeNode t1, TreeNode t2) { if (t1 == null) { return t2; } Stack<TreeNode[]> stack = new Stack<>(); stack.push(new TreeNode[]{t1, t2}); while (!stack.isEmpty()) { TreeNode[] t = stack.pop(); if (t[0] == null || t[1] == null) { continue; } t[0].val += t[1].val; if (t[0].left == null) { t[0].left = t[1].left; } else { stack.push(new TreeNode[]{t[0].left, t[1].left}); } if (t[0].right == null) { t[0].right = t[1].right; } else { stack.push(new TreeNode[]{t[0].right, t[1].right}); } } return t1; } public static void main(String[] args) { TreeNode tree1 = new TreeNode(1); TreeNode treeNode3 = new TreeNode(3); TreeNode treeNode2 = new TreeNode(2); treeNode3.left = new TreeNode(5); tree1.left = treeNode3; tree1.right = treeNode2; TreeNode tree2 = new TreeNode(2); TreeNode treeNode21 = new TreeNode(1); TreeNode treeNode23 = new TreeNode(3); TreeNode treeNode24 = new TreeNode(4); TreeNode treeNode27 = new TreeNode(7); treeNode21.right = treeNode24; treeNode23.right = treeNode27; tree2.left = treeNode21; tree2.right = treeNode23; TreeNode tree = mergeTrees2(tree1, tree2); System.out.println(tree); } } class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }
package com.wt.jiaduo.service; import org.springframework.data.domain.Page; import com.wt.jiaduo.dto.jpa.XiaomaiBaifenbing; public interface XiaomaiBaifenbingService { public Page<XiaomaiBaifenbing> findAll(Integer pageNum,Integer pageSize); public XiaomaiBaifenbing saveOne(XiaomaiBaifenbing xiaomaiBaifenbing); public XiaomaiBaifenbing modify(XiaomaiBaifenbing xiaomaiBaifenbing); public void delete(Integer id); public XiaomaiBaifenbing getOne(Integer id); }
import java.util.List; import com.google.api.gax.rpc.ApiStreamObserver; import com.google.cloud.speech.v1.SpeechRecognitionAlternative; import com.google.cloud.speech.v1.StreamingRecognizeResponse; import com.google.common.util.concurrent.SettableFuture; //defining a whole new class and override each of the methods for apistreamobserver class ResponseApiStreamingObserver<T> implements ApiStreamObserver<T> { private final SettableFuture<List<T>> future = SettableFuture.create(); private final List<T> messages = new java.util.ArrayList<T>(); @Override public void onNext(T message) { messages.add(message); com.google.cloud.speech.v1.StreamingRecognitionResult result = ((StreamingRecognizeResponse) message).getResultsList().get(0); SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0); System.out.println(alternative.getTranscript()); } @Override public void onError(Throwable t) { future.setException(t); } @Override //We call this right after public void onCompleted() { future.set(messages); } // Returns the SettableFuture object to get received messages / exceptions. public SettableFuture<List<T>> future() { return future; } }
package com.qq149.zhibj149.domain; import java.util.ArrayList; /** * 分类信息封装 * 使用Gson解析时,对象书写技巧 * 1.逢{}创建对象,逢【】创建结合(ArrayList) * 2.所有字段名称要和json返回字段高度一致 * @author zhuww * @description: 149 * @date :2019/5/20 15:40 */ public class NewsMenu { //根据json定义变量 public int retcode; public ArrayList<Integer> extend; public ArrayList< NewsMenuData> data; //侧边栏菜单对象 public class NewsMenuData{ public int id; public String title; public int type; public ArrayList<NewsTabData> children; @Override public String toString() { return "NewsMenuData{" + "title='" + title + '\'' + ", children=" + children + '}'; } } //页签的对象 public class NewsTabData{ public int id; public String title; public int type; public String url; @Override public String toString() { return "NewsTabData{" + "title='" + title + '\'' + '}'; } } @Override public String toString() { return "NewsMenu{" + "data=" + data + '}'; } }
package com.gld.znaqm.service.impl; import com.gld.znaqm.mapper.UserMapper; import com.gld.znaqm.model.User; import com.gld.znaqm.service.UserService; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; @Service public class UserServiceImpl implements UserService { @Resource private UserMapper userMapper; @Override public List<User> getUserList() { return userMapper.selectAll(); } }
/* * Copyright (C) 2007 Bastian Schenke (bastian.schenke(at)gmail.com) and * <a href="http://www-ist.massey.ac.nz/JBDietrich" target="_top">Jens Dietrich</a> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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 */ package test.nz.org.take.r2ml.a; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.Reader; import java.io.StringReader; import java.util.Iterator; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.Unmarshaller; import test.nz.org.take.r2ml.Log4jConfigurator; import de.tu_cottbus.r2ml.Condition; import nz.org.take.KnowledgeBase; import nz.org.take.KnowledgeElement; import nz.org.take.TakeException; import nz.org.take.r2ml.Normalizer; import nz.org.take.r2ml.R2MLDriver; import nz.org.take.r2ml.R2MLException; import nz.org.take.r2ml.R2MLKnowledgeSource; import nz.org.take.r2ml.reference.CheckOnlyNormalizer; import nz.org.take.r2ml.reference.DefaultDatatypeMapper; import nz.org.take.r2ml.reference.DefaultNameMapper; import junit.framework.TestCase; public class DisjunctiveConditionsTest extends TestCase { R2MLDriver driver = null; public DisjunctiveConditionsTest() { super("DisjunctiveConditionsTest"); } protected void setUp() throws Exception { super.setUp(); Log4jConfigurator.configure(); driver = R2MLDriver.get(); driver.setNameMapper(new DefaultNameMapper()); driver.setDatatypeMapper(new DefaultDatatypeMapper()); driver.setNormalizer(new CheckOnlyNormalizer()); } protected void tearDown() throws Exception { super.tearDown(); Log4jConfigurator.shutdown(); driver = null; } public void testGenericAtom() { driver.logger.info("##### testGenericAtom #####"); String testXml = "<r2ml:conditions\n" + " xmlns:r2ml='http://www.rewerse.net/I1/2006/R2ML'" + " xmlns:xs='http://www.w3.org/2001/XMLSchema'>\n" + " <r2ml:qf.Disjunction>\n" + " <r2ml:GenericAtom r2ml:predicateID='dummy'>\n" + " <r2ml:arguments>\n" + " <r2ml:TypedLiteral r2ml:datatypeID='xs:string' r2ml:lexicalValue='A'/>\n" + " </r2ml:arguments>\n" + " </r2ml:GenericAtom>\n" + " <r2ml:GenericAtom r2ml:predicateID='dummy'>\n" + " <r2ml:arguments>\n" + " <r2ml:TypedLiteral r2ml:datatypeID='xs:string' r2ml:lexicalValue='B'/>\n" + " </r2ml:arguments>\n" + " </r2ml:GenericAtom>\n" + " </r2ml:qf.Disjunction>\n" + "</r2ml:conditions>\n"; try { JAXBContext jc = JAXBContext .newInstance("de.tu_cottbus.r2ml:de.tu_cottbus.r2ml.r2mlv:de.tu_cottbus.dc");// Unmarshaller um = jc.createUnmarshaller(); Condition condition = (Condition)((JAXBElement)um.unmarshal(new StringReader(testXml))).getValue(); assertEquals("Normalizer returned another condition.", condition, driver.getNormalizer().normalize(condition)); } catch (Exception e) { fail("Exception occured" + e.toString()); } } public void testUnnormalizedCondition() { driver.logger.info("##### testUnnormalizedCondition #####"); String testXml = "<r2ml:conditions" + " xmlns:r2ml='http://www.rewerse.net/I1/2006/R2ML'" + " xmlns:xs='http://www.w3.org/2001/XMLSchema'>" + " <r2ml:qf.Disjunction>" + " <r2ml:GenericAtom r2ml:predicateID='pred1'>" + " <r2ml:arguments>" + " <r2ml:TypedLiteral r2ml:datatypeID='xs:string' r2ml:lexicalValue='A'/>" + " </r2ml:arguments>" + " </r2ml:GenericAtom>" + " <r2ml:GenericAtom r2ml:predicateID='pred2'>" + " <r2ml:arguments>" + " <r2ml:TypedLiteral r2ml:datatypeID='xs:string' r2ml:lexicalValue='B'/>" + " </r2ml:arguments>" + " </r2ml:GenericAtom>" + " </r2ml:qf.Disjunction>" + " <r2ml:qf.StrongNegation>" + " <r2ml:GenericAtom r2ml:predicateID='pred3'>" + " <r2ml:arguments>" + " <r2ml:TypedLiteral r2ml:datatypeID='xs:string' r2ml:lexicalValue='C'/>" + " </r2ml:arguments>" + " </r2ml:GenericAtom>" + " </r2ml:qf.StrongNegation>" + "</r2ml:conditions>"; try { JAXBContext jc = JAXBContext.newInstance("de.tu_cottbus.r2ml:de.tu_cottbus.r2ml.r2mlv:de.tu_cottbus.dc"); Unmarshaller um = jc.createUnmarshaller(); Condition condition = (Condition)((JAXBElement)um.unmarshal(new StringReader(testXml))).getValue(); Normalizer norm = new CheckOnlyNormalizer(); norm.normalize(condition); fail("Exception expected."); } catch (R2MLException r2mle) { assertEquals("Wrong Errorcode.", R2MLException.FEATURE_NOT_SUPPORTED, r2mle.getErrorCode()); } catch (Exception e) { fail("Exception occured" + e.toString()); } } public void testQfDisjunction() { driver.logger.info("##### testQfDisjunction #####"); String testXml = "<r2ml:conditions" + " xmlns:r2ml='http://www.rewerse.net/I1/2006/R2ML'" + " xmlns:xs='http://www.w3.org/2001/XMLSchema'>" + " <r2ml:qf.Disjunction>" + " <r2ml:GenericAtom r2ml:predicateID='dummy'>" + " <r2ml:arguments>" + " <r2ml:TypedLiteral r2ml:datatypeID='xs:string' r2ml:lexicalValue='A'/>" + " </r2ml:arguments>" + " </r2ml:GenericAtom>" + " <r2ml:GenericAtom r2ml:predicateID='dummy'>" + " <r2ml:arguments>" + " <r2ml:TypedLiteral r2ml:datatypeID='xs:string' r2ml:lexicalValue='B'/>" + " </r2ml:arguments>" + " </r2ml:GenericAtom>" + " </r2ml:qf.Disjunction>" + "</r2ml:conditions>"; try { JAXBContext jc = JAXBContext.newInstance("de.tu_cottbus.r2ml:de.tu_cottbus.r2ml.r2mlv:de.tu_cottbus.dc"); Unmarshaller um = jc.createUnmarshaller(); Condition condition = (Condition)((JAXBElement)um.unmarshal(new StringReader(testXml))).getValue(); Normalizer norm = new CheckOnlyNormalizer(); assertEquals(condition, norm.normalize(condition)); } catch (Exception e) { fail("Exception occured" + e.toString()); } } public void testNestedConjuntion() { driver.logger.info("##### testNestedConjuntion #####"); String testXml = "<r2ml:RuleBase " + " xmlns:xs='http://www.w3.org/2001/XMLSchema' " + " xmlns:r2ml='http://www.rewerse.net/I1/2006/R2ML'>" + " <r2ml:DerivationRuleSet r2ml:ruleSetID='DRStestNestedConjuntion'> " + " <r2ml:DerivationRule r2ml:ruleID='DRtestNestedConjuntion'>" + " <r2ml:conditions>" + " <r2ml:qf.Conjunction>" + " <r2ml:qf.Conjunction>" + " <r2ml:GenericAtom r2ml:predicateID='pred1'>" + " <r2ml:arguments>" + " <r2ml:TypedLiteral r2ml:datatypeID='xs:string' r2ml:lexicalValue='A'/>" + " </r2ml:arguments>" + " </r2ml:GenericAtom>" + " <r2ml:GenericAtom r2ml:predicateID='pred3'>" + " <r2ml:arguments>" + " <r2ml:TypedLiteral r2ml:datatypeID='xs:string' r2ml:lexicalValue='D'/>" + " </r2ml:arguments>" + " </r2ml:GenericAtom>" + " </r2ml:qf.Conjunction>" + " <r2ml:GenericAtom r2ml:predicateID='pred2'>" + " <r2ml:arguments>" + " <r2ml:TypedLiteral r2ml:datatypeID='xs:string' r2ml:lexicalValue='B'/>" + " </r2ml:arguments>" + " </r2ml:GenericAtom>" + " </r2ml:qf.Conjunction>" + " </r2ml:conditions>" + " <r2ml:conclusion>" + " <r2ml:GenericAtom r2ml:predicateID='pred3'>" + " <r2ml:arguments>" + " <r2ml:TypedLiteral r2ml:datatypeID='xs:string' r2ml:lexicalValue='C'/>" + " </r2ml:arguments>" + " </r2ml:GenericAtom>" + " </r2ml:conclusion>" + " </r2ml:DerivationRule>" + " </r2ml:DerivationRuleSet>" + "</r2ml:RuleBase>"; KnowledgeBase kb = null; try { StringReader input = new StringReader(testXml); R2MLKnowledgeSource kSrc = new R2MLKnowledgeSource(input); kb = kSrc.getKnowledgeBase(); } catch (R2MLException r2mle) { fail("Internal Error: " + r2mle.toString()); } catch (TakeException e) { fail("Internal error: " + e.toString()); } assertNotNull("No Knowledgebase returned!", kb); assertEquals("Wrong number of rules:", 1, kb.getElements().size()); Iterator<KnowledgeElement> it = kb.getElements().iterator(); assertEquals("Wrong number of conditions for rule", 3, ((nz.org.take.DerivationRule)it.next()).getBody().size()); } public void testMisc() { driver.logger.info("##### testMisc #####"); KnowledgeBase kb = null; try { Reader is = new FileReader(new File( "testsrc/test/nz/org/take/r2ml/a/DisjunctiveConditionsTest1.xml")); R2MLKnowledgeSource kSrc = new R2MLKnowledgeSource(is); kb = kSrc.getKnowledgeBase(); } catch (R2MLException r2mle) { fail("Internal Error: " + r2mle.toString()); } catch (TakeException e) { fail("Exception occured: " + e.toString()); } catch (FileNotFoundException e) { e.printStackTrace(); fail("FileNotFound: " + e.toString()); } assertNotNull("KnowledgeBase is null.", kb); assertEquals("KnowledgeBase contains the wrong number of rules.", 2, kb.getElements().size()); } }
package com.cnk.travelogix.custom.zif.erp.ws.opportunity; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for ZifProdCatActivities complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ZifProdCatActivities"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="FromDate" type="{urn:sap-com:document:sap:rfc:functions}date10"/> * &lt;element name="ToDate" type="{urn:sap-com:document:sap:rfc:functions}date10"/> * &lt;element name="NoOfAdults" type="{urn:sap-com:document:sap:rfc:functions}numeric2"/> * &lt;element name="NoOfChildren" type="{urn:sap-com:document:sap:rfc:functions}numeric2"/> * &lt;element name="Destination" type="{urn:sap-com:document:sap:rfc:functions}char20"/> * &lt;element name="Themes" type="{urn:sap-com:document:sap:rfc:functions}char5"/> * &lt;element name="MonthOfDeparture" type="{urn:sap-com:document:sap:rfc:functions}char5"/> * &lt;element name="YearOfDeparture" type="{urn:sap-com:document:sap:rfc:functions}char5"/> * &lt;element name="BudgetPerPerson" type="{urn:sap-com:document:sap:rfc:functions}char20"/> * &lt;element name="PhysicalIntensity" type="{urn:sap-com:document:sap:rfc:functions}char5"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ZifProdCatActivities", propOrder = { "fromDate", "toDate", "noOfAdults", "noOfChildren", "destination", "themes", "monthOfDeparture", "yearOfDeparture", "budgetPerPerson", "physicalIntensity" }) public class ZifProdCatActivities { @XmlElement(name = "FromDate", required = true) protected String fromDate; @XmlElement(name = "ToDate", required = true) protected String toDate; @XmlElement(name = "NoOfAdults", required = true) protected String noOfAdults; @XmlElement(name = "NoOfChildren", required = true) protected String noOfChildren; @XmlElement(name = "Destination", required = true) protected String destination; @XmlElement(name = "Themes", required = true) protected String themes; @XmlElement(name = "MonthOfDeparture", required = true) protected String monthOfDeparture; @XmlElement(name = "YearOfDeparture", required = true) protected String yearOfDeparture; @XmlElement(name = "BudgetPerPerson", required = true) protected String budgetPerPerson; @XmlElement(name = "PhysicalIntensity", required = true) protected String physicalIntensity; /** * Gets the value of the fromDate property. * * @return * possible object is * {@link String } * */ public String getFromDate() { return fromDate; } /** * Sets the value of the fromDate property. * * @param value * allowed object is * {@link String } * */ public void setFromDate(String value) { this.fromDate = value; } /** * Gets the value of the toDate property. * * @return * possible object is * {@link String } * */ public String getToDate() { return toDate; } /** * Sets the value of the toDate property. * * @param value * allowed object is * {@link String } * */ public void setToDate(String value) { this.toDate = value; } /** * Gets the value of the noOfAdults property. * * @return * possible object is * {@link String } * */ public String getNoOfAdults() { return noOfAdults; } /** * Sets the value of the noOfAdults property. * * @param value * allowed object is * {@link String } * */ public void setNoOfAdults(String value) { this.noOfAdults = value; } /** * Gets the value of the noOfChildren property. * * @return * possible object is * {@link String } * */ public String getNoOfChildren() { return noOfChildren; } /** * Sets the value of the noOfChildren property. * * @param value * allowed object is * {@link String } * */ public void setNoOfChildren(String value) { this.noOfChildren = value; } /** * Gets the value of the destination property. * * @return * possible object is * {@link String } * */ public String getDestination() { return destination; } /** * Sets the value of the destination property. * * @param value * allowed object is * {@link String } * */ public void setDestination(String value) { this.destination = value; } /** * Gets the value of the themes property. * * @return * possible object is * {@link String } * */ public String getThemes() { return themes; } /** * Sets the value of the themes property. * * @param value * allowed object is * {@link String } * */ public void setThemes(String value) { this.themes = value; } /** * Gets the value of the monthOfDeparture property. * * @return * possible object is * {@link String } * */ public String getMonthOfDeparture() { return monthOfDeparture; } /** * Sets the value of the monthOfDeparture property. * * @param value * allowed object is * {@link String } * */ public void setMonthOfDeparture(String value) { this.monthOfDeparture = value; } /** * Gets the value of the yearOfDeparture property. * * @return * possible object is * {@link String } * */ public String getYearOfDeparture() { return yearOfDeparture; } /** * Sets the value of the yearOfDeparture property. * * @param value * allowed object is * {@link String } * */ public void setYearOfDeparture(String value) { this.yearOfDeparture = value; } /** * Gets the value of the budgetPerPerson property. * * @return * possible object is * {@link String } * */ public String getBudgetPerPerson() { return budgetPerPerson; } /** * Sets the value of the budgetPerPerson property. * * @param value * allowed object is * {@link String } * */ public void setBudgetPerPerson(String value) { this.budgetPerPerson = value; } /** * Gets the value of the physicalIntensity property. * * @return * possible object is * {@link String } * */ public String getPhysicalIntensity() { return physicalIntensity; } /** * Sets the value of the physicalIntensity property. * * @param value * allowed object is * {@link String } * */ public void setPhysicalIntensity(String value) { this.physicalIntensity = value; } }
package com.espendwise.manta.service; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Propagation; import org.springframework.web.multipart.commons.CommonsMultipartFile; import org.apache.log4j.Logger; import com.espendwise.manta.model.view.UploadFileListView; import com.espendwise.manta.model.view.EntityHeaderView; import com.espendwise.manta.model.view.UploadSkuView; import com.espendwise.manta.model.data.BusEntityData; import com.espendwise.manta.model.data.UploadSkuData; import com.espendwise.manta.model.data.UploadData; import com.espendwise.manta.util.criteria.UploadFileListViewCriteria; import com.espendwise.manta.util.validation.ValidationException; import com.espendwise.manta.util.RefCodeNames; import com.espendwise.manta.dao.*; import javax.persistence.EntityManager; import java.util.List; import java.util.ArrayList; @Service public class UploadFileServiceImpl extends DataAccessService implements UploadFileService { private static final Logger logger = Logger.getLogger(UploadFileServiceImpl.class); @Override @Transactional(readOnly = true, propagation = Propagation.REQUIRED) public List<UploadFileListView> findUploadFilesByCriteria(UploadFileListViewCriteria criteria) { EntityManager entityManager = getEntityManager(); UploadFileDAO fileDao = new UploadFileDAOImpl(entityManager); return fileDao.findUploadFilesByCriteria(criteria); } @Override public UploadFileListView findUploadFile(Long storeId, Long uploadId) { EntityManager entityManager = getEntityManager(); UploadFileDAO fileDao = new UploadFileDAOImpl(entityManager); UploadFileListViewCriteria criteria = new UploadFileListViewCriteria(); criteria.setStoreId(storeId); criteria.setUploadId(uploadId); List<UploadFileListView> list = fileDao.findUploadFilesByCriteria(criteria); if (list != null && list.size()> 0) { return list.get(0); } else { return null; } } @Override public UploadData findUploadData(Long uploadId) { EntityManager entityManager = getEntityManager(); UploadFileDAO fileDao = new UploadFileDAOImpl(entityManager); return fileDao.findUploadData(uploadId); } @Override public List<UploadSkuData> findUploadSkuDataList(Long tableId) { EntityManager entityManager = getEntityManager(); UploadFileDAO fileDao = new UploadFileDAOImpl(entityManager); return fileDao.findUploadSkuDataList(tableId); } @Override public List<UploadSkuView> findUploadSkuViewList(Long tableId) { EntityManager entityManager = getEntityManager(); UploadFileDAO fileDao = new UploadFileDAOImpl(entityManager); return fileDao.findUploadSkuViewList(tableId); } @Override public EntityHeaderView findUploadFileHeader(Long uploadId) { EntityManager entityManager = getEntityManager(); UploadFileDAO fileDao = new UploadFileDAOImpl(entityManager); return fileDao.findUploadFileHeader(uploadId); } @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public UploadData saveUploadData(Long storeId, UploadData uploadData) { EntityManager entityManager = getEntityManager(); UploadFileDAO fileDao = new UploadFileDAOImpl(entityManager); return fileDao.saveUploadData(storeId, uploadData); } @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public UploadSkuData saveUploadSkuData(Long tableId, UploadSkuData skuData) { EntityManager entityManager = getEntityManager(); UploadFileDAO fileDao = new UploadFileDAOImpl(entityManager); return fileDao.saveUploadSkuData(tableId, skuData); } @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public List<UploadSkuView> saveUploadSkuViewList(Long tableId, List<UploadSkuView> skuViewList) { EntityManager entityManager = getEntityManager(); UploadFileDAO fileDao = new UploadFileDAOImpl(entityManager); return fileDao.saveUploadSkuViewList(tableId, skuViewList); } @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public List<UploadSkuData> saveUploadSkuDataList(Long tableId, List<UploadSkuData> skuDataList) { EntityManager entityManager = getEntityManager(); UploadFileDAO fileDao = new UploadFileDAOImpl(entityManager); return fileDao.saveUploadSkuDataList(tableId, skuDataList); } @Override public List<UploadSkuView> matchItems(Long storeId, Long uploadId, List<UploadSkuView> itemsToMatch) { EntityManager entityManager = getEntityManager(); UploadFileDAO fileDao = new UploadFileDAOImpl(entityManager); return fileDao.matchItems(storeId, uploadId, itemsToMatch); } @Override public List<UploadSkuView> getMatchedItems(Long storeId, Long uploadId, List<Long> pUploadSkuIds) { EntityManager entityManager = getEntityManager(); UploadFileDAO fileDao = new UploadFileDAOImpl(entityManager); return fileDao.getMatchedItems(storeId, uploadId, pUploadSkuIds); } @Override public Long getStoreCatalogId(Long storeId) { EntityManager entityManager = getEntityManager(); UploadFileDAO fileDao = new UploadFileDAOImpl(entityManager); return fileDao.getStoreCatalogId(storeId); } }
package com.espendwise.manta.web.validator; import org.apache.log4j.Logger; import com.espendwise.manta.model.view.ShoppingControlItemView; import com.espendwise.manta.util.Constants; import com.espendwise.manta.util.RefCodeNames; import com.espendwise.manta.util.Utility; import com.espendwise.manta.util.arguments.Args; import com.espendwise.manta.util.validation.CodeValidationResult; import com.espendwise.manta.util.validation.LongValidator; import com.espendwise.manta.util.validation.TextValidator; import com.espendwise.manta.util.validation.ValidationResult; import com.espendwise.manta.util.validation.Validators; import com.espendwise.manta.web.forms.AccountShoppingControlFilterResultForm; import com.espendwise.manta.web.resolver.NumberErrorWebResolver; import com.espendwise.manta.web.resolver.TextErrorWebResolver; import com.espendwise.manta.web.util.WebError; import com.espendwise.manta.web.util.WebErrors; public class AccountShoppingControlFilterResultFormValidator extends AbstractFormValidator{ private static final Logger logger = Logger.getLogger(AccountShoppingControlFilterResultFormValidator.class); public AccountShoppingControlFilterResultFormValidator() { super(); } @Override public ValidationResult validate(Object obj) { WebErrors errors = new WebErrors(); AccountShoppingControlFilterResultForm form = (AccountShoppingControlFilterResultForm) obj; LongValidator longValidator = Validators.getLongValidator(); TextValidator textValidator = Validators.getTextValidator(99, true); for (ShoppingControlItemView shoppingControl : form.getShoppingControls()) { String maxOrderQuantity = shoppingControl.getShoppingControlMaxOrderQty(); if (Utility.isSet(maxOrderQuantity) && !Constants.CHARS.ASTERISK.equalsIgnoreCase(maxOrderQuantity)) { CodeValidationResult vr = longValidator.validate(shoppingControl.getShoppingControlMaxOrderQty(), new NumberErrorWebResolver("admin.account.shoppingcontrol.label.maxOrderQuantity")); if (vr != null) { errors.putErrors(vr.getResult()); } } String restrictionDays = shoppingControl.getShoppingControlRestrictionDays(); if (Utility.isSet(restrictionDays) && !Constants.CHARS.ASTERISK.equalsIgnoreCase(restrictionDays)) { CodeValidationResult vr = longValidator.validate(shoppingControl.getShoppingControlRestrictionDays(), new NumberErrorWebResolver("admin.account.shoppingcontrol.label.restrictionDays")); if (vr != null) { errors.putErrors(vr.getResult()); } } if (Utility.isSet(shoppingControl.getShoppingControlAction())) { String action = shoppingControl.getShoppingControlAction(); if (!RefCodeNames.SHOPPING_CONTROL_ACTION_CD.APPLY.equalsIgnoreCase(action) && !RefCodeNames.SHOPPING_CONTROL_ACTION_CD.WORKFLOW.equalsIgnoreCase(action)) { errors.add(new WebError("validation.web.error.invalidValue", Args.i18nTyped("admin.account.shoppingcontrol.label.action"))); } } //account id is required Long accountId = shoppingControl.getShoppingControlAccountId(); if (!Utility.isSet(accountId) || accountId.longValue() == 0) { CodeValidationResult vr = textValidator.validate("", new TextErrorWebResolver("admin.account.label.accountId")); errors.putErrors(vr.getResult()); } //item id is required Long itemId = shoppingControl.getItemId(); if (!Utility.isSet(itemId) || itemId.longValue() == 0) { CodeValidationResult vr = textValidator.validate("", new TextErrorWebResolver("admin.global.filter.label.itemId")); errors.putErrors(vr.getResult()); } } return new MessageValidationResult(errors.get()); } }
package com.timmy.customeView.countdownTime; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.os.CountDownTimer; import android.support.annotation.Nullable; import android.text.Layout; import android.text.StaticLayout; import android.text.TextPaint; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.View; import com.timmy.R; /** * Created by admin on 2017/6/21. * 广告页面倒计时处理: * 1.使用CountDownTime实现倒计时功能 * 2. * <p> * <p> * 1000为倒计时时长 * 10为每隔10毫秒会调用一次onTick方法 * CountDownTimer countDownTimer = new CountDownTimer(1000,50) { * * @Override public void onTick(long millisUntilFinished) { * Log.d(TAG,"millisUntilFinished:"+millisUntilFinished); * } * @Override public void onFinish() { * Log.d(TAG,"onFinish:"); * } * }.start(); */ public class CountDownTimeView extends View { public static final String TAG = CountDownTimeView.class.getSimpleName(); private static final int BACKGROUND_COLOR = 0x50555555; private static final int PROGRESS_COLOR = Color.BLUE; private static final float PROGRESS_WIDTH = 10f; private static final float TEXT_SIZE = 50f; private static final String TEXT = "跳过广告"; private static final int TEXT_COLOR = 0xffffffff; private static final int TAG_WIDTH = 0; private static final int TAG_HEIGHT = 1; private static final int COUNT_DOWN_TIME = 3600; private float mTextSize; private int mProgressColor; private int mBackgroundColor; private float mProgressWidht; private final int mTextColor; private String mText; private Paint mCirclePaint; private Paint mProgressPaint; private TextPaint mTextPaint; private StaticLayout mStaticLayout; private int mWidth; private int mHeight; private int min; private RectF mOval; private CountDownTimer mCountDownTimer; private int mRadio = COUNT_DOWN_TIME / 100; private int mCountDownTime; private int mCurrProgress; private OnCountDownTimeListener mListener; public CountDownTimeView(Context context) { this(context, null); } public CountDownTimeView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public CountDownTimeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); Log.d(TAG, "CountDownTimeView -- "); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CountDownTimeView, defStyleAttr, 0); //获取各种属性值 /** * 圆盘的背景色 圆环颜色 圆环宽度 文字内容 文字颜色 文字大小 倒计时时间 */ mBackgroundColor = typedArray.getColor(R.styleable.CountDownTimeView_background_color, BACKGROUND_COLOR); mProgressColor = typedArray.getColor(R.styleable.CountDownTimeView_progress_color, PROGRESS_COLOR); mProgressWidht = typedArray.getDimension(R.styleable.CountDownTimeView_progress_width, PROGRESS_WIDTH); mText = typedArray.getString(R.styleable.CountDownTimeView_text); if (TextUtils.isEmpty(mText)) { mText = TEXT; } mTextSize = typedArray.getDimension(R.styleable.CountDownTimeView_text_size, TEXT_SIZE); mTextColor = typedArray.getColor(R.styleable.CountDownTimeView_text_color, TEXT_COLOR); mCountDownTime = typedArray.getInt(R.styleable.CountDownTimeView_count_down_timer, COUNT_DOWN_TIME); Log.d(TAG, "mCountDownTime:" + mCountDownTime); typedArray.recycle(); initConf(); } /** * 初始化画笔属性 * 需要画背景圆 * 画圆弧 * 画文字 */ private void initConf() { //背景圆画笔 mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG); mCirclePaint.setColor(mBackgroundColor); mCirclePaint.setStyle(Paint.Style.FILL); // mCirclePaint.setDither(); 增加性能 //圆弧画笔 mProgressPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mProgressPaint.setColor(mProgressColor); mProgressPaint.setStyle(Paint.Style.STROKE); mProgressPaint.setStrokeWidth(mProgressWidht); //文字画笔 mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); mTextPaint.setColor(mTextColor); mTextPaint.setTextSize(mTextSize); mTextPaint.setStyle(Paint.Style.STROKE); mTextPaint.setTextAlign(Paint.Align.CENTER); //使用StaticLayout实现文字绘制自动换行效果 int textWidth = (int) mTextPaint.measureText(mText.substring(0, (mText.length() + 1) / 2));//文字宽度的一半 mStaticLayout = new StaticLayout(mText, mTextPaint, textWidth, Layout.Alignment.ALIGN_NORMAL, 1f, 0, false); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { Log.d(TAG, "onMeasure"); setMeasuredDimension(setSuitableDimension(widthMeasureSpec, TAG_WIDTH), setSuitableDimension(heightMeasureSpec, TAG_HEIGHT) ); } private int setSuitableDimension(int measureSpec, int tag) { int mode = MeasureSpec.getMode(measureSpec); int size = MeasureSpec.getSize(measureSpec); if (mode != MeasureSpec.EXACTLY) { switch (tag) { case TAG_WIDTH: size = mStaticLayout.getWidth(); break; case TAG_HEIGHT: size = mStaticLayout.getHeight(); break; } } return size; } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); Log.d(TAG, "onSizeChanged"); mWidth = getMeasuredWidth(); mHeight = getMeasuredHeight(); min = Math.min(mWidth, mHeight); Log.d(TAG, "onSizeChanged mWidth:" + mWidth + ",mHeight:" + mHeight); //绘制圆弧的矩形范围 if (mWidth > mHeight) { mOval = new RectF(mWidth / 2 - min / 2 + mProgressWidht / 2, mProgressWidht / 2, mWidth / 2 + min / 2 - mProgressWidht / 2, mHeight - mProgressWidht / 2); } else { mOval = new RectF(mProgressWidht / 2, mHeight / 2 - min / 2 + mProgressWidht / 2, mWidth - mProgressWidht / 2, mHeight / 2 + min / 2 - mProgressWidht / 2); } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Log.d(TAG, "onDraw"); //画背景圆 canvas.drawCircle(mWidth / 2, mHeight / 2, min / 2, mCirclePaint); //画圆弧 canvas.drawArc(mOval, -90, 3.6f * (100 - mCurrProgress), false, mProgressPaint); //画文字-->画布居中,左上角为控制点 canvas.translate(mWidth / 2, mHeight / 2 - mStaticLayout.getHeight() / 2); mStaticLayout.draw(canvas); } /** * 开始倒计时 */ public void startCountDown() { mCountDownTimer = new CountDownTimer(mCountDownTime, mRadio) { //倒计时执行了多长时间-->根据millisUntilFinished值计算执行百分比 @Override public void onTick(long millisUntilFinished) { mCurrProgress = (int) ( (mCountDownTime -millisUntilFinished) * 100.0f/ mCountDownTime ); Log.d(TAG, "onTick--millisUntilFinished:" + millisUntilFinished + ",mCurrProgress:" + mCurrProgress+ ",--:"+(int) (millisUntilFinished* 100.0f / mCountDownTime )); invalidate(); if (mListener != null) { mListener.onProgress(mCurrProgress); } } @Override public void onFinish() { if (mListener != null) { mListener.onFinish(); } endCountDown(); } }.start(); } /** * 结束倒计时->性能考虑,置空 */ public void endCountDown() { if (mCountDownTimer != null) { mCountDownTimer.cancel(); mCountDownTimer = null; } } public void setOnCountDownTimeListener(OnCountDownTimeListener listener) { this.mListener = listener; } public interface OnCountDownTimeListener { //倒计时执行百分比 void onProgress(int progress); //倒计时结束 void onFinish(); } }
package Algorithm; public class a2 { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { int count=0; if (l1==null)return l2; if (l2==null)return l1; ListNode res=new ListNode(-1); ListNode cur=res; while (l1!=null||l2!=null){ int x=(l1==null)?0:l1.val; int y=(l2==null)?0:l2.val; int temp=x+y+count; if (temp>=10){ count=1; temp=temp-10; }else { count=0; } cur.next=new ListNode(temp); cur=cur.next; l1=(l1==null)?null:l1.next; l2=(l2==null)?null:l2.next; } if (count!=0){ cur.next=new ListNode(1); } return res.next; } public static void main(String[] args) { System.out.println(1l/10); } }
package com.paytechnologies.cloudacar; import java.util.HashMap; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.paytechnologies.DTO.NavDrawerItems; import com.paytechnologies.cloudacar.adapters.AdapterListForNavGrid; import com.paytechnologies.cloudacar.interfaces.INavigationHandler; import com.paytechnologies.util.Constants; import com.paytechnologies.util.FontFactory; import com.paytechnologies.util.NavigationDrawerSetup; import com.paytechnologies.util.SessionManager; import android.annotation.SuppressLint; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Intent; import android.content.res.Configuration; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.util.Log; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.view.MenuItem.OnActionExpandListener; import android.view.MenuItem.OnMenuItemClickListener; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.Button; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ShareActionProvider; import android.widget.TextView; @SuppressLint("NewApi") public class CallToBook extends SherlockFragmentActivity implements OnClickListener,INavigationHandler{ private String TAG = "CallToBook"; Button callTobook,missedTobook; // private ListView mDrawerList; // private DrawerLayout mDrawer; // private CustomActionBarDrawerToggle mDrawerToggle; // private String[] menuItems; private ShareActionProvider mShareActionProvider; private GridView mDrawerList; private DrawerLayout mDrawer; private NavigationDrawerSetup navDrawerSetup; private TextView txtPayout, txtTrip, txtHowItWorks, txtHeaderName; private ImageView imgHeaderName; private LinearLayout linearDrawerLayout; SessionManager session; String authuser,fromIntent; public void linearHeaderLayoutOnClickListener (View v) { Log.d (TAG, "##### linearHeaderLayoutOnClickListener called..."); return; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_call_to_book); init(); Intent i = getIntent(); fromIntent = i.getStringExtra("fromIntent"); session = new SessionManager(getApplicationContext()); HashMap<String, String> user = session.getUserAuth(); authuser = user.get(SessionManager.KEY_AUTHUSER); Log.d("cac", "Auth user"+authuser); // // enable ActionBar app icon to behave as action to toggle nav drawer // getActionBar().setDisplayHomeAsUpEnabled(true); // getActionBar().setHomeButtonEnabled(true); // mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout); // // // set a custom shadow that overlays the main content when the drawer // // opens // mDrawer.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); // _initMenu(); // // mDrawerToggle = new CustomActionBarDrawerToggle(this, mDrawer); // mDrawer.setDrawerListener(mDrawerToggle); callTobook.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub try { Intent callIntent1 = new Intent(Intent.ACTION_CALL); callIntent1.setData(Uri.parse("tel:08010006600")); startActivity(callIntent1); } catch (ActivityNotFoundException e) { Log.e("helloandroid dialing example", "Call failed", e); } } }); mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout); linearDrawerLayout = (LinearLayout) findViewById(R.id.main_drawer_linear); mDrawerList = (GridView) findViewById(R.id.main_lst_leftdrawer); txtHeaderName = (TextView) findViewById(R.id.main_txt_gridheader); txtHeaderName.setTypeface(FontFactory.getRobotoCondensedBold(this)); imgHeaderName = (ImageView) findViewById(R.id.drawergridheader_img_user); txtPayout = (TextView) findViewById(R.id.main_txtpayout); txtPayout.setOnClickListener(this); txtPayout.setTypeface(FontFactory.getRobotoCondensedBold(this)); txtTrip = (TextView) findViewById(R.id.main_txttrips); txtTrip.setOnClickListener(this); txtTrip.setTypeface(FontFactory.getRobotoCondensedBold(this)); txtHowItWorks = (TextView) findViewById(R.id.main_txthowitworks); txtHowItWorks.setOnClickListener(this); txtHowItWorks.setTypeface(FontFactory.getRobotoCondensedBold(this)); navDrawerSetup = new NavigationDrawerSetup(this, getActionBar(), mDrawerList, mDrawer, getResources().getString(R.string.callToBook),linearDrawerLayout,txtHeaderName,imgHeaderName); navDrawerSetup.setNavigationHandler(this); navDrawerSetup.InitializeDrawer(); navDrawerSetup.setIntentExtra("callTobook"); navDrawerSetup.setCurrentCategoryAndPosition(Constants.CATEGORY_HOWITWORKS, 1); txtHowItWorks.performClick(); AdapterListForNavGrid adapter = (AdapterListForNavGrid) mDrawerList.getAdapter(); ((NavDrawerItems)adapter.getItem(1)).setSelected(true); adapter.notifyDataSetChanged(); } @Override public void onBackPressed() { // TODO Auto-generated method stub super.onBackPressed(); if(fromIntent!=null){ if(fromIntent.equalsIgnoreCase("showPref")){ Intent showPref = new Intent(CallToBook.this,ShowPrefernces.class); startActivity(showPref); }else if(fromIntent.equalsIgnoreCase("travelPref")){ Intent travelPref = new Intent(CallToBook.this,TravelPrefences.class); startActivity(travelPref); }else if(fromIntent.equalsIgnoreCase("prof")){ Intent prof = new Intent(CallToBook.this,ProfessionalInformation.class); startActivity(prof); }else if(fromIntent.equalsIgnoreCase("login")){ Intent login = new Intent(CallToBook.this,Login.class); startActivity(login); }else if(fromIntent.equalsIgnoreCase("profile")){ Intent profile = new Intent(CallToBook.this,Profile.class); startActivity(profile); }else if(fromIntent.equalsIgnoreCase("newProfile")){ Intent newProfile= new Intent(CallToBook.this,NewProfile.class); startActivity(newProfile); }else if(fromIntent.equalsIgnoreCase("submitDoc")){ Intent newProfile= new Intent(CallToBook.this,Submit_document_address.class); startActivity(newProfile); }else if(fromIntent.equalsIgnoreCase("submitIndettity")){ Intent newProfile= new Intent(CallToBook.this,Submit_document_identity.class); startActivity(newProfile); }else if(fromIntent.equalsIgnoreCase("submitDocVehicle")){ Intent newProfile= new Intent(CallToBook.this,Submit_document_vehicle.class); startActivity(newProfile); }else if(fromIntent.equalsIgnoreCase("bookTrip")){ Intent BookTrip = new Intent(CallToBook.this,BookTrip.class); startActivity(BookTrip); }else if(fromIntent.equalsIgnoreCase("tripsDashboard")){ Intent BookTrip = new Intent(CallToBook.this,TripsDashboard.class); startActivity(BookTrip); }else if(fromIntent.equalsIgnoreCase("myTest")){ Intent BookTrip = new Intent(CallToBook.this,DashBoard.class); startActivity(BookTrip); }else if(fromIntent.equalsIgnoreCase("manageTrip")){ Intent BookTrip = new Intent(CallToBook.this,ManageTrip.class); startActivity(BookTrip); }else if(fromIntent.equalsIgnoreCase("registration")){ Intent BookTrip = new Intent(CallToBook.this,Registration.class); startActivity(BookTrip); } }else{ Intent login = new Intent(CallToBook.this,Login.class); startActivity(login); } } // private void _initMenu() { // // TODO Auto-generated method stub // // NsMenuAdapter mAdapter = new NsMenuAdapter(this); // // if(authuser.equalsIgnoreCase("true")){ // // mAdapter.addProfile(R.string.ns_menu_main_header_Profile); // // // --------------------- Add Header list1 ----------------------------------------------------- // mAdapter.addHeader(R.string.ns_menu_main_header_Payout); // // mAdapter.addItem(R.drawable.secured); // // // Add first block // menuItems = getResources().getStringArray( // R.array.ns_menu_items_one); // String[] menuItemsIcon = getResources().getStringArray( // R.array.ns_menu_items_icon_one); // // int res = 0; // for (String item : menuItems) { // // int id_title = getResources().getIdentifier(item, "string", // this.getPackageName()); // int id_icon = getResources().getIdentifier(menuItemsIcon[res], // "drawable", this.getPackageName()); // // NsMenuItemModel mItem = new NsMenuItemModel(id_title,id_icon); // // mAdapter.addItem(mItem); // res++; // } // //--------------------------------------------------- next header ----------------------------------------------------------------- // mAdapter.addHeader(R.string.ns_menu_main_header_trips); // // menuItems = getResources().getStringArray( // R.array.ns_menu_items_two); // // String[] menuItemsIcon1 = getResources().getStringArray( // R.array.ns_menu_items_icon_two); // // int res1=0; // for (String item : menuItems) { // // int id_title = getResources().getIdentifier(item, "string", // this.getPackageName()); // int id_icon = getResources().getIdentifier(menuItemsIcon1[res1], // "drawable", this.getPackageName()); // Log.d("id icomn", ""+id_icon); // // NsMenuItemModel mItem = new NsMenuItemModel(id_title,id_icon); // mAdapter.addItem(mItem); // res1++; // } // // //--------------------------------------------------- next header ----------------------------------------------------------------- // mAdapter.addHeader(R.string.ns_menu_main_header_cac); // // menuItems = getResources().getStringArray( // R.array.ns_menu_items_three); // // String[] menuItemsIcon2= getResources().getStringArray( // R.array.ns_menu_items_icon_three); // // int res3=0; // for (String item : menuItems) { // // int id_title = getResources().getIdentifier(item, "string", // this.getPackageName()); // int id_icon = getResources().getIdentifier(menuItemsIcon2[res3], // "drawable", this.getPackageName()); // Log.d("id icomn", ""+id_icon); // // NsMenuItemModel mItem = new NsMenuItemModel(id_title,id_icon); // mAdapter.addItem(mItem); // res3++; // } // // }if(authuser.equalsIgnoreCase("false")){ // // //--------------------------------------------------- next header ----------------------------------------------------------------- // mAdapter.addHeader(R.string.ns_menu_main_header_cac); // // menuItems = getResources().getStringArray( // R.array.ns_menu_items_three); // // String[] menuItemsIcon2= getResources().getStringArray( // R.array.ns_menu_items_icon_three); // // int res3=0; // for (String item : menuItems) { // // int id_title = getResources().getIdentifier(item, "string", // this.getPackageName()); // int id_icon = getResources().getIdentifier(menuItemsIcon2[res3], // "drawable", this.getPackageName()); // Log.d("id icomn", ""+id_icon); // // NsMenuItemModel mItem = new NsMenuItemModel(id_title,id_icon); // mAdapter.addItem(mItem); // res3++; // } // } // mDrawerList = (ListView) findViewById(R.id.drawer); // // if (mDrawerList != null) // mDrawerList.setAdapter(mAdapter); // // mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); // } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. navDrawerSetup.getDrawerToggle().syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); navDrawerSetup.getDrawerToggle().onConfigurationChanged(newConfig); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate menu resource file. getSupportMenuInflater().inflate(R.menu.share_via, menu); /** Getting the actionprovider associated with the menu item whose id is share */ // mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.menu_item_share).getActionProvider(); // // /** Setting a share intent */ // mShareActionProvider.setShareIntent(getDefaultShareIntent()); return super.onCreateOptionsMenu(menu); } // Call to update the share intent private Intent getDefaultShareIntent() { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT,"Extra Text"); return intent; } @Override public boolean onOptionsItemSelected(MenuItem item) { /* * The action bar home/up should open or close the drawer. * ActionBarDrawerToggle will take care of this. */ if(navDrawerSetup.getDrawerToggle().onOptionsItemSelected(getMenuItem(item))){ return true; } switch(item.getItemId()){ case R.id.menu_item_share: Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); sharingIntent.setType("text/plain"); String link_val ="https://play.google.com/store/apps/details?id=com.paytechnologies.cloudacar"; sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Check out this link to download CAC:"); sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, link_val); startActivity(Intent.createChooser(sharingIntent, "Share via")); break; } // Handle your other action bar items... return super.onOptionsItemSelected(item); } private class CustomActionBarDrawerToggle extends ActionBarDrawerToggle { public CustomActionBarDrawerToggle(Activity mActivity,DrawerLayout mDrawerLayout){ super( mActivity, mDrawerLayout, R.drawable.ic_drawer, R.string.ns_menu_open, R.string.ns_menu_close); } @Override public void onDrawerClosed(View view) { getActionBar().setTitle(getString(R.string.callToBook)); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } @Override public void onDrawerOpened(View drawerView) { getActionBar().setTitle(getString(R.string.callToBook)); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } } // private class DrawerItemClickListener implements ListView.OnItemClickListener { // // @Override // public void onItemClick(AdapterView<?> parent, View view, int position, // long id) { // // Highlight the selected item, update the title, and close the drawer // // update selected item and title, then close the drawer // // mDrawerList.setItemChecked(position, true); // Log.d("Postion is", ""+position); // // if(authuser.equalsIgnoreCase("true")){ // // // // if(position ==0){ // Log.d("Drwaer",""+mDrawerList.getChildAt(1)); // // //-----------------Go to update Profile------------- // //-----As of now it will go to the new profile page // // Intent myPlans =new Intent(BookTrip.this,NewProfile.class); // // startActivity(myPlans); // // overridePendingTransition(R.anim.fade_in, R.anim.fade_out); // } // if(position == 2){ // Intent myPlans =new Intent(CallToBook.this,NewModifiedCacPlans.class); // startActivity(myPlans); // overridePendingTransition(R.anim.fade_in, R.anim.fade_out); // } // if(position == 3){ // Intent myPlans =new Intent(CallToBook.this,MyPlan.class); // startActivity(myPlans); // overridePendingTransition(R.anim.fade_in, R.anim.fade_out); // } // if(position==5){ // // Intent inbox =new Intent(CallToBook.this,ManageTrip.class); // startActivity(inbox); // overridePendingTransition(R.anim.fade_in, R.anim.fade_out); // // } // if(position==6){ // // Intent bookeTrip =new Intent(CallToBook.this,BookTrip.class); // startActivity(bookeTrip); // overridePendingTransition(R.anim.fade_in, R.anim.fade_out); // // } // if(position==7){ // // //-----------Book Trip---------------- // Intent bookedTrip = new Intent(CallToBook.this,TripPendingRequest.class); // startActivity(bookedTrip); // overridePendingTransition(R.anim.fade_in, R.anim.fade_out); // // } // if(position==8){ // // Intent liveListTrack = new Intent(CallToBook.this,LiveTripUsersList.class); // startActivity(liveListTrack); // overridePendingTransition(R.anim.fade_in, R.anim.fade_out); // }if(position==9){ // // Intent liveListChat = new Intent(CallToBook.this,DashBoard.class); // startActivity(liveListChat); // overridePendingTransition(R.anim.fade_in, R.anim.fade_out); // } // if(position==10){ // // Intent tripsDashBoard =new Intent(CallToBook.this,TripsDashboard.class); // startActivity(tripsDashBoard); // overridePendingTransition(R.anim.fade_in, R.anim.fade_out); // } // if(position==12){ // // Intent howItWorks =new Intent(CallToBook.this,MyTestActivity.class); // howItWorks.putExtra("fromIntent", "callTobook"); // startActivity(howItWorks); // overridePendingTransition(R.anim.fade_in, R.anim.fade_out); // // }if(position==13){ // TextView tv = (TextView)mDrawerList.getChildAt(13).findViewById(R.id.menurow_title); // tv.setTextColor(getResources().getColor(R.color.Blue)); // // }if(position==16){ // // String mailTo="info@cloudacar.com"; // Intent email_intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto",mailTo, null)); // email_intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "CAC Comments"); // email_intent.putExtra(android.content.Intent.EXTRA_TEXT,""); // // startActivity(Intent.createChooser(email_intent, "Send email...")); } // if(position==14){ // Intent benifits= new Intent(CallToBook.this,Benifits.class); // benifits.putExtra("fromIntent", "callTobook"); // startActivity(benifits); // overridePendingTransition(R.anim.fade_in, R.anim.fade_out); // }if(position==15){ // Intent features= new Intent(CallToBook.this,Features.class); // features.putExtra("fromIntent", "callTobook"); // startActivity(features); // overridePendingTransition(R.anim.fade_in, R.anim.fade_out); // }if(position==17){ // Intent logOut= new Intent(CallToBook.this,LogOut.class); // startActivity(logOut); // overridePendingTransition(R.anim.fade_in, R.anim.fade_out); // } // }else{ // if(position==1){ // // Intent howItWorks =new Intent(CallToBook.this,MyTestActivity.class); // howItWorks.putExtra("fromIntent", "callTobook"); // startActivity(howItWorks); // overridePendingTransition(R.anim.fade_in, R.anim.fade_out); // }if(position==2){ // // TextView tv = (TextView)mDrawerList.getChildAt(2).findViewById(R.id.menurow_title); // tv.setTextColor(getResources().getColor(R.color.Blue)); // }if(position==5){ // // String mailTo="info@cloudacar.com"; // Intent email_intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto",mailTo, null)); // email_intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "CAC Comments"); // email_intent.putExtra(android.content.Intent.EXTRA_TEXT,""); // // startActivity(Intent.createChooser(email_intent, "Send email...")); } // if(position==3){ // // Intent benifits =new Intent(CallToBook.this,Benifits.class); // benifits.putExtra("fromIntent", "callTobook"); // startActivity(benifits); // overridePendingTransition(R.anim.fade_in, R.anim.fade_out); // // } // if(position==4){ // // Intent features =new Intent(CallToBook.this,Features.class); // features.putExtra("fromIntent", "callTobook"); // startActivity(features); // overridePendingTransition(R.anim.fade_in, R.anim.fade_out); // } // if(position==6){ // // Intent logout =new Intent(CallToBook.this,LogOut.class); // startActivity(logout); // overridePendingTransition(R.anim.fade_in, R.anim.fade_out); // } // } // mDrawer.closeDrawer(mDrawerList); // } // // } private void init() { // TODO Auto-generated method stub callTobook = (Button)findViewById(R.id.buttonToCall); missedTobook = (Button)findViewById(R.id.buttonToMissedCall); callTobook.setOnClickListener(this); missedTobook.setOnClickListener(this); } @Override public void onClick(View arg0) { switch (arg0.getId()) { case R.id.main_txthowitworks: navDrawerSetup.LoadHowItWorks(); ((TextView) arg0).setTextColor(Color.parseColor("#0399cd")); break; case R.id.buttonCall: // try { // Intent callIntent1 = new Intent(Intent.ACTION_CALL); // callIntent1.setData(Uri.parse("tel:08010006600")); // startActivity(callIntent1); // } catch (ActivityNotFoundException e) { // Log.e("helloandroid dialing example", "Call failed", e); // } break; case R.id.buttonToMissedCall: try { Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(Uri.parse("tel:08010007700")); startActivity(callIntent); } catch (ActivityNotFoundException e) { Log.e("helloandroid dialing example", "Call failed", e); } break; default: break; } } private android.view.MenuItem getMenuItem(final MenuItem item) { return new android.view.MenuItem() { @Override public int getItemId() { return item.getItemId(); } public boolean isEnabled() { return true; } @Override public boolean collapseActionView() { // TODO Auto-generated method stub return false; } @Override public boolean expandActionView() { // TODO Auto-generated method stub return false; } @Override public View getActionView() { // TODO Auto-generated method stub return null; } @Override public char getAlphabeticShortcut() { // TODO Auto-generated method stub return 0; } @Override public int getGroupId() { // TODO Auto-generated method stub return 0; } @Override public Intent getIntent() { // TODO Auto-generated method stub return null; } @Override public char getNumericShortcut() { // TODO Auto-generated method stub return 0; } @Override public int getOrder() { // TODO Auto-generated method stub return 0; } @Override public CharSequence getTitle() { // TODO Auto-generated method stub return null; } @Override public CharSequence getTitleCondensed() { // TODO Auto-generated method stub return null; } @Override public boolean hasSubMenu() { // TODO Auto-generated method stub return false; } @Override public boolean isActionViewExpanded() { // TODO Auto-generated method stub return false; } @Override public boolean isCheckable() { // TODO Auto-generated method stub return false; } @Override public boolean isChecked() { // TODO Auto-generated method stub return false; } @Override public boolean isVisible() { // TODO Auto-generated method stub return false; } @Override public android.view.MenuItem setActionView(View view) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setActionView(int resId) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setAlphabeticShortcut(char alphaChar) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setCheckable(boolean checkable) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setChecked(boolean checked) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setEnabled(boolean enabled) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setIcon(int iconRes) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setIntent(Intent intent) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setNumericShortcut(char numericChar) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setOnActionExpandListener(OnActionExpandListener listener) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setOnMenuItemClickListener(OnMenuItemClickListener menuItemClickListener) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setShortcut(char numericChar, char alphaChar) { // TODO Auto-generated method stub return null; } @Override public void setShowAsAction(int actionEnum) { // TODO Auto-generated method stub } @Override public android.view.MenuItem setShowAsActionFlags(int actionEnum) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setTitle(CharSequence title) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setTitle(int title) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setTitleCondensed(CharSequence title) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setVisible(boolean visible) { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setActionProvider( android.view.ActionProvider actionProvider) { // TODO Auto-generated method stub return null; } @Override public android.view.ActionProvider getActionProvider() { // TODO Auto-generated method stub return null; } @Override public android.view.SubMenu getSubMenu() { // TODO Auto-generated method stub return null; } @Override public Drawable getIcon() { // TODO Auto-generated method stub return null; } @Override public ContextMenuInfo getMenuInfo() { // TODO Auto-generated method stub return null; } @Override public android.view.MenuItem setIcon(Drawable arg0) { // TODO Auto-generated method stub return null; } }; } @Override public void InvalidateMenu() { // TODO Auto-generated method stub invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } }
/* * 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 mouse.server.network.event; import mouse.server.network.ClientConnectionHandler; /** * * @author Kevin Streicher <e1025890@student.tuwien.ac.at> */ public class PlayerJoinedEvent { private final ClientConnectionHandler clientConnectionHandler; public PlayerJoinedEvent(ClientConnectionHandler clientConnectionHandler) { this.clientConnectionHandler = clientConnectionHandler; } public ClientConnectionHandler getClientConnectionHandler() { return clientConnectionHandler; } }
package modi.member.pac2; import modi.member.pac1.A; public class C { public C() { A a =new A(); a.var1 =1; // a.var2 =1;//default(x) // a.var3 =1;//private(x) a.method1(); // a.method2();//default(x) // a.method3();//private(x) } }
package com.project.database.repository; import com.project.database.entities.VidomistMarkEntity; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface VidomistMarkRepository extends JpaRepository<VidomistMarkEntity, Integer> { Page<VidomistMarkEntity> findAllByVidomistMarkIdStudentCode(int studentCode, Pageable pageable); Page<VidomistMarkEntity> findAllByVidomistMarkIdVidomistNo(int vidomistNo, Pageable pageable); VidomistMarkEntity findByVidomistMarkIdVidomistNoAndVidomistMarkIdStudentCode(Integer vidomistNo, Integer StudentCode); }
public class CelestialObject { protected double velocity = 828000; public void setVelocity(double velocityVal) { velocity = velocityVal; } public double getVelocity() { return velocity; } }
package task73; /** * @author Igor */ public class Main1 { public static void main(String[] args) { double half = 1d/2d; double third = 1d/3d; int count = 0; for (int d = 5; d <= 12000; d++) { for (int n = (d/3)-1; n < (d/2)+1; n++) { if (gcd(n,d) == 1) { double temp = (double)n/d; if (temp > third && temp < half) count++; } } } System.out.println(count); } public static int gcd(int a, int b) { while (b != 0) { int temp = b; b = a % b; a = temp; } return a; } }
package com.rolandopalermo.facturacion.ec.web.controller; import java.io.File; import java.io.IOException; import javax.xml.bind.JAXBException; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; 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.rolandopalermo.facturacion.ec.bo.FirmadorBO; import com.rolandopalermo.facturacion.ec.common.exception.InternalServerException; import com.rolandopalermo.facturacion.ec.common.exception.ResourceNotFoundException; import com.rolandopalermo.facturacion.ec.common.exception.VeronicaException; import com.rolandopalermo.facturacion.ec.dto.rest.ByteArrayResponseDTO; import com.rolandopalermo.facturacion.ec.dto.rest.FacturaRequestDTO; import com.rolandopalermo.facturacion.ec.dto.rest.GuiaRemisionRequestDTO; import com.rolandopalermo.facturacion.ec.dto.rest.RetencionRequestDTO; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; @RestController @RequestMapping(value = "/api/v1/firmar") @Api(description = "Permite firmar un comprobante electrónico.") public class FirmaController { private static final Logger logger = Logger.getLogger(FirmaController.class); @Autowired private FirmadorBO firmadorBO; @ApiOperation(value = "Firma un comprobante electrónico") @PostMapping(value = "/factura", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ByteArrayResponseDTO> firmarFactura( @ApiParam(value = "Comprobante electrónico codificado como base64", required = true) @RequestBody FacturaRequestDTO request) { byte[] content = new byte[0]; try { if (!new File(request.getRutaArchivoPkcs12()).exists()) { throw new ResourceNotFoundException("No se pudo encontrar el certificado de firma digital."); } content = firmadorBO.firmarFactura(request); } catch (VeronicaException | JAXBException | IOException e) { logger.error("firmarFactura", e); throw new InternalServerException(e.getMessage()); } return new ResponseEntity<ByteArrayResponseDTO>(new ByteArrayResponseDTO(content), HttpStatus.OK); } @ApiOperation(value = "Firma un comprobante de retención") @PostMapping(value = "/retencion", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ByteArrayResponseDTO> firmarRetencion( @ApiParam(value = "Comprobante electrónico codificado como base64", required = true) @RequestBody RetencionRequestDTO request) { byte[] content = new byte[0]; try { if (!new File(request.getRutaArchivoPkcs12()).exists()) { throw new ResourceNotFoundException("No se pudo encontrar el certificado de firma digital."); } content = firmadorBO.firmarRetencion(request); } catch (VeronicaException | JAXBException | IOException e) { logger.error("firmarRetencion", e); throw new InternalServerException(e.getMessage()); } return new ResponseEntity<ByteArrayResponseDTO>(new ByteArrayResponseDTO(content), HttpStatus.OK); } @ApiOperation(value = "Firma un comprobante de Guia Remsion") @PostMapping(value = "/guia-remision", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<ByteArrayResponseDTO> firmarRemision( @ApiParam(value = "Comprobante electrónico codificado como base64", required = true) @RequestBody GuiaRemisionRequestDTO request) { byte[] content = new byte[0]; try { if (!new File(request.getRutaArchivoPkcs12()).exists()) { throw new ResourceNotFoundException("No se pudo encontrar el certificado de firma digital."); } content = firmadorBO.firmarGuiaRemision(request); } catch (VeronicaException | JAXBException | IOException e) { logger.error("firmarGuiaRemision", e); throw new InternalServerException(e.getMessage()); } return new ResponseEntity<ByteArrayResponseDTO>(new ByteArrayResponseDTO(content), HttpStatus.OK); } }
package com.app.sapient.grade.controller; 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.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.RestController; import com.app.sapient.grade.dto.TeacherDto; import com.app.sapient.grade.exception.TeacherNotFoundException; import com.app.sapient.grade.service.TeacherService; @RestController public class TeacherController { private static final Logger LOGGER = LoggerFactory.getLogger(TeacherController.class); private TeacherService teacherService; @Autowired public TeacherController(TeacherService teacherService) { this.teacherService = teacherService; } @PostMapping(value = "/teachers") public ResponseEntity<TeacherDto> configureTeacher(@RequestBody TeacherDto teacherDto) { try { TeacherDto configuredTeacherDto = teacherService.configureTeacher(teacherDto); return new ResponseEntity<>(configuredTeacherDto, HttpStatus.OK); } catch (Exception e) { LOGGER.error("Exception while adding teacher: {}", e.getMessage()); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } @GetMapping(value = "/teachers/{id}") public ResponseEntity<TeacherDto> getTeacherById(@PathVariable("id") Long teacherId) { try { TeacherDto configuredTeacherDto = teacherService.getTeacherById(teacherId); return new ResponseEntity<>(configuredTeacherDto, HttpStatus.OK); } catch(TeacherNotFoundException e) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } catch (Exception e) { LOGGER.error("Exception while getting teacher: {}", e.getMessage()); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } @DeleteMapping(value = "/teachers/{id}") public ResponseEntity<Void> deleteTeacherById(@PathVariable("id") Long teacherId) { try { teacherService.deleteTeacherById(teacherId); return new ResponseEntity<>(HttpStatus.OK); } catch (Exception e) { LOGGER.error("Exception while deleting teacher: {}", e.getMessage()); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } }
package tez.levent.feyyaz.kedi.receivers; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.util.Log; import android.widget.Toast; public class AutoStart extends BroadcastReceiver { final int REQUEST_CODE = 1; @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { SharedPreferences sharedPref = context.getSharedPreferences("preferences", Context.MODE_PRIVATE); Boolean notification = sharedPref.getBoolean("bildirim",true); String k_adi = sharedPref.getString("k_adi",null); if (notification && (k_adi!=null)){ Intent i = new Intent(context, AlarmStartService.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, i, 0); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000L, AlarmManager.INTERVAL_HOUR, pendingIntent); Log.d("AutoStart","Servis alarmı kuruldu!"); }else { Log.d("AutoStart","Servis kurulmadı! notification:" + String.valueOf(notification) + " k_adi:"+k_adi); } } } }
package com.sietecerouno.atlantetransportador.sections; import android.app.ActionBar; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.support.annotation.NonNull; import android.support.constraint.ConstraintLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.Gravity; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import com.crowdfire.cfalertdialog.CFAlertDialog; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.EventListener; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreException; import com.google.firebase.firestore.QuerySnapshot; import com.google.firebase.firestore.SetOptions; import com.sietecerouno.atlantetransportador.R; import com.sietecerouno.atlantetransportador.manager.Manager; import com.sietecerouno.atlantetransportador.utils.ChargeCreditCard; import com.sietecerouno.atlantetransportador.utils.NumberTextWatcherForThousand; import com.sietecerouno.atlantetransportador.utils.SendNotification; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Objects; import jp.wasabeef.glide.transformations.CropCircleTransformation; import me.zhanghai.android.materialratingbar.MaterialRatingBar; public class OfertActivity extends AppCompatActivity { String TAG = "GIO"; FirebaseFirestore db; FirebaseUser user; String clientToken = ""; String medioPagoID = ""; TextView myComments; EditText value_txt; Integer value = 0; Integer numCuotas = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ofert); Manager.getInstance().actualContext = this; //title getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); getSupportActionBar().setCustomView(R.layout.custom_bar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.greenApp))); //bg ImageView bg = (ImageView) findViewById(R.id.bg); Glide.with(bg.getContext()).load(R.drawable.bg_solo).into(bg); TextView title = (TextView) findViewById(R.id.action_bar_title); ImageView btnMenu = (ImageView) findViewById(R.id.btnMenu); btnMenu.setVisibility(View.INVISIBLE); title.setText("OFERTA SERVICIO PERSONALIZADO "); //get extra Intent myIntent = getIntent(); // gets the previously created intent final String typeKey = myIntent.getStringExtra("type"); final String idKey = myIntent.getStringExtra("idOferta"); String clientKey = myIntent.getStringExtra("idClient"); FirebaseFirestore.setLoggingEnabled(true); db = FirebaseFirestore.getInstance(); user = FirebaseAuth.getInstance().getCurrentUser(); final TextView btnNext = (TextView) findViewById(R.id.btn_next); final TextView btn_aceptar = (TextView) findViewById(R.id.btn_aceptar); final TextView btn_rechazar = (TextView) findViewById(R.id.btn_rechazar); final EditText contraoferta_txt = (EditText) findViewById(R.id.contraoferta_txt); final TextView contraoferta = (TextView) findViewById(R.id.contraoferta); contraoferta.setVisibility(View.INVISIBLE); final ConstraintLayout btns_contraoferta = (ConstraintLayout) findViewById(R.id.btns_contraoferta); myComments = (TextView) findViewById(R.id.comment); value_txt = (EditText) findViewById(R.id.value); value_txt.addTextChangedListener(new NumberTextWatcherForThousand(value_txt)); if(Objects.equals("Pendiente", typeKey) || Objects.equals("Contraoferta", typeKey) || Objects.equals("Rechazado", typeKey)) { btnNext.setVisibility(View.INVISIBLE); db.collection("pedidos_personalizados").document(Manager.getInstance().idPersonalizadoDoc) .collection("ofertas") .document(idKey) .get() .addOnCompleteListener( new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if (task.isSuccessful()) { myComments.setText(task.getResult().getData().get("comentario").toString()); value_txt.setText(task.getResult().getData().get("oferta").toString()); value_txt.setEnabled(false); myComments.setEnabled(false); if(Objects.equals("Contraoferta", typeKey)) { contraoferta_txt.addTextChangedListener(new NumberTextWatcherForThousand(contraoferta_txt)); contraoferta_txt.setText(task.getResult().getLong("contraoferta").toString()); value = Integer.parseInt(task.getResult().getLong("contraoferta").toString()); contraoferta.setVisibility(View.VISIBLE); btns_contraoferta.setVisibility(View.VISIBLE); btn_aceptar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Create Alert using Builder CFAlertDialog.Builder pDialog = new CFAlertDialog.Builder(OfertActivity.this) .setCornerRadius(20) .setTextGravity(Gravity.CENTER) .setTitle("¿ Estas seguro que deseas aceptar la contraoferta?") .setDialogStyle(CFAlertDialog.CFAlertStyle.ALERT) .addButton("NO", Color.parseColor("#FFFFFF"), Color.parseColor("#FF0000"), CFAlertDialog.CFAlertActionStyle.NEGATIVE, CFAlertDialog.CFAlertActionAlignment.JUSTIFIED, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { dialog.dismiss(); } }) .addButton("SI", Color.parseColor("#FFFFFF"), Color.parseColor("#578936"), CFAlertDialog.CFAlertActionStyle.POSITIVE, CFAlertDialog.CFAlertActionAlignment.JUSTIFIED, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { DocumentReference docRefT = db.collection("usuarios").document(user.getUid()); DocumentReference docRefV = db.collection("vehiculos").document(Manager.getInstance().vehicleSelected); //CHANGE ID BY ADMIN Map<String, Object> data = new HashMap<>(); data.put("estado_actual", 2); data.put("transportista", docRefT); data.put("vehiculo_obj", docRefV); db.collection("pedidos_personalizados").document(Manager.getInstance().idPersonalizadoDoc).set(data, SetOptions.merge()); // Update one field, creating the document if it does not already exist. Map<String, Object> dataPedido = new HashMap<>(); Map<String, Date> estado = new HashMap<>(); estado.put("en_curso", new Date()); dataPedido.put("valor", value); dataPedido.put("transportista", docRefT); dataPedido.put("estado", estado); dataPedido.put("estado_actual", 2); dataPedido.put("vehiculo_obj", docRefV); db.collection("pedidos").document(Manager.getInstance().idPersonalizado).set(dataPedido, SetOptions.merge()); sendPush("Tu servicio fue aceptado","aceptaron tu contra oferta",clientToken); checkPay(); finish(); } }); pDialog.show(); } }); btn_rechazar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Create Alert using Builder CFAlertDialog.Builder pDialog = new CFAlertDialog.Builder(OfertActivity.this) .setCornerRadius(20) .setTextGravity(Gravity.CENTER) .setTitle("¿ Estas seguro que deseas rechazar la contraoferta?") .setDialogStyle(CFAlertDialog.CFAlertStyle.ALERT) .addButton("NO", Color.parseColor("#FFFFFF"), Color.parseColor("#FF0000"), CFAlertDialog.CFAlertActionStyle.NEGATIVE, CFAlertDialog.CFAlertActionAlignment.JUSTIFIED, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { dialog.dismiss(); } }) .addButton("SI", Color.parseColor("#FFFFFF"), Color.parseColor("#578936"), CFAlertDialog.CFAlertActionStyle.POSITIVE, CFAlertDialog.CFAlertActionAlignment.JUSTIFIED, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Map<String, Object> data = new HashMap<>(); data.put("estado", false); db.collection("pedidos_personalizados").document(Manager.getInstance().idPersonalizadoDoc).collection("ofertas").document(idKey).set(data, SetOptions.merge()); sendPush("Tu oferta fue rechazada"," no aceptaron tu oferta",clientToken); finish(); } }); pDialog.show(); } }); }else{ btns_contraoferta.setVisibility(View.GONE); } } else { Log.i(TAG, "Error getting documents: ", task.getException()); } } }); }else{ btnNext.setVisibility(View.VISIBLE); } final ImageView icon = (ImageView) findViewById(R.id.photoUser); final MaterialRatingBar myRate = (MaterialRatingBar) findViewById(R.id.myRate); final TextView name = (TextView) findViewById(R.id.name); // set USER info from db user DocumentReference docRefUser = db.collection("usuarios").document(clientKey); docRefUser.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if (task.isSuccessful()) { DocumentSnapshot document = task.getResult(); if (document != null) { CropCircleTransformation cropCircleTransformation = new CropCircleTransformation(); String completeName = document.getData().get("nombre") + " " + document.getData().get("apellido"); Long lg = (Long) document.getData().get("calificacion"); myRate.setRating(lg.intValue()); name.setText(completeName); if(document.getData().get("token") != null) clientToken = (String) document.getData().get("token"); else clientToken = ""; Manager.getInstance().actualTokenPush = clientToken; Glide.with(icon.getContext()) .load(document.getData().get("foto").toString()) .apply(RequestOptions.bitmapTransform(cropCircleTransformation)) .into(icon); } else { Log.i(TAG, "No such document inside"); } } else { Log.i(TAG, "get failed with inside", task.getException()); } } }); btnNext.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Update one field, creating the document if it does not already exist. Map<String, Object> data = new HashMap<>(); DocumentReference docRefUser = db.collection("usuarios").document(user.getUid()); DocumentReference docRefV = db.collection("vehiculos").document(Manager.getInstance().vehicleSelected); //Integer _num = Integer.parseInt(value_txt.getText().toString()); Integer _num = Integer.parseInt(NumberTextWatcherForThousand.trimCommaOfString(value_txt.getText().toString())); data.put("transportista", docRefUser); data.put("estado", true); data.put("comentario", myComments.getText().toString()); data.put("oferta", _num); data.put("vehiculo", docRefV); db.collection("pedidos_personalizados").document(Manager.getInstance().idPersonalizadoDoc).collection("ofertas").document().set(data); sendPush("Nueva oferta","Tu servicio tiene una nueva oferta",clientToken); finish(); } }); } private void checkPay() { DocumentReference docRef = db.collection("pedidos").document(Manager.getInstance().idPersonalizado); docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if (task.isSuccessful()) { DocumentSnapshot document = task.getResult(); if (document.exists()) { DocumentReference payRef = (DocumentReference) task.getResult().getData().get("mediosPago"); medioPagoID = payRef.getId(); Manager.getInstance().actualId_to_charge = Manager.getInstance().idPersonalizado; Manager.getInstance().actualService = "personalizado"; // set CUOTAS info from db user payRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if (task.isSuccessful()) { DocumentSnapshot document = task.getResult(); if (document.exists()) { String cuotas = document.getData().get("cuotas").toString(); Log.i(TAG, cuotas); numCuotas = Integer.parseInt(cuotas); ChargeCreditCard chargeCreditCard = new ChargeCreditCard(); chargeCreditCard.charge(value,medioPagoID,numCuotas); } else { Log.i(TAG, "No such document inside"); } } else { Log.i(TAG, "get failed with inside", task.getException()); } } }); } else { Log.d(TAG, "No such document"); } } else { Log.d(TAG, "get failed with ", task.getException()); } } }); } private void sendPush(String _title, String _body, String _to) { SendNotification sendNotification = new SendNotification(); sendNotification._id = _to; sendNotification._body = _body; sendNotification._title = _title; sendNotification.execute(); } @Override protected void onDestroy() { super.onDestroy(); Manager.getInstance().actualContext = null; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; default: return super.onOptionsItemSelected(item); } } }
import java.util.*; import java.util.Arrays; import java.math.BigInteger; public class Main { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < arr.length; i++) { arr[i] = sc.nextInt(); } int[] t = new int[n]; int min = Integer.MAX_VALUE; for (int i = 0; i < arr.length; i++) { int x = (arr[i]-i)/n; if(arr[i] - i < 0) t[i] = 0; else if(x*n==arr[i]-i) t[i] = x; else t[i] = x+1; if(t[i] < min) min = t[i]; } // System.out.println(Arrays.toString(t)); for (int i = 0; i < t.length; i++) { if(t[i]==min) { System.out.println(i+1); break; } } } }
package blackjackbuildone; //Austin //Luis import java.io.IOException; import java.util.Scanner; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Scanner; /**** * <3 = hearts * <> = diamond * $$ = Spade * ** = Club */ public class Main { private static Scanner input = new Scanner(System.in); /*Fields for logging in purposes*/ private static String username; private static String passwd; /*Fields for statistics purposes*/ private static int wins; private static int loses; private static int extremeWins; private static int fNRounds; private static int nBJROunds; private static int fFRounds; private static int bJCount; private static int creditsEarned; private static int creditsLost; private static int highestCredits; private static int bankRuptcies; /*New players are always defaulted to credits*/ private static String currency = "credits"; /*Instantiate a currentPlayer Player object*/ private static Player currentPlayer = new Player (username, passwd, wins, loses, extremeWins, fNRounds, nBJROunds, fFRounds, bJCount, creditsEarned, creditsLost, highestCredits, bankRuptcies, currency); public static void main(String[] args) throws IOException, InterruptedException { ProjectFileIO_v2.readFile(); System.out.println("Welcome to BlackJack Extreme\nPlease log in :)\n"); logIn(); isNewPlayer(username); while(!displayMenu()); } static void logIn() throws IOException { username = IR4.getString("Alias: "); currentPlayer.setName(username); passwd = IR4.getString("Password: "); checkPassword(username, passwd); currentPlayer.setPassword(passwd); } /**************************************************************************** Checks the password whether it's correct, depending on the user name entered The user can log in as a different user by entering q ****************************************************************************/ static void checkPassword(String user, String pass) throws IOException { //Surprised this mess works for(Player x: ProjectFileIO_v2.getPlayerArrayList()) { if(username.equals(x.getName())) { while(!passwd.equals(x.getPassword())) { System.err.println("Wrong password, try again, or press 'q' to change alias"); System.out.print("Password: "); passwd = input.next(); if(passwd.equals("q")) { logIn(); break; } } } } } static void isNewPlayer(String user) throws IOException { if(ProjectFileIO_v2.addNewPlayer(currentPlayer)) { System.out.println("Welcome to the club " + currentPlayer.getName()); ProjectFileIO_v2.writeFile(); } else { System.out.println("Welcome back " + ProjectFileIO_v2.getPlayer(currentPlayer.getName(), passwd).getName() + "!"); } } static boolean displayMenu() throws IOException, InterruptedException { boolean quit = false; System.out.println(" +----------------------------------------------------------------------------------+\n" + " | |\n" + " | __ __ __ __ __ |\n" + " | | | | | | | (__) | | |\n" + " | | |__ | | __ _ ___ | | __ __ __ _ ___ | | __ |\n" + " | | * \\ | |/ _` | / __|| |/ / | |/ _ ` | / __|| |/ / |\n" + " | | |_) || | (_| || (__ | < | | (_| || (__ | < |\n" + " | |__*__ / |__|\\ __'_| \\ ___||__|\\__\\ | |\\ __ '_| \\ ___||__|\\__\\ |\n" + " | __/ | |\n" + " | |_____/ |\n" + " | _______ _____________ ________ ________ | \n" + " | | ___\\ \\ / /_ _| ___ \\ ___| \\/ | ___| | \n" + " | | |__ \\ V / | | | |_/ / |__ | . . | |__ | \n" + " | | __| / \\ | | | /| __|| |\\/| | __| | \n" + " | | |___/ /^\\ \\ | | | |\\ \\| |___| | | | |___ | \n" + " | \\____/\\/ \\/ \\_/ \\_| \\_\\____/\\_| |_|____/ |\n" + " +==================================================================================+"); System.out.printf(" %-1s%-59s%10s", "| Signed in as: ", ProjectFileIO_v2.getPlayer(currentPlayer.getName(), passwd).getName(), "|\n"); System.out.println(" | |\n" + " | 1. Play |\n" + " | 2. Settings |\n" + " | 3. Statistics |\n" + " | 4. Hall of Fame |\n" + " | 5. Credits |\n" + " | 6. Exit |\n" + " | Enter 1 - 6 for selection |\n" + " +==================================================================================+"); switch(IR4.getIntegerBetweenLowAndHigh("", 1, 6, "Invalid input, try again")) { case 1: //Play menu displayPlay(); quit = true; break; case 2: //Settings menu displaySetting(); quit = true; break; case 3: //Player statistics displayStats(); quit = true; break; case 4: displayHOF(); quit = true; break; case 5: displayCredits(); quit = true; break; case 6: //Quits the game displayThanks(); quit = true; break; } return quit; } //Play submenu static void displayPlay() throws IOException, InterruptedException { System.out.printf("%35s\n","Play"); System.out.println("1. Extreme Blackjack!\n" + "2. Back"); switch(IR4.getIntegerBetweenLowAndHigh("", 1, 2, "Invalid input, try again")) { case 1: mainGame(); break; case 2: displayMenu(); break; } } //Setting submenu that allows the user to modify their account static void displaySetting() throws IOException, InterruptedException { System.out.printf("%42s\n", "Settings" ); System.out.println("1. Change currency \n"+ "2. Change Alias \n" + "3. Back"); switch(IR4.getIntegerBetweenLowAndHigh("", 1, 3, "Invalid input, try again")) { case 1: changeCurrency(); break; case 2: changeAlias(); break; case 3: displayMenu(); break; default: System.err.println("Enter 1 - 3 and try again"); } } //The option to change their in game currency static void changeCurrency() throws IOException, InterruptedException { ProjectFileIO_v2.readFile(); System.out.printf("%31s\n", "Change currency"); System.out.println("Current currency: " + ProjectFileIO_v2.getPlayer(currentPlayer.getName(), passwd).getCurrency()); System.out.println("Enter new currency name or enter 'q' to go back"); String newCurrency = input.next(); if(newCurrency.equalsIgnoreCase("q")) displaySetting(); else System.out.println(); ProjectFileIO_v2.getPlayer(currentPlayer.getName(), passwd).setCurrency(newCurrency); System.out.println("Currency successfully changed"); ProjectFileIO_v2.writeFile(); displaySetting(); } //The option to change their log in username. //Duplicate usernames are not allowed to avoid log in conflicts static void changeAlias() throws IOException, InterruptedException { ProjectFileIO_v2.readFile(); String newAlias = ""; System.out.printf("%31s\n", "Change alias"); System.out.println("Enter new name"); newAlias = input.next(); for(Player x: ProjectFileIO_v2.getPlayerArrayList()) { while(newAlias.equals(x.getName())) { System.err.println("Alias already taken, choose another one"); System.out.println("Enter new name"); newAlias = input.next(); // if(newAlias.equalsIgnoreCase("q")) { // displaySetting(); // break; // } // else { } } ProjectFileIO_v2.getPlayer(currentPlayer.getName(), passwd).setName(newAlias); currentPlayer.setName(newAlias); System.out.println("Alias successfully changed"); ProjectFileIO_v2.writeFile(); displaySetting(); } static void displayStats() throws IOException, InterruptedException { System.out.printf("%20s", "Statistics\n"); System.out.println("Wins: " + ProjectFileIO_v2.getPlayer(currentPlayer.getName(), passwd).getWins() +"\n" + "Loses: " + ProjectFileIO_v2.getPlayer(currentPlayer.getName(), passwd).getLoses() + "\n" + "Blackjacks: " + ProjectFileIO_v2.getPlayer(currentPlayer.getName(), passwd).getbJCount() + "\n" + "Credits earned: " + ProjectFileIO_v2.getPlayer(currentPlayer.getName(), passwd).getCreditsEarned() + "\n" + "Credits lost: " + ProjectFileIO_v2.getPlayer(currentPlayer.getName(), passwd).getCreditsLost() + "\n" + "Highest credit : " + ProjectFileIO_v2.getPlayer(currentPlayer.getName(), passwd).getHighestCredits() + "\n" + "Bankruptcies: " + ProjectFileIO_v2.getPlayer(currentPlayer.getName(), passwd).getBankRuptcies() + "\n" + "Press q to go back"); if(pressQ().equals("q")) displayMenu(); } //High score lists static void displayHOF() throws IOException, InterruptedException { System.out.println("<=================== HALL OF FAME ===================>\n"); System.out.printf("%-20s%33s\n", "Hustler:", "Wins:"); System.out.printf("%-20s%27c%3s\n", "--------", ' ', "------"); int playerSize = ProjectFileIO_v2.getPlayerArrayList().size(); int[] scores = new int[playerSize]; String [] users = new String[playerSize]; int count = 0; for(Player player: ProjectFileIO_v2.getPlayerArrayList()) { scores[count] = player.getWins(); users[count] = player.getName(); count++; } sortHighScores(scores, users); for(int x=0;x<playerSize;x++) { System.out.printf("%-25s%27d\n",users[x] , scores[x]); } System.out.println("Press q to go back"); if(pressQ().equals("q")) displayMenu(); } public static void sortHighScores(int [] arr, String [] arra) { int n = arr.length; for (int i = 0; i < n-1; i++) for (int j = 0; j < n-i-1; j++) if (arr[j] < arr[j+1]) { int temp = arr[j]; String tempura = arra[j]; arr[j] = arr[j+1]; arr[j+1] = temp; arra[j] = arra[j+1]; arra[j+1] = tempura; } } static void displayCredits() throws InterruptedException, IOException { System.out.println("***********************************"); System.out.println("Blackjack Extreme " + "v" +ProjectFileIO_v2.getVersionNumber()); System.out.println("Authors:"); System.out.println("Luis Gascon"); System.out.println("Austin Connick"); System.out.println("***********************************"); Thread.sleep(3000); displayMenu(); } static void displayThanks() { //Displays a thank you message when user quits //Create an ASCII art System.out.println(" ______ _ _ \n" + "|__ __| | | | |\n" + " | | |__ __ _ _ __ | | __ _ _ ___ _ _ | |\n" + " | | '_ \\ / _` | '_ \\| |/ / | | | |/ _ \\| | | | | |\n" + " | | | | | (_| | | | | < | |_| | (_) | |_| | |_|\n" + " | |_| |_|\\__,_|_| |_|_|\\_\\ \\__, |\\___/ \\__,_| (_)\n" + " __/ | \n" + " |___/ "); } static String pressQ() { String q = input.next(); while(!q.equals("q")) { System.out.println("Enter q to quit"); q = input.next(); } return q; } /*****************Game logic*******************/ private static void mainGame() throws IOException { double score = 1500; int lost = 0; double bet = 0; boolean run = true; int move; int numberDraws = 2; int drawFactor = 8; int compHit = 16; int CARDGAMENUM = 21; boolean runTwo = true; while(runTwo) { Deck playingDeck = new Deck(); Deck PlayerHand = new Deck(); Deck CompHand = new Deck(); playingDeck.createDeck(); playingDeck.shuffle(); //Winning numbers CARDGAMENUM = IR4.getRandomNumber(21, 61); compHit = CARDGAMENUM - 6 ; System.out.printf(currentPlayer.getCurrency()+": " +score+"\n"); printWiningscore(CARDGAMENUM); /*If user runs out of money to bet */ if(score <= 0) { runTwo = false; run = false; bankRuptcies++; ProjectFileIO_v2.writeFile(); ProjectFileIO_v2.getPlayer(username, passwd).setBankRuptcies(bankRuptcies); } if(score > 0) { bet = placeBets(score); } numberDraws = CARDGAMENUM /drawFactor; for(int i = 1; i<= numberDraws; i++) { PlayerHand.draw(playingDeck); } for(int i = 2; i< numberDraws; i++) { CompHand.draw(playingDeck); } CompHand.draw(playingDeck); if(score <= 0) { runTwo = false; run = false; bankRuptcies++; ProjectFileIO_v2.writeFile(); ProjectFileIO_v2.getPlayer(username, passwd).setBankRuptcies(bankRuptcies); } run = true; while(run) { dividers(); System.out.printf("Win- "+ wins+" Lost- "+lost+"\n"); dividers(); printdealerHand(); dividers(); System.out.println(CompHand.toString()); dividers(); printHand(); System.out.printf(PlayerHand.toString()); dividers(); printSum(); dividers(); System.out.print("Computer: "+CompHand.cardValue()+" "+username + ": "+PlayerHand.cardValue()+"\t\tWinnig Number: "+ CARDGAMENUM +"\n"); dividers(); if(PlayerHand.cardValue() > CARDGAMENUM) { dividers(); bustprint(); dividers(); lost = lost + 1; score = score - bet; creditsLost = (int) (creditsLost + bet); run = false; } ////////////////////////////////21/insta win//////////////////////////////////////////////// if(PlayerHand.cardValue() == CARDGAMENUM) { System.out.println(CARDGAMENUM); dividers(); printdealerHand(); dividers(); System.out.println(CompHand.toString()); dividers(); printHand(); System.out.printf(PlayerHand.toString()); dividers(); printSum(); dividers(); System.out.print("Computer: "+CompHand.cardValue()+" "+username + ": "+PlayerHand.cardValue()+"\t\tWinnig Number: "+ CARDGAMENUM +"\n"); dividers(); WinningPrints(); run = false; } move = getMove(); ////////////////////Quit Add Save Stuff Here?///////////////////////////////////////////////////////// if(move == 3) { String user = currentPlayer.getName(); run = false; runTwo = false; ProjectFileIO_v2.writeFile(); ProjectFileIO_v2.getPlayer(user, passwd).setWins(wins); ProjectFileIO_v2.getPlayer(user, passwd).setBankRuptcies(bankRuptcies); ProjectFileIO_v2.getPlayer(user, passwd).setCreditsEarned(creditsEarned); ProjectFileIO_v2.getPlayer(user, passwd).setCreditsLost(creditsLost); } ////////////////////////////Hit///////////////////////////////////////////////////////////////// if(move == 1) { PlayerHand.draw(playingDeck); if(PlayerHand.cardValue() > CARDGAMENUM) { dividers(); printdealerHand(); dividers(); System.out.println(CompHand.toString()); dividers(); printHand(); System.out.printf(PlayerHand.toString()); dividers(); printSum(); dividers(); System.out.print("Computer: "+CompHand.cardValue()+" "+username + ": "+PlayerHand.cardValue()+"\t\tWinnig Number: "+ CARDGAMENUM +"\n"); dividers(); bustprint(); dividers(); lost = lost + 1; score = score - bet; creditsLost = (int) (creditsLost + bet); //System.out.println(score); run = false; } //////////////////////////////////////21//////////////////////////////////// if(PlayerHand.cardValue() == CARDGAMENUM) { System.out.println(CARDGAMENUM); dividers(); printdealerHand(); dividers(); System.out.println(CompHand.toString()); dividers(); printHand(); System.out.printf(PlayerHand.toString()); dividers(); printSum(); dividers(); System.out.print("Computer: "+CompHand.cardValue()+" "+username + ": "+PlayerHand.cardValue()+"\t\tWinnig Number: "+ CARDGAMENUM +"\n"); dividers(); WinningPrints(); score = score + bet; run = false; } ////////////////////////////////comp Win/////////////////////////////// if(CompHand.cardValue() > CARDGAMENUM) { dividers(); printdealerHand(); dividers(); System.out.println(CompHand.toString()); dividers(); printHand(); System.out.printf(PlayerHand.toString()); dividers(); printSum(); dividers(); System.out.print("Computer: "+CompHand.cardValue()+" "+username + ": "+PlayerHand.cardValue()+"\t\tWinnig Number: "+ CARDGAMENUM +"\n"); dividers(); dealerBust(); dividers(); WinningPrints(); dividers(); wins = wins + 1; score = score + bet; creditsEarned = (int) (creditsEarned + bet); //System.out.println(score); run = false; } } /////////////////////////////////////////////Stand////////////////////////////////////////////// if(move == 2) { run = false; /////////////////////////////////////////////AI/////////////////////////////////////// while(CompHand.cardValue() <= compHit) { CompHand.draw(playingDeck); } /////////////////////////////////////////Rest menu////////////////// dividers(); printdealerHand(); dividers(); System.out.println(CompHand.toString()); dividers(); printHand(); System.out.printf(PlayerHand.toString()); dividers(); printSum(); dividers(); System.out.print("Computer: "+CompHand.cardValue()+" "+username + ": "+PlayerHand.cardValue()+"\t\tWinnig Number: "+ CARDGAMENUM +"\n"); dividers(); WinningPrints(); dividers(); /////////////////////////////////////////////////Player wins////////////////////////////////////////////////////////////////////////////////// if(CompHand.cardValue() <= PlayerHand.cardValue()&& PlayerHand.cardValue() <= CARDGAMENUM) { dividers(); printdealerHand(); dividers(); System.out.println(CompHand.toString()); dividers(); printHand(); System.out.printf(PlayerHand.toString()); dividers(); printSum(); dividers(); System.out.print("Computer: "+CompHand.cardValue()+" "+username + ": "+PlayerHand.cardValue()+"\t\tWinnig Number: "+ CARDGAMENUM +"\n"); dividers(); WinningPrints(); dividers(); wins = wins + 1; score =score + bet; creditsEarned = (int) (creditsEarned + bet); System.out.println(score); } ////////////////////////////////////////////////////////AI wins//////////////////////////////////////////// if(CompHand.cardValue() >= PlayerHand.cardValue() && CompHand.cardValue() <= CARDGAMENUM) { dividers(); printdealerHand(); dividers(); System.out.println(CompHand.toString()); dividers(); printHand(); System.out.printf(PlayerHand.toString()); dividers(); printSum(); dividers(); System.out.print("Computer: "+CompHand.cardValue()+" "+username + ": "+PlayerHand.cardValue()+"\t\tWinnig Number: "+ CARDGAMENUM +"\n"); dividers(); printDealerwin(); dividers(); lost = lost + 1; score =score - bet; System.out.println(score); } ////////////////////////////AI Bust/////////////////////////////////// if(CompHand.cardValue() > CARDGAMENUM) { dividers(); printdealerHand(); dividers(); System.out.println(CompHand.toString()); dividers(); printHand(); System.out.printf(PlayerHand.toString()); dividers(); printSum(); dividers(); System.out.print("Computer: "+CompHand.cardValue()+" "+username + ": "+PlayerHand.cardValue()+"\t\tWinnig Number: "+ CARDGAMENUM +"\n"); dividers(); dealerBust(); dividers(); WinningPrints(); dividers(); wins = wins +1; score = score + bet; run = false; } } } } try { displayMenu(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static int getMove() { int move; boolean run = true; do{ System.out.printf("1. Hit\n"); System.out.printf("2. Stand\n"); move = IR4.getInteger("3. Quit"); if(move != 1 && move != 2 && move != 3) { System.out.printf("Invald input\n"); run = true; } }while(!run); return move; } private static double placeBets(double score) { double temp = IR4.getDouble("Places Bets"); boolean run = true; while(run) { if(temp <= score && temp > 0) { run = false; return temp; } else { System.out.printf("Invald input\n"); temp = IR4.getDouble("Places Bets"); run = true; } } return temp; } }
package com.prog.test.designpattern; public enum PreventSingletonByEnum { INSTANCE; public void doDisplay() { System.out.println("Test Singleton by Enum"); } }
package com.ifeiyang.bijia; import java.io.InputStream; import zback._Test; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.ifeiyang.bijia.adapter.ProductAdapter; import com.ifeiyang.bijia.entity.ClusterList; import com.ifeiyang.bijia.model.App; import com.ifeiyang.bijia.model.AttrModel; import com.ifeiyang.bijia.model.GsonModel; import com.ifeiyang.bijia.model.HttpModel; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.exception.HttpException; import com.lidroid.xutils.http.ResponseInfo; import com.lidroid.xutils.http.callback.RequestCallBack; import com.lidroid.xutils.util.LogUtils; import com.lidroid.xutils.view.annotation.ViewInject; import com.way.ui.swipelistview.BaseSwipeListViewListener; import com.way.ui.swipelistview.SwipeListView; public class CompareActivity extends Activity { private static final int MSG_LOADTESTPRODUCT_FINISHED = 0; @ViewInject(R.id.recent_listview) SwipeListView mSwipeListView; @ViewInject(R.id.bottom_panel) LinearLayout bottom_panel; // @OnClick(R.id.compareTable) // public void testButtonClick(View v) { // 方法签名必须和接口中的要求一致 // } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_compare_v2); ViewUtils.inject(this); attrModel = App.getInstance().getAttrModel(); initView(); initData(); LogUtils.d("onCreate"); // getWindowManager().addView(view, params); // getWindow().addContentView(view, params); } private void initData() { if (_Test.test()) { try { InputStream is = getAssets().open("testjson.txt"); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); String text = new String(buffer, "utf-8"); ClusterList clusterList = GsonModel.gson.fromJson(text, ClusterList.class); myHandler.onLoadSucces(clusterList); } catch (Exception e) { e.printStackTrace(); } } else { HttpModel httpModel = App.getInstance().getHttpModel(); httpModel.setRequestCallBack(callBack); httpModel.loadTestProduct(); } } ProductAdapter adapter = new ProductAdapter(); MyHandler myHandler = new MyHandler(); private void initView() { setTypeSelectorEnable(false); mSwipeListView.setAdapter(adapter); attrModel.initListView(mSwipeListView); mSwipeListView.setSwipeListViewListener(new BaseSwipeListViewListener()); } private void setTypeSelectorEnable(boolean isEnable) { // 3 } private void addLeftAttrsToView() { } private void addProductsToView() { // } RequestCallBack<String> callBack = new RequestCallBack<String>() { @Override public void onLoading(long total, long current, boolean isUploading) { LogUtils.d("onLoading"); } @Override public void onSuccess(ResponseInfo<String> responseInfo) { LogUtils.d("onSuccess responseInfo=" + responseInfo.result); ClusterList clusterList = GsonModel.gson.fromJson(responseInfo.result, ClusterList.class); myHandler.onLoadSucces(clusterList); } @Override public void onStart() { LogUtils.d("onStart"); } @Override public void onFailure(HttpException error, String msg) { LogUtils.d("onFailure"); LogUtils.d(msg); } }; private AttrModel attrModel; class MyHandler extends Handler { public void handleMessage(Message msg) { if (msg.what == MSG_LOADTESTPRODUCT_FINISHED) { // listView ClusterList clusterList = (ClusterList) msg.obj; adapter.initData(clusterList); adapter.notifyDataSetChanged(); attrModel.initBottom(getLayoutInflater(), bottom_panel); attrModel.invalidateBottom(); // addProductsToView(); // addLeftAttrsToView(); // setTypeSelectorEnable(true); } } public void onLoadSucces(ClusterList clusterList) { Message msg = obtainMessage(); msg.what = MSG_LOADTESTPRODUCT_FINISHED; msg.obj = clusterList; sendMessage(msg); } }; }
/* * Copyright 2015 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.clerezza.commons.rdf.impl.sparql; import com.hp.hpl.jena.query.DatasetAccessor; import com.hp.hpl.jena.query.DatasetAccessorFactory; import java.io.IOException; import java.net.ServerSocket; import org.apache.jena.fuseki.EmbeddedFusekiServer; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import java.io.InputStream; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.apache.clerezza.commons.rdf.Graph; import org.apache.clerezza.commons.rdf.IRI; import org.apache.clerezza.commons.rdf.Language; import org.apache.clerezza.commons.rdf.Literal; import org.apache.clerezza.commons.rdf.RDFTerm; import org.apache.clerezza.commons.rdf.Triple; import org.apache.clerezza.commons.rdf.impl.utils.PlainLiteralImpl; import org.apache.clerezza.rdf.core.serializedform.Serializer; import org.apache.clerezza.rdf.core.serializedform.SupportedFormat; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; /** * * @author reto */ public class Dadmin2Test { final static int serverPort = findFreePort(); static EmbeddedFusekiServer server; @BeforeClass public static void prepare() throws IOException { final String serviceURI = "http://localhost:" + serverPort + "/ds/data"; final DatasetAccessor accessor = DatasetAccessorFactory.createHTTP(serviceURI); final InputStream in = Dadmin2Test.class.getResourceAsStream("dadmin2.ttl"); final Model m = ModelFactory.createDefaultModel(); String base = "http://example.org/"; m.read(in, base, "TURTLE"); server = EmbeddedFusekiServer.memTDB(serverPort, "/ds");//dataSet.getAbsolutePath()); server.start(); System.out.println("Started fuseki on port " + serverPort); accessor.putModel(m); } @AfterClass public static void cleanup() { server.stop(); } @Test public void graphSize() { final Graph graph = new SparqlGraph("http://localhost:" + serverPort + "/ds/query"); Assert.assertEquals("Graph not of the exepected size", 12, graph.size()); } @Test public void dump() { final Graph graph = new SparqlGraph("http://localhost:" + serverPort + "/ds/query"); Serializer serializer = Serializer.getInstance(); serializer.serialize(System.out, graph, SupportedFormat.TURTLE); } public static int findFreePort() { int port = 0; try (ServerSocket server = new ServerSocket(0);) { port = server.getLocalPort(); } catch (Exception e) { throw new RuntimeException("unable to find a free port"); } return port; } }
package ch.noseryoung.uk.domainModels.auction.dto; public class AuctionDTO { //Fields private int id; private String name; private String reason; private Float price; // Standard empty constructor public AuctionDTO() { } // Getters and setters public int getId() { return id; } public AuctionDTO setId(int id) { this.id = id; return this; } public String getName() { return name; } public AuctionDTO setName(String name) { this.name = name; return this; } public Float getPrice() { return price; } public void setPrice(Float price) { this.price = price; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } }
package Models; public class StudentsList { private int userID,classID,roleID; private String username,studentName,gender; public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public int getUserID() { return userID; } public void setUserID(int userID) { this.userID = userID; } public int getClassID() { return classID; } public void setClassID(int classID) { this.classID = classID; } public int getRoleID() { return roleID; } public void setRoleID(int roleID) { this.roleID = roleID; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } }
package com.jim.multipos.ui.mainpospage.di; import android.content.Context; import android.support.v7.app.AppCompatActivity; import com.jim.multipos.R; import com.jim.multipos.config.scope.PerActivity; import com.jim.multipos.config.scope.PerFragment; import com.jim.multipos.core.BaseActivityModule; import com.jim.multipos.ui.lock_screen.auth.AuthFragment; import com.jim.multipos.ui.lock_screen.auth.AuthFragmentModule; import com.jim.multipos.ui.mainpospage.MainPosPageActivity; import com.jim.multipos.ui.mainpospage.MainPosPageActivityImpl; import com.jim.multipos.ui.mainpospage.MainPosPageActivityPresenter; import com.jim.multipos.ui.mainpospage.MainPosPageActivityView; import com.jim.multipos.ui.mainpospage.connection.MainPageConnection; import com.jim.multipos.ui.mainpospage.view.BarcodeScannerFragment; import com.jim.multipos.ui.mainpospage.view.BarcodeScannerFragmentModule; import com.jim.multipos.ui.mainpospage.view.CustomerNotificationsFragment; import com.jim.multipos.ui.mainpospage.view.CustomerNotificationsFragmentModule; import com.jim.multipos.ui.mainpospage.view.OrderListFragment; import com.jim.multipos.ui.mainpospage.view.OrderListFragmentModule; import com.jim.multipos.ui.mainpospage.view.OrderListHistoryFragment; import com.jim.multipos.ui.mainpospage.view.OrderListHistoryFragmentModule; import com.jim.multipos.ui.mainpospage.view.PaymentFragment; import com.jim.multipos.ui.mainpospage.view.PaymentFragmentModule; import com.jim.multipos.ui.mainpospage.view.ProductFolderFragmentModule; import com.jim.multipos.ui.mainpospage.view.ProductFolderViewFragment; import com.jim.multipos.ui.mainpospage.view.ProductInfoFragment; import com.jim.multipos.ui.mainpospage.view.ProductInfoFragmentModule; import com.jim.multipos.ui.mainpospage.view.ProductPickerFragment; import com.jim.multipos.ui.mainpospage.view.ProductPickerFragmentModule; import com.jim.multipos.ui.mainpospage.view.ProductSquareFragmentModule; import com.jim.multipos.ui.mainpospage.view.ProductSquareViewFragment; import com.jim.multipos.ui.mainpospage.view.SearchModeFragment; import com.jim.multipos.ui.mainpospage.view.SearchModeFragmentModule; import com.jim.multipos.utils.managers.NotifyManager; import javax.inject.Named; import dagger.Binds; import dagger.Module; import dagger.Provides; import dagger.android.ContributesAndroidInjector; /** * Created by bakhrom on 10/6/17. */ @Module(includes = BaseActivityModule.class) public abstract class MainPageMenuModule { @Binds @PerActivity abstract AppCompatActivity provideMainPosPageActivity(MainPosPageActivity mainPosPageActivity); @Binds @PerActivity abstract MainPosPageActivityPresenter provideMainPosPageActivityPresenter(MainPosPageActivityImpl mainPosPageActivityPresenter); @Binds @PerActivity abstract MainPosPageActivityView provideMainPosPageActivityView(MainPosPageActivity mainPosPageActivity); @PerFragment @ContributesAndroidInjector(modules = ProductPickerFragmentModule.class) abstract ProductPickerFragment provideProductPickerFragmentInjector(); @PerFragment @ContributesAndroidInjector(modules = ProductSquareFragmentModule.class) abstract ProductSquareViewFragment provideProductSquareViewFragmentInjector(); @PerFragment @ContributesAndroidInjector(modules = PaymentFragmentModule.class) abstract PaymentFragment providePaymentFragmentInjector(); @PerFragment @ContributesAndroidInjector(modules = ProductFolderFragmentModule.class) abstract ProductFolderViewFragment provideProductFolderViewFragmentInjector(); @PerFragment @ContributesAndroidInjector(modules = SearchModeFragmentModule.class) abstract SearchModeFragment provideSearchModeFragment(); @PerFragment @ContributesAndroidInjector(modules = ProductInfoFragmentModule.class) abstract ProductInfoFragment provideProductInfoFragment(); @PerFragment @ContributesAndroidInjector(modules = OrderListFragmentModule.class) abstract OrderListFragment provideOrderListFragment(); @PerFragment @ContributesAndroidInjector(modules = CustomerNotificationsFragmentModule.class) abstract CustomerNotificationsFragment provideCustomerNotificationsFragment(); @PerFragment @ContributesAndroidInjector(modules = OrderListHistoryFragmentModule.class) abstract OrderListHistoryFragment provideOrderListHistoryFragment(); @PerActivity @Provides @Named(value = "discount_amount_types") static String[] provideDiscountAmountTypes(Context context) { return context.getResources().getStringArray(R.array.discount_amount_types_abr); } @PerFragment @ContributesAndroidInjector(modules = AuthFragmentModule.class) abstract AuthFragment provideAuthFragment(); @PerActivity @Provides @Named(value = "discount_used_types_abr") static String[] provideDiscountUsedTypesAbr(Context context) { return context.getResources().getStringArray(R.array.discount_used_types_abr); } @PerActivity @Provides @Named(value = "discount_used_types") static String[] provideUsedType(Context context){ return context.getResources().getStringArray(R.array.discount_used_types); } @PerActivity @Provides static MainPageConnection provideMainPageConnection(Context context){ return new MainPageConnection(context); } @PerFragment @ContributesAndroidInjector(modules = BarcodeScannerFragmentModule.class) abstract BarcodeScannerFragment provideBarcodeScannerFragmentInjector(); @PerActivity @Provides static NotifyManager getNotifyManager() { return new NotifyManager(); } }
import java.util.Optional; public class Optionals { public static void main(String[] args) { World world = generateWorld(); // Displaying building tenant name: // 1) 'Old school' boolean found = false; if (world != null) { Country country = world.getCountry("Australia"); if (country != null) { City city = country.getCity("Sydney"); if (city != null) { Street street = city.getStreet("Wallaby Way"); if (street != null) { Building building = street.getBuilding("42"); if (building != null) { String tenantName = building.getTenantName(); if (tenantName != null) { System.out.println(tenantName); found = true; } } } } } } if (!found) { System.out.println("No data"); } // 2) Using Optional<> System.out.println(world.getCountry_Optional("Australia") .flatMap(country -> country.getCity_Optional("Sydney")) .flatMap(city -> city.getStreet_Optional("Wallaby Way")) .flatMap(street -> street.getBuilding_Optional("42")) .map(building -> building.getTenantName()) .orElse("No data") ); } // Helper function to generate a World private static World generateWorld() { World world = new World() .addCountry("Australia", new Country() .addCity("Sydney", new City() .addStreet("Wallaby Way", new Street() .addBuilding("42", new Building("Nemo")) ) ) ); return world; } }
package com.hesoyam.pharmacy.pharmacy.exceptions; public class PharmacyNotFoundException extends Exception { public PharmacyNotFoundException(Long id){ super(String.format("Pharmacy with ID '%s' not found", id)); } }
package com.parrello.tvseries.notification.ws; import javax.jws.WebService; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.ArrayList; import java.util.Date; import java.util.Properties; /** * Created by nicola on 27/11/14. */ @WebService(endpointInterface = "com.parrello.tvseries.notification.ws.NotificationSenderService") public class NotificationSenderServiceImplementation implements NotificationSenderService { final String username = "USERNAME"; final String password = "PASSWORD"; final String myEmailAddress = "EMAIL"; final String subject = "[Tv Series Tool] New episodes available"; Properties props; public NotificationSenderServiceImplementation() { props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); } @Override public void sendNotification(ArrayList<String> downloadedEpisodeNamesList) { Session session = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(myEmailAddress)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(myEmailAddress)); message.setSubject(subject); String emailBody = null; if (downloadedEpisodeNamesList != null && downloadedEpisodeNamesList.size() > 0) { emailBody = "The following episodes are being downloaded:"; for(String episode : downloadedEpisodeNamesList) { emailBody += "\n - " + episode; } } else { emailBody = "No new episode was downloaded during the last run."; } message.setText(emailBody); Transport.send(message); System.out.println("[" + new Date(System.currentTimeMillis()) + "]: Email successfully sent."); } catch (MessagingException e) { //e.printStackTrace(); System.out.println("[" + new Date(System.currentTimeMillis()) + "]: Email NOT sent; check and retry."); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ package org.apache.clerezza.utils; /** * A utility class for IRI and String manipulations. * * @author tio */ public class IRIUtil { /** * Strips #x00 - #x1F and #x7F-#x9F from a Unicode string * * @param inputChars * @return the stripped string * @see <a href="http://www.w3.org/TR/rdf-concepts/#dfn-URI-reference"> * http://www.w3.org/TR/rdf-concepts/#dfn-URI-reference</a> and * replaces all US-ASCII space character with a "+". */ public static String stripNonIRIChars(CharSequence inputChars) { if (inputChars == null) { return ""; } StringBuffer buffer = new StringBuffer(); for (int i = 0; i < inputChars.length(); i++) { char c = inputChars.charAt(i); if (!isIllegal(c)) { buffer.append(c); } } return buffer.toString().replaceAll("\\s+", "+"); } private static boolean isIllegal(char ch) { if ((ch >= 0x7F) && (ch <= 0x9F)) { return true; } return false; } }
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class ConnectionTest { public static void main(String[] args) throws SQLException, ClassNotFoundException { // TODO Auto-generated method stub Connection con=null; Class.forName("org.postgresql.Driver"); con=DriverManager.getConnection("jdbc:postgresql://localhost:5432/ecabinet","postgres", "root"); System.out.println(con); } }
package compare; import java.util.*; /** * @Author weimin * @Date 2020/10/7 0007 20:36 */ public class Lion implements Comparable{ private String name; private Integer age; public Lion(String name, Integer age) { this.name = name; this.age = age; } @Override public String toString() { return "Lion{" + "name='" + name + '\'' + ", age=" + age + '}'; } @Override public int compareTo(Object o) { Lion lion = (Lion) o; if(this.age>lion.age){ return 1; }else if(this.age.equals(lion.age)){ return 0; }else { return -1; } } public static void main(String[] args) { Lion lion1 = new Lion("辛巴",5); Lion lion2 = new Lion("木法沙",8); Lion lion3 = new Lion("娜拉",4); Lion[] lions = {lion1, lion2, lion3}; Arrays.sort(lions); System.out.println(Arrays.toString(lions)); Arrays.sort(lions, (o1, o2) -> o2.age - o1.age); System.out.println(Arrays.toString(lions)); List<Lion> list = new ArrayList<>(); list.add(lion1); list.add(lion2); list.add(lion3); Collections.sort(list); System.out.println(list); } }