text
stringlengths
10
2.72M
package com.test; import java.util.HashMap; import java.util.HashSet; import com.test.base.Solution; /** * 方案2:【方案1,已经说明,直接遍历方式不可行】 * * 1,先把他添加到两个HashMap里面,【相当于建立映射关系】 * 2,随机取一个数字,按照递归的方式,找到所有相连的数据 * 3,判断HashMap中是否还有值,还有的话继续,直到HashMap值全部清空 * * @author YLine * * 2019年6月3日 下午2:15:55 */ public class SolutionB implements Solution { @Override public int removeStones(int[][] stones) { HashMap<Integer, HashSet<Integer>> xMap = new HashMap<>(); // x的映射,映射到stone下标 HashMap<Integer, HashSet<Integer>> yMap = new HashMap<>(); // y的映射,映射到stone下标 // 建立映射关系 for (int i = 0; i < stones.length; i++) { int x = stones[i][0]; int y = stones[i][1]; // x对应的所有下标值 HashSet<Integer> xSet = xMap.get(x); if (null == xSet) { xSet = new HashSet<>(); xSet.add(i); xMap.put(x, xSet); } else { xSet.add(i); } // y对应的所有x值 HashSet<Integer> ySet = yMap.get(y); if (null == ySet) { ySet = new HashSet<>(); ySet.add(i); yMap.put(y, ySet); } else { ySet.add(i); } } // 开始递归删除内容 Info info = new Info(stones); for (int x : xMap.keySet()) { HashSet<Integer> xSet = xMap.get(x); for (int position : xSet) { if (!info.isDelete(position)) { info.addCircleCount(); dfs(xMap, yMap, info, position); } } } return info.getResult(); } /** * 随机取一个值,然后开始,将相连的值递归 * @param xMap x值维护的所有值 * @param yMap y值维护的所有值 * @return 相连的总数 */ private void dfs(HashMap<Integer, HashSet<Integer>> xMap, HashMap<Integer, HashSet<Integer>> yMap, Info info, int position) { // 避免太多次进入 if (info.isDelete(position)) { return; } info.delete(position); // 所有的x int x = info.getX(position); HashSet<Integer> xSet = xMap.get(x); for (int xPosition : xSet) { if (!info.isDelete(xPosition)) { dfs(xMap, yMap, info, xPosition); } } // 所有的y int y = info.getY(position); HashSet<Integer> ySet = yMap.get(y); for (int yPosition : ySet) { if (!info.isDelete(yPosition)) { dfs(xMap, yMap, info, yPosition); } } } public static class Info { private final int[][] stones; private boolean[] isDelete; // 是否已经被删除 private int circleCount; // 循环的个数 public Info(int[][] stones) { this.stones = stones; this.circleCount = 0; this.isDelete = new boolean[stones.length]; } public void addCircleCount() { circleCount++; } public void delete(int position) { isDelete[position] = true; } public boolean isDelete(int position) { return isDelete[position]; } public int getResult() { return stones.length - circleCount; } public int getX(int position) { return stones[position][0]; } public int getY(int position) { return stones[position][1]; } } }
import java.util.Scanner; /** * Created by EddyJ on 6/16/16. */ public class Main { public static void main(String[] args) { Inventory inventory = new Inventory(); Item item = new Item(); Scanner scanner = new Scanner(System.in); int id = 0; int option = 0; do { switch (inventory.showMenu()) { case 1: System.out.println("Please enter the name for your Item"); item.setName(scanner.nextLine()); System.out.println("How much will this item be?"); item.setPrice(scanner.nextDouble()); System.out.println("What is the quantity of this item?"); item.setQuantity(scanner.nextInt()); id++; item.setId(id); inventory.addItem(item); break; case 2: inventory.showItems(); inventory.sellItem(); break; case 3: inventory.showItems(); System.out.println("Please enter the item's ID you would like to remove."); inventory.removeItem(); break; case 4: inventory.showItems(); System.out.println("Choose which item you would like to update the quantity of."); inventory.updateQuantity(); break; case 5: inventory.showItems(); System.out.println("Which item would you like to udpate the price to?"); inventory.updatePrice(); break; case 6: option = 6; System.out.println("Goodbye"); break; default: System.out.println("Command not found"); } }while(option != 6); System.out.println("System end."); } }
package io.indreams.ecommerceuserinfoservice.configuration.security.service; import io.indreams.ecommerceuserinfoservice.configuration.security.dao.UserRepository; import io.indreams.ecommerceuserinfoservice.model.User; import io.indreams.ecommerceuserinfoservice.utility.Constants; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.util.Optional; @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException { Optional<User> user = userRepository.findByUsername(userName); if (user.isPresent()) return new UserDetailsImpl(user.get()); throw new UsernameNotFoundException(Constants.NO_USER_FOUND); } }
package com.kodilla.patterns2.decorator.pizza; import java.math.BigDecimal; import java.util.List; public class BasicPizzaOrder implements PizzaOrder{ @Override public BigDecimal getCost() { return new BigDecimal(15.0); } @Override public String getName() { return "Plain Pizza"; } }
package fr.cea.nabla.interpreter.nodes.expression; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.ExplodeLoop; import fr.cea.nabla.interpreter.NablaTypesGen; import fr.cea.nabla.interpreter.values.NV1Bool; public abstract class NablaBool1Node extends NablaExpressionNode { @Children private final NablaExpressionNode[] values; public NablaBool1Node(NablaExpressionNode[] values) { this.values = values; } @Override @ExplodeLoop @Specialization public NV1Bool executeNV1Bool(VirtualFrame frame) { final boolean[] computedValues = new boolean[values.length]; for (int i = 0; i < values.length; i++) { computedValues[i] = NablaTypesGen.asNV0Bool(values[i].executeGeneric(frame)).isData(); } return new NV1Bool(computedValues); } }
package com.pdd.pop.sdk.http.api.response; import com.pdd.pop.ext.fasterxml.jackson.annotation.JsonProperty; import com.pdd.pop.sdk.http.PopBaseHttpResponse; import java.util.List; public class PddAdHistoryRtPlanReportGetResponse extends PopBaseHttpResponse{ /** * 返回response */ @JsonProperty("ad_plan_real_time_report_response") private AdPlanRealTimeReportResponse adPlanRealTimeReportResponse; public AdPlanRealTimeReportResponse getAdPlanRealTimeReportResponse() { return adPlanRealTimeReportResponse; } public static class AdPlanRealTimeReportResponse { /** * 报表对象列表 */ @JsonProperty("plan_real_time_report_list") private List<PlanRealTimeReportListItem> planRealTimeReportList; public List<PlanRealTimeReportListItem> getPlanRealTimeReportList() { return planRealTimeReportList; } } public static class PlanRealTimeReportListItem { /** * 计划id */ @JsonProperty("plan_id") private Long planId; /** * 计划名 */ @JsonProperty("plan_name") private String planName; /** * 计划日限额,单位厘 */ @JsonProperty("max_cost") private Long maxCost; /** * 1:已启用,2:未启用 */ @JsonProperty("operate_status") private Integer operateStatus; /** * 1:余额充足,2:余额不足,3:超出消耗上限 */ @JsonProperty("account_status") private Integer accountStatus; /** * 1:推广中,2:手动暂停,3:余额不足,4:到达日限额,5:无推广单元,6:已删除 */ @JsonProperty("status") private Integer status; /** * 1:已删除,0:未删除 */ @JsonProperty("is_deleted") private Integer isDeleted; /** * 推广单元数量 */ @JsonProperty("ad_unit_num") private Long adUnitNum; /** * 广告投资回报率 */ @JsonProperty("roi") private Double roi; /** * 广告曝光数 */ @JsonProperty("impression") private Long impression; /** * 广告点击数 */ @JsonProperty("click") private Long click; /** * 广告点击率 */ @JsonProperty("ctr") private Double ctr; /** * 广告消耗,单位厘 */ @JsonProperty("spend") private Long spend; /** * 点击单价,单位厘 */ @JsonProperty("cpc") private Double cpc; /** * 广告转化支付订单数 */ @JsonProperty("order_num") private Long orderNum; /** * 广告转化支付金额,单位厘 */ @JsonProperty("gmv") private Long gmv; /** * 日期 */ @JsonProperty("date") private String date; public Long getPlanId() { return planId; } public String getPlanName() { return planName; } public Long getMaxCost() { return maxCost; } public Integer getOperateStatus() { return operateStatus; } public Integer getAccountStatus() { return accountStatus; } public Integer getStatus() { return status; } public Integer getIsDeleted() { return isDeleted; } public Long getAdUnitNum() { return adUnitNum; } public Double getRoi() { return roi; } public Long getImpression() { return impression; } public Long getClick() { return click; } public Double getCtr() { return ctr; } public Long getSpend() { return spend; } public Double getCpc() { return cpc; } public Long getOrderNum() { return orderNum; } public Long getGmv() { return gmv; } public String getDate() { return date; } } }
package com.example.lavishbansal.demose2; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.webkit.WebView; import android.webkit.WebViewClient; public class particularNewspaper extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_particular_newspaper);Intent intent= getIntent(); WebView webView= (WebView)findViewById(R.id.webView); webView.getSettings().setJavaScriptEnabled(true); webView.setWebViewClient(new WebViewClient()); webView.loadUrl( intent.getStringExtra("http")); } }
/** * @author Nollan * Date: 2016-09-14 * Description: * This class handles all logic and GUI functionality. With this program you can practice your mathskills * and become better at calculating in your head. * The program was made to practice my skills in programming and the idea of the program in from my sister who * is a teacher. */ package tenbuddies; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridLayout; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.concurrent.TimeUnit; import javax.imageio.ImageIO; import javax.swing.AbstractButton; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.SwingConstants; import javax.swing.border.EmptyBorder; import com.sun.glass.events.KeyEvent; import java.util.Collections; @SuppressWarnings("serial") public class Window extends JFrame { private JLabel[] buttons = new JLabel[11]; private JLabel btnZero,btnOne, btnTwo, btnThree, btnFour, btnFive, btnSix, btnSeven, btnEight, btnNine, btnTen, correctImg, incorrectImg; private JMenuBar menuBar; private JMenu menu, subMenuSettings, subMenuAnimation, subMenuMaxNumbers, subMenuArithmeticChoise, subMenuCompetition; private JCheckBox boxItemAnimationOnOff, boxItemAllowNegativeNumbers, boxItemButtonAutoRestart; private JMenuItem buttonCompetition; private JRadioButton radioButtonMaxNumber10, radioButtonMaxNumber20, radioButtonMaxNumber30, radioButtonMaxNumber40, radioButtonMaxNumber50, radioButtonMinNum10MaxNumber50, radioButtonMinNum10MaxNumber40, radioButtonMinNum10MaxNumber30,radioButtonMinNum10MaxNumber20, radioButtonMinNum20MaxNumber50, radioButtonMinNum20MaxNumber40, radioButtonMinNum20MaxNumber30, radioButtonMinNum30MaxNumber50, radioButtonMinNum30MaxNumber40, radioButtonMinNum40MaxNumber50, radioButtonAddition, radioButtonSubtraction, radioButtonDivision, radioButtonMultiplication; private ButtonGroup numberGroup, arithmeticChoiseGroup; private JTextField textFieldExpression, textFieldTime, textFieldScoreCount, textFieldCompetition, countDownText, congratzText, congratzTextTop, congratzText2nd, congratzText3rd; private ArrayList<Integer> listButtonOrder; private JPanel row0, row1, row2, row3, row4, expressionScreen, competitionCountDown, congratzScreen; private JMenuItem newExpression; private int correctAnswer = -1, competitionExpressionCount = 0, comptetitionCorrectCount = 0; private long startTime, totalTime = 0, totalTimeTmp = 0; private boolean timeCountStarted, allowNumberButtonClick = true, competitionActive = false; /** * @author Nollan * Construct for class Window */ public Window() { super("Tiokompisar"); createMenu(); setSize(600,600); setDefaultCloseOperation(EXIT_ON_CLOSE); setResizable(false); expressionScreen = new JPanel(new GridLayout(5, 1)); //Adds expressionscreen and its properties expressionScreen.setSize(600,600); expressionScreen.setBackground(Color.CYAN); competitionCountDown = new JPanel(new FlowLayout()); //Adds competitionscreen and its properties competitionCountDown.setBackground(Color.BLACK); competitionCountDown.setSize(600,600); competitionCountDown.setVisible(false); //Hides competition panel this.add(competitionCountDown); congratzScreen = new JPanel(new FlowLayout()); //Adds congratzscreen and its properties congratzScreen.setBackground(Color.YELLOW); congratzScreen.setSize(600,600); congratzScreen.setVisible(false); this.add(congratzScreen); congratzTextTop = new JTextField("Grattis"); //Adds textfield for congratztexttop and its properties congratzTextTop.setEnabled(false); congratzTextTop.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 100)); congratzTextTop.setDisabledTextColor(Color.BLACK); congratzTextTop.setBackground(Color.YELLOW); congratzTextTop.setBorder(null); congratzScreen.add(congratzTextTop); congratzText = new JTextField(); //Adds textfield for congratztext and its properties congratzText.setEnabled(false); congratzText.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 20)); congratzText.setDisabledTextColor(Color.BLACK); congratzText.setBackground(Color.YELLOW); congratzText.setBorder(null); congratzScreen.add(congratzText); congratzText2nd = new JTextField(); //Adds textfield for congratztext2nd and its properties congratzText2nd.setEnabled(false); congratzText2nd.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 20)); congratzText2nd.setDisabledTextColor(Color.BLACK); congratzText2nd.setBackground(Color.YELLOW); congratzText2nd.setBorder(null); congratzScreen.add(congratzText2nd); congratzText3rd = new JTextField("Klicka för att komma tillbaka så du kan prova igen."); //Adds textfield for congratztext3rd and its properties congratzText3rd.setEnabled(false); congratzText3rd.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 20)); congratzText3rd.setDisabledTextColor(Color.BLACK); congratzText3rd.setBackground(Color.YELLOW); congratzText3rd.setBorder(null); congratzScreen.add(congratzText3rd); countDownText = new JTextField("3"); //Adds textfield for countdown and its properties countDownText.setEnabled(false); countDownText.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 400)); countDownText.setDisabledTextColor(Color.WHITE); countDownText.setBackground(Color.BLACK); countDownText.setBorder(null); competitionCountDown.add(countDownText); //Adds text to jpanel this.add(expressionScreen); row0 = new JPanel(); //Skapar översta raden row0.setLayout(new FlowLayout(FlowLayout.CENTER)); //Layout på raden row0.setBackground(Color.CYAN); //Bakgrundsfärg expressionScreen.add(row0); //Lägger till första raden till frame textFieldScoreCount = new JTextField(""); textFieldScoreCount.setPreferredSize(new Dimension(110,50)); textFieldScoreCount.setEnabled(false); textFieldScoreCount.setOpaque(false); textFieldScoreCount.setBorder(null); textFieldScoreCount.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 30)); textFieldScoreCount.setDisabledTextColor(Color.black); row0.add(textFieldScoreCount); row0.add(Box.createRigidArea(new Dimension(24,0))); textFieldExpression = new JTextField(""); //Skapar textrutan som uttrycket ska visas i textFieldExpression.setPreferredSize(new Dimension(300,50)); //Sätter storlek och andra formateringar textFieldExpression.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 34)); textFieldExpression.setDisabledTextColor(Color.black); textFieldExpression.setHorizontalAlignment(SwingConstants.CENTER); textFieldExpression.setEnabled(false); textFieldExpression.setBorder(BorderFactory.createCompoundBorder(textFieldExpression.getBorder(),BorderFactory.createEmptyBorder(5,5,5,5))); row0.add(textFieldExpression); //Lägger till textrutan row0.add(Box.createRigidArea(new Dimension(34,0))); textFieldTime = new JTextField(""); textFieldTime.setPreferredSize(new Dimension(100,50)); textFieldTime.setEnabled(false); textFieldTime.setOpaque(false); textFieldTime.setBorder(null); textFieldTime.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 30)); textFieldTime.setDisabledTextColor(Color.black); row0.add(textFieldTime); try { correctImg = new JLabel(); incorrectImg = new JLabel(); correctImg.setVisible(false); incorrectImg.setVisible(false); row0.add(correctImg); row0.add(incorrectImg); correctImg.setIcon(new ImageIcon(ImageIO.read(ClassLoader.getSystemResourceAsStream("correct.png")))); incorrectImg.setIcon(new ImageIcon(ImageIO.read(ClassLoader.getSystemResourceAsStream("incorrect.png")))); } catch (IOException e) { e.printStackTrace(); } row1 = new JPanel(); row1.setLayout(new FlowLayout(FlowLayout.CENTER,1,1)); row1.setBackground(Color.CYAN); expressionScreen.add(row1); row2 = new JPanel(); row2.setLayout(new FlowLayout(FlowLayout.CENTER,1,1)); row2.setBackground(Color.CYAN); expressionScreen.add(row2); row3 = new JPanel(); row3.setLayout(new FlowLayout(FlowLayout.CENTER,1,1)); row3.setBackground(Color.CYAN); expressionScreen.add(row3); row4 = new JPanel(); row4.setLayout(new FlowLayout(FlowLayout.CENTER,1,1)); row4.setBackground(Color.CYAN); expressionScreen.add(row4); initButtons(); this.setJMenuBar(menuBar); this.setVisible(true); randomizeButtonValues(); setButtonImages(); } /** * @author Nollan * Function initiate buttons and adds them to the panel */ public void initButtons(){ btnZero = new JLabel(); //Initializes "buttons" btnOne = new JLabel(); btnTwo = new JLabel(); btnThree = new JLabel(); btnFour = new JLabel(); btnFive = new JLabel(); btnSix = new JLabel(); btnSeven = new JLabel(); btnEight = new JLabel(); btnNine = new JLabel(); btnTen = new JLabel(); buttons[0] = btnZero; //Adds "buttons" to array buttons[1] = btnOne; buttons[2] = btnTwo; buttons[3] = btnThree; buttons[4] = btnFour; buttons[5] = btnFive; buttons[6] = btnSix; buttons[7] = btnSeven; buttons[8] = btnEight; buttons[9] = btnNine; buttons[10] = btnTen; int count = 0; for (JLabel jLabel : buttons) { //Loops array with "buttons" jLabel.setBorder(new EmptyBorder(5, 5, 5, 5)); //Sets border addButtonListener(jLabel); //Adds buttonListener (calls function) if (count >= 0 && count < 3){ //Add "button" to correct row row1.add(jLabel); } else if (count >= 3 && count < 6){ row2.add(jLabel); } else if (count >= 6 && count < 9){ row3.add(jLabel); } else { row4.add(jLabel); } count++; } } public void disableButtonClicks(){ allowNumberButtonClick = false; } public void enableButtonClicks(){ allowNumberButtonClick = true; } /** * @author Nollan * @param jLabel: Is a button that will be clickable * Function makes a jLabel clickable */ public void addButtonListener(JLabel jLabel){ jLabel.addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseClicked(MouseEvent e) { if (allowNumberButtonClick){ gradingChoise(jLabel.getName()); } } }); } /** * @author Nollan * @param clickValue: Contains the name of the jLabel clicked * Function will check if clicked value is the correct answer */ public void gradingChoise(String clickValue){ if (competitionActive){ competitionExpressionCount++; } if (correctAnswer != -1){ if (clickValue == buttons[listButtonOrder.get(correctAnswer)].getName()){ stopTimeCount(); setCorrectAnswerImage(); if (competitionActive){ comptetitionCorrectCount++; textFieldScoreCount.setText(Integer.toString(comptetitionCorrectCount)+ "/" + textFieldCompetition.getText()); } if (boxItemButtonAutoRestart.isSelected()){ createExpression(); } } else if(clickValue != buttons[listButtonOrder.get(correctAnswer)].getName()){ if (competitionActive){ textFieldScoreCount.setText(Integer.toString(comptetitionCorrectCount)+ "/" + textFieldCompetition.getText()); stopTimeCount(); createExpression(); } setIncorrectAnswerImage(); } } } /** * @author Nollan * Function switches visible image from incorrect to correct */ public void setCorrectAnswerImage(){ incorrectImg.setVisible(false); Double timeElapsed = Double.parseDouble(textFieldTime.getText().toString()); System.out.println(timeElapsed); try { if (timeElapsed < 2){ correctImg.setIcon(new ImageIcon(ImageIO.read(ClassLoader.getSystemResourceAsStream("5star.png")))); } else if (timeElapsed < 4){ correctImg.setIcon(new ImageIcon(ImageIO.read(ClassLoader.getSystemResourceAsStream("4star.png")))); } else if (timeElapsed < 6){ correctImg.setIcon(new ImageIcon(ImageIO.read(ClassLoader.getSystemResourceAsStream("3star.png")))); } else if (timeElapsed < 8){ correctImg.setIcon(new ImageIcon(ImageIO.read(ClassLoader.getSystemResourceAsStream("2star.png")))); } else { correctImg.setIcon(new ImageIcon(ImageIO.read(ClassLoader.getSystemResourceAsStream("1star.png")))); } correctImg.setVisible(true); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * @author Nollan * Function switches visible image from correct to incorrect */ public void setIncorrectAnswerImage(){ correctImg.setVisible(false); incorrectImg.setVisible(true); } /** * @author Nollan * Function creates and sets a menubar with settings */ public void createMenu(){ menuBar = new JMenuBar(); //Declares a menubar menu = new JMenu("Meny"); //Declares rootmenu menuBar.add(menu); //Adds rootmenu to menubar newExpression = new JMenuItem("Nytt uttryck"); newExpression.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, KeyEvent.MODIFIER_NONE)); menu.add(newExpression); subMenuSettings = new JMenu("Inställningar"); //Declares a submenu menu.add(subMenuSettings); //Adds a submenu called settings to rootmenu boxItemButtonAutoRestart = new JCheckBox("Nytt tal automatiskt"); boxItemButtonAutoRestart.setSelected(false); subMenuSettings.add(boxItemButtonAutoRestart); subMenuCompetition = new JMenu("Tävling.."); subMenuSettings.add(subMenuCompetition); buttonCompetition = new JMenuItem("Starta tävling!"); subMenuCompetition.add(buttonCompetition); textFieldCompetition = new JTextField("10"); textFieldCompetition.setToolTipText("Antal uttryck.."); subMenuCompetition.add(textFieldCompetition); subMenuMaxNumbers = new JMenu("Nummer intervall"); //Declares a subMenu (Numbers interval) subMenuSettings.add(subMenuMaxNumbers); //Adds subMenuNumbers to subMenuSettings subMenuArithmeticChoise = new JMenu("Välj räknesätt"); //Declares a submenu for arithmetic choise subMenuSettings.add(subMenuArithmeticChoise); //Adds submenu to menu boxItemAllowNegativeNumbers = new JCheckBox("Tillåt negativa tal"); //Declares a checkboxitem for allowing negative numbers subMenuSettings.add(boxItemAllowNegativeNumbers); //Add the checkboxitem to menu subMenuAnimation = new JMenu("Animering"); //Declares a subMenu (Animation) //subMenuSettings.add(subMenuAnimation); //Adds subMenuNumbers to subMenuSettings boxItemAnimationOnOff = new JCheckBox("Animering PÅ/AV",true); //Declares a checkboxitem for animation on/off subMenuAnimation.add(boxItemAnimationOnOff); //Adds the checkboxitem to menu radioButtonMaxNumber10 = new JRadioButton("0-10", true); //Delclares buttonchoises for numberinterval subMenuMaxNumbers.add(radioButtonMaxNumber10); //Adds them to menu radioButtonMaxNumber20 = new JRadioButton("0-20"); subMenuMaxNumbers.add(radioButtonMaxNumber20); radioButtonMaxNumber30 = new JRadioButton("0-30"); subMenuMaxNumbers.add(radioButtonMaxNumber30); radioButtonMaxNumber40 = new JRadioButton("0-40"); subMenuMaxNumbers.add(radioButtonMaxNumber40); radioButtonMaxNumber50 = new JRadioButton("0-50"); subMenuMaxNumbers.add(radioButtonMaxNumber50); radioButtonMinNum10MaxNumber20 = new JRadioButton("10-20"); subMenuMaxNumbers.add(radioButtonMinNum10MaxNumber20); radioButtonMinNum10MaxNumber30 = new JRadioButton("10-30"); subMenuMaxNumbers.add(radioButtonMinNum10MaxNumber30); radioButtonMinNum10MaxNumber40 = new JRadioButton("10-40"); subMenuMaxNumbers.add(radioButtonMinNum10MaxNumber40); radioButtonMinNum10MaxNumber50 = new JRadioButton("10-50"); subMenuMaxNumbers.add(radioButtonMinNum10MaxNumber50); radioButtonMinNum20MaxNumber30 = new JRadioButton("20-30"); subMenuMaxNumbers.add(radioButtonMinNum20MaxNumber30); radioButtonMinNum20MaxNumber40 = new JRadioButton("20-40"); subMenuMaxNumbers.add(radioButtonMinNum20MaxNumber40); radioButtonMinNum20MaxNumber50 = new JRadioButton("20-50"); subMenuMaxNumbers.add(radioButtonMinNum20MaxNumber50); radioButtonMinNum30MaxNumber40 = new JRadioButton("30-40"); subMenuMaxNumbers.add(radioButtonMinNum30MaxNumber40); radioButtonMinNum30MaxNumber50 = new JRadioButton("30-50"); subMenuMaxNumbers.add(radioButtonMinNum30MaxNumber50); radioButtonMinNum40MaxNumber50 = new JRadioButton("40-50"); subMenuMaxNumbers.add(radioButtonMinNum40MaxNumber50); numberGroup = new ButtonGroup(); //Adds buttons to group so only one choise can be active at once numberGroup.add(radioButtonMaxNumber10); numberGroup.add(radioButtonMaxNumber20); numberGroup.add(radioButtonMaxNumber30); numberGroup.add(radioButtonMaxNumber40); numberGroup.add(radioButtonMaxNumber50); numberGroup.add(radioButtonMinNum10MaxNumber20); numberGroup.add(radioButtonMinNum10MaxNumber30); numberGroup.add(radioButtonMinNum10MaxNumber40); numberGroup.add(radioButtonMinNum10MaxNumber50); numberGroup.add(radioButtonMinNum20MaxNumber30); numberGroup.add(radioButtonMinNum20MaxNumber40); numberGroup.add(radioButtonMinNum20MaxNumber50); numberGroup.add(radioButtonMinNum30MaxNumber40); numberGroup.add(radioButtonMinNum30MaxNumber50); numberGroup.add(radioButtonMinNum40MaxNumber50); radioButtonAddition = new JRadioButton("Addition", true); subMenuArithmeticChoise.add(radioButtonAddition); radioButtonSubtraction = new JRadioButton("Subtraktion"); subMenuArithmeticChoise.add(radioButtonSubtraction); radioButtonDivision = new JRadioButton("Division"); //subMenuArithmeticChoise.add(radioButtonDivision); radioButtonMultiplication = new JRadioButton("Multiplikation"); subMenuArithmeticChoise.add(radioButtonMultiplication); arithmeticChoiseGroup = new ButtonGroup(); arithmeticChoiseGroup.add(radioButtonAddition); arithmeticChoiseGroup.add(radioButtonSubtraction); arithmeticChoiseGroup.add(radioButtonDivision); arithmeticChoiseGroup.add(radioButtonMultiplication); addNewExpressionListener(); } /** * @author Nollan * Function adds listener to all radiobuttons in numberGroup and arithmeticChoiseGroup */ public void addNewExpressionListener(){ for (Enumeration<AbstractButton> buttons = numberGroup.getElements(); buttons.hasMoreElements();){ //Loops all buttons in numberGroup AbstractButton button = buttons.nextElement(); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { stopTimeCount(); createExpression(); } }); } for (Enumeration<AbstractButton> buttons = arithmeticChoiseGroup.getElements(); buttons.hasMoreElements();){ //Loops all buttons in numberGroup AbstractButton button = buttons.nextElement(); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { stopTimeCount(); createExpression(); } }); } newExpression.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { stopTimeCount(); createExpression(); } }); boxItemButtonAutoRestart.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { stopTimeCount(); createExpression(); } }); boxItemAllowNegativeNumbers.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { stopTimeCount(); createExpression(); } }); buttonCompetition.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { competitionActive = true; stopTimeCount(); startCompetition(); } });; } /** * @author Nollan * Function to set button images depending on their values * After this function all button should have a image corresponding to their value */ public void setButtonImages(){ for (JLabel jLabel : buttons) { //Loops all buttons (numbers) try { //Creates a img from imputstream and scales it to be 100x100 InputStream inputStream = ClassLoader.getSystemResourceAsStream(jLabel.getName()+".png"); Image buttonicon = ImageIO.read(inputStream).getScaledInstance(100, 100, Image.SCALE_SMOOTH); jLabel.setIcon(new ImageIcon(buttonicon)); //Sets the jLabel (buttons) image } catch (IOException e) { e.printStackTrace(); } } } /** * @author Nollan * Function gives every button (JLabel) a value */ public void randomizeButtonValues(){ int min = 0, max = 0, negMin = 0, negMax = 0; //Declares variables that hold min and max value and negative min max for (Enumeration<AbstractButton> buttons = numberGroup.getElements(); buttons.hasMoreElements();){ //Loops all buttons in numberGroup AbstractButton button = buttons.nextElement(); if (button.isSelected()){ //If the button is selected max = Integer.parseInt(button.getText().substring(button.getText().indexOf("-") +1)); //Set max to the choosen maxvalue min = Integer.parseInt(button.getText().substring(0,button.getText().indexOf("-"))); //Set min to the choosen minvalue if (boxItemAllowNegativeNumbers.isSelected()){ //If user want to allow negative numbers negMin = Integer.parseInt("-"+String.valueOf(max)); //Invert max and min to negative numbers negMax = Integer.parseInt("-"+String.valueOf(min)); //and save them in variables } break; //Break the loop } } ArrayList<Integer> list = new ArrayList<Integer>(); //List with int for (int count = min; count<=max; count++){ //Loops the number of numbers we want list.add(count); //Adds the number to the list } if (boxItemAllowNegativeNumbers.isSelected()){ if (negMax == 0){ negMax--; } for (int count = negMin; count<= negMax; count++){ //Loops the negativenumbers we want list.add(count); //Adds these to the list } } Collections.shuffle(list); //Shuffles the list int idx = 0; //Index counter for (JLabel button : buttons) { //Loops buttons button.setName(String.valueOf(list.get(idx)));; //adds the value in the list to the button idx++; //increases with 1 } } /** * @author Nollan * Function creates the expression that the user is supposed to solve. */ public void createExpression(){ if (!competitionActive || (competitionActive && competitionExpressionCount < Integer.parseInt(textFieldCompetition.getText()))){ randomizeButtonValues(); setButtonImages(); int answer = 0; listButtonOrder = new ArrayList<Integer>(); //List with int for (int count = 0; count< buttons.length; count++){ //Loops the number of numbers we want listButtonOrder.add(count); //Adds the number to the list } Collections.shuffle(listButtonOrder); //Shuffles the list String arithmetic = ""; if(radioButtonAddition.isSelected()){ //Checks if we are dealing with addition arithmetic = " + "; //Calculates the answer and stores it in variable answer = Integer.parseInt(buttons[listButtonOrder.get(0)].getName().toString()) + Integer.parseInt(buttons[listButtonOrder.get(1)].getName().toString()); } else if (radioButtonSubtraction.isSelected()) { //Checks if we are dealing with subtraction arithmetic = " - "; //Calculates the answer and stores it in variable answer = Integer.parseInt(buttons[listButtonOrder.get(0)].getName().toString()) - Integer.parseInt(buttons[listButtonOrder.get(1)].getName().toString()); while (!boxItemAllowNegativeNumbers.isSelected() && answer < 0){ randomizeButtonValues(); answer = Integer.parseInt(buttons[listButtonOrder.get(0)].getName().toString()) - Integer.parseInt(buttons[listButtonOrder.get(1)].getName().toString()); } } else if (radioButtonMultiplication.isSelected()){ //Checks if we are dealing with multiplication arithmetic = " \u2219 "; //Gives the value of multiplication sign //Calculates the answer and stores it in variable answer = Integer.parseInt(buttons[listButtonOrder.get(0)].getName().toString()) * Integer.parseInt(buttons[listButtonOrder.get(1)].getName().toString()); } else if (radioButtonDivision.isSelected()){ //Checks if we are dealing with division arithmetic = " / "; //Calculates the answer and stores it in variable answer = Integer.parseInt(buttons[listButtonOrder.get(0)].getName().toString()) / Integer.parseInt(buttons[listButtonOrder.get(1)].getName().toString()); } if (Integer.parseInt(buttons[0].getName()) > Integer.parseInt(buttons[1].getName())){ textFieldExpression.setText(buttons[listButtonOrder.get(0)].getName() + arithmetic + "____ = " + String.valueOf(answer) ); //Adds expression to textbox correctAnswer = 1; //Stores the correct index of answer } else { textFieldExpression.setText("____" + arithmetic + buttons[listButtonOrder.get(1)].getName() + " = " + String.valueOf(answer) ); //Adds expression to textbox correctAnswer = 0; //Stores the correct index of answer } setButtonImages(); //Calls function setButtonImages startTimeCount(); //Calls function startTimeCount } else { endCompetition(); } } /** * @author Nollan * Function handles the time counting */ public void updateTime(){ new Thread(new Runnable() { //Create new thread for timecount @Override public void run() { while (timeCountStarted){ //If timecount is started long timeElapsed = System.nanoTime() - startTime; //Current elapsed time is calculated totalTimeTmp = timeElapsed; timeElapsed = TimeUnit.MILLISECONDS.convert(timeElapsed, TimeUnit.NANOSECONDS); //Convert to correct format long seconds = TimeUnit.MILLISECONDS.toSeconds(timeElapsed); timeElapsed -= TimeUnit.SECONDS.toMillis(seconds); textFieldTime.setText(String.format("%01d.%02d", seconds,timeElapsed)); //Set text with correct format } } }).start(); } /** * @author Nollan * Function start the time count */ public void startTimeCount(){ timeCountStarted = true; //Sets variable timeCountStarted to true startTime = System.nanoTime(); //Current time updateTime(); //Calls function } /** * @author Nollan * Function stops the time count */ public void stopTimeCount(){ if (competitionExpressionCount != 1){ totalTime += totalTimeTmp; } timeCountStarted = false; //Sets to false } /** * @author Nollan * Function handle the competition start screen and enabling the correct GUI */ public void startCompetition(){ disableButtonClicks(); menuBar.setVisible(false); comptetitionCorrectCount = 0; competitionExpressionCount = 0; correctImg.setVisible(false); incorrectImg.setVisible(false); new Thread(new Runnable() { public void run() { try { expressionScreen.setVisible(false); //Hides the main screen (called expression) competitionCountDown.setVisible(true); //Shows the countdown for competition textFieldScoreCount.setVisible(true); //Shows the counter if (!textFieldCompetition.equals("")){ //IF the textfield isn't empty textFieldScoreCount.setText(Integer.toString(comptetitionCorrectCount)+ "/" + textFieldCompetition.getText()); } countDownText.setText("3"); //Countdown Thread.sleep(1000); countDownText.setText("2"); Thread.sleep(1000); countDownText.setText("1"); Thread.sleep(1000); competitionCountDown.setVisible(false); //Switches back to main screen expressionScreen.setVisible(true); boxItemButtonAutoRestart.setSelected(true); //Enables autorestart so the competition will generate new expressions. createExpression(); //Calls function enableButtonClicks(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); } public void endCompetition(){ disableButtonClicks(); menuBar.setVisible(true); new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(1500); totalTime = TimeUnit.MILLISECONDS.convert(totalTime, TimeUnit.NANOSECONDS); //Convert to correct format long seconds = TimeUnit.MILLISECONDS.toSeconds(totalTime); totalTime -= TimeUnit.SECONDS.toMillis(seconds); congratzText.setText("Du har precis avklarat tävlingen. Du hade " + textFieldScoreCount.getText() + " rätt."); congratzText2nd.setText("Total tid för detta var " + String.format("%01d.%02d", seconds,totalTime) + "s."); correctImg.setVisible(false); incorrectImg.setVisible(false); comptetitionCorrectCount = 0; competitionExpressionCount = 0; expressionScreen.setVisible(false); correctImg.setVisible(false); textFieldExpression.setText(""); congratzScreen.setVisible(true); textFieldTime.setText(""); boxItemButtonAutoRestart.setSelected(false); textFieldScoreCount.setText(""); competitionActive = false; addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseClicked(MouseEvent e) { congratzScreen.setVisible(false); expressionScreen.setVisible(true); enableButtonClicks(); }}); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }).start(); //Här vill vi visa en bra jobbat skärm. Summan av tid och antal korrekta/antal frågor. //Även slå av competition och autorestart } }
package com.example.a77354.android_final_project.HttpServiceInterface; import java.util.Map; import retrofit2.http.GET; import retrofit2.http.Headers; /** * Created by 77354 on 2018/1/6. */ public interface GetArticleServiceInterface { @Headers({"Content-Type: application/json","Accept: application/json"}) @GET("articles") rx.Observable<Map<String, Map<String, String>>> getArticle(); }
package com.javalab.controller; public class AppController { }
/** * */ package frames; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Toolkit; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JPanel; import resources.AllImage; /** * @author NikitaNB * */ public class HelpFrame extends JFrame { private JPanel panel =null; public static final ImageIcon engineOptimalSel=(ImageIcon)AllImage.engineOptimalSel; public HelpFrame() { initGUI(); } private void initGUI() { this.setResizable(false); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); this.setSize(engineOptimalSel.getIconWidth()+18, engineOptimalSel.getIconHeight()+45); this.setLocation(screenSize.width/2-this.getSize().width/2, screenSize.height/2-this.getSize().height/2); this.setTitle("JTetris"); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); this.setContentPane(panel=new JPanel(){ private static final long serialVersionUID = 1L; public void paintComponent(Graphics g){ super.paintComponent(g); Graphics2D grf = (Graphics2D)g; grf.drawImage(engineOptimalSel.getImage(), 0, 0, null); } }); panel.setBackground(Color.BLACK); } }
/* * 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 unitTests; import model.Location; import model.Planning; import model.Vehicle; import model.VehicleLocation; import org.junit.Test; import static org.junit.Assert.*; import org.junit.Before; /** * * @author Team Foufou */ public class LocationTest { private Location location; /** * Function run before each call to a test function */ @Before public void setUp() { } /** * Test for the Location Class constructor */ @Test public final void LegalConstructor() { this.location = new Location(); assertEquals("[LegalConstructor] Constructeur par défaut - x différent de 0", this.location.getX(), null); assertEquals("[LegalConstructor] Constructeur par défaut - y différent de 0", this.location.getY(), null); assertEquals("[LegalConstructor] Constructeur par défaut - startTime différent de 0", this.location.getStartTime(), new Integer(0)); assertEquals("[LegalConstructor] Constructeur par défaut - endTime différent de 0", this.location.getEndTime(), new Integer(0)); assertTrue("[LegalConstructor] Constructeur par défaut - myRoads pas instancié", this.location.getMyRoads().isEmpty()); assertTrue("[LegalConstructor] Constructeur par défaut - vehicles pas instancié", this.location.getMyRoads().isEmpty()); this.location = new Location(5, 10.0, 20.0, 140, 130); assertEquals("[LegalConstructor] Constructeur par défaut - Mauvais x", this.location.getX(), new Double(10.0)); assertEquals("[LegalConstructor] Constructeur par défaut - Mauvais y", this.location.getY(), new Double(20.0)); assertEquals("[LegalConstructor] Constructeur par défaut - Mauvais startTime", this.location.getStartTime(), new Integer(140)); assertEquals("[LegalConstructor] Constructeur par défaut - Mauvais endTime", this.location.getEndTime(), new Integer(130)); assertTrue("[LegalConstructor] Constructeur par défaut - myRoads pas instancié", this.location.getMyRoads().isEmpty()); assertTrue("[LegalConstructor] Constructeur par défaut - vehicles pas instancié", this.location.getMyRoads().isEmpty()); } /** * Test for the Location addDestination function */ @Test public final void addDestination() { Boolean returnValue; Location destination; this.location = new Location(2, 10.0, 20.0, 110, 270); destination = null; returnValue = this.location.addDestination(destination, 20.0, 15); assertTrue("[addDestination] Destination est null", !returnValue && this.location.getMyRoads().isEmpty()); destination = new Location(5, 10.0, 20.0, 110, 270); returnValue = this.location.addDestination(destination, null, 15); assertTrue("[addDestination] Coût est null", !returnValue && this.location.getMyRoads().isEmpty()); destination = new Location(5, 10.0, 20.0, 110, 270); returnValue = this.location.addDestination(destination, 20.0, null); assertTrue("[addDestination] Time est null", !returnValue && this.location.getMyRoads().isEmpty()); destination = new Location(2, 10.0, 20.0, 110, 270); returnValue = this.location.addDestination(destination, 20.0, 100); assertTrue("[addDestination] Destination est égal à la location", !returnValue && this.location.getMyRoads().isEmpty()); destination = new Location(5, 10.0, 20.0, 110, 270); returnValue = this.location.addDestination(destination, 20.0, 15); assertTrue("[addDestination] Destination lambda", returnValue && this.location.getMyRoads().containsKey(destination)); returnValue = this.location.addDestination(destination, 20.0, 15); assertTrue("[addLocation] Location lambda doublon", !returnValue && this.location.getMyRoads().size() == 1); } /** * Test for the Location addVehicle function */ @Test public final void addVehicle() { Boolean returnValue; Vehicle vehicle; VehicleLocation vehicleLocation; Planning planning = new Planning(); this.location = new Location(2, 10.0, 20.0, 110, 270); vehicle = null; vehicleLocation = new VehicleLocation(); returnValue = this.location.addVehicle(vehicle, vehicleLocation); assertTrue("[addVehicle] Vehicle est null", !returnValue && this.location.getVehicles().isEmpty()); vehicle = new Vehicle(200, planning); vehicleLocation = null; returnValue = this.location.addVehicle(vehicle, vehicleLocation); assertTrue("[addVehicle] VehicleLocationRelation est null", !returnValue && this.location.getVehicles().isEmpty()); vehicle = new Vehicle(200, planning); vehicleLocation = new VehicleLocation(vehicle, this.location); returnValue = this.location.addVehicle(vehicle, vehicleLocation); assertTrue("[addVehicle] Vehicle et VehicleLocationRelation lambda", !returnValue && this.location.getVehicles().isEmpty()); } /** * Test for the Location toString function */ @Test public void testToString() { this.location = new Location(2, 10.0, 20.0, 110, 270); String result = this.location.toString(); assertNotNull("[toString] Must be defined and return a value", result); assertFalse("[toString] Must be defined and return a value", result.isEmpty()); } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.server.handler; import java.util.Arrays; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import org.springframework.http.HttpStatus; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebExceptionHandler; import org.springframework.web.server.WebHandler; import org.springframework.web.server.adapter.HttpWebHandlerAdapter; import org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest; import org.springframework.web.testfixture.server.MockServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link ExceptionHandlingWebHandler}. * @author Rossen Stoyanchev */ public class ExceptionHandlingWebHandlerTests { private final WebHandler targetHandler = new StubWebHandler(new IllegalStateException("boo")); private final ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("http://localhost:8080")); @Test void handleErrorSignal() { createWebHandler(new BadRequestExceptionHandler()).handle(this.exchange).block(); assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); } @Test void handleErrorSignalWithMultipleHttpErrorHandlers() { createWebHandler( new UnresolvedExceptionHandler(), new UnresolvedExceptionHandler(), new BadRequestExceptionHandler(), new UnresolvedExceptionHandler()).handle(this.exchange).block(); assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); } @Test void unresolvedException() { Mono<Void> mono = createWebHandler(new UnresolvedExceptionHandler()).handle(this.exchange); StepVerifier.create(mono).expectErrorMessage("boo").verify(); assertThat(this.exchange.getResponse().getStatusCode()).isNull(); } @Test void unresolvedExceptionWithWebHttpHandlerAdapter() { new HttpWebHandlerAdapter(createWebHandler(new UnresolvedExceptionHandler())) .handle(this.exchange.getRequest(), this.exchange.getResponse()).block(); assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); } @Test void thrownExceptionBecomesErrorSignal() { createWebHandler(new BadRequestExceptionHandler()).handle(this.exchange).block(); assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); } @Test void thrownExceptionIsStoredAsExchangeAttribute() { createWebHandler(new BadRequestExceptionHandler()).handle(this.exchange).block(); Exception exceptionAttribute = this.exchange.getAttribute(ExceptionHandlingWebHandler.HANDLED_WEB_EXCEPTION); assertThat(exceptionAttribute).isInstanceOf(IllegalStateException.class); } private WebHandler createWebHandler(WebExceptionHandler... handlers) { return new ExceptionHandlingWebHandler(this.targetHandler, Arrays.asList(handlers)); } private static class StubWebHandler implements WebHandler { private final RuntimeException exception; private final boolean raise; StubWebHandler(RuntimeException exception) { this(exception, false); } StubWebHandler(RuntimeException exception, boolean raise) { this.exception = exception; this.raise = raise; } @Override public Mono<Void> handle(ServerWebExchange exchange) { if (this.raise) { throw this.exception; } return Mono.error(this.exception); } } private static class BadRequestExceptionHandler implements WebExceptionHandler { @Override public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) { exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST); return Mono.empty(); } } /** Leave the exception unresolved. */ private static class UnresolvedExceptionHandler implements WebExceptionHandler { @Override public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) { return Mono.error(ex); } } }
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.core.type; /** * Interface that defines abstract access to the annotations of a specific * method, in a form that does not require that method's class to be loaded yet. * * @author Juergen Hoeller * @author Mark Pollack * @author Chris Beams * @author Phillip Webb * @since 3.0 * @see StandardMethodMetadata * @see AnnotationMetadata#getAnnotatedMethods * @see AnnotatedTypeMetadata */ public interface MethodMetadata extends AnnotatedTypeMetadata { /** * Get the name of the underlying method. */ String getMethodName(); /** * Get the fully-qualified name of the class that declares the underlying method. */ String getDeclaringClassName(); /** * Get the fully-qualified name of the underlying method's declared return type. * @since 4.2 */ String getReturnTypeName(); /** * Determine whether the underlying method is effectively abstract: * i.e. marked as abstract in a class or declared as a regular, * non-default method in an interface. * @since 4.2 */ boolean isAbstract(); /** * Determine whether the underlying method is declared as 'static'. */ boolean isStatic(); /** * Determine whether the underlying method is marked as 'final'. */ boolean isFinal(); /** * Determine whether the underlying method is overridable, * i.e. not marked as static, final, or private. */ boolean isOverridable(); }
package com.project.strings.entity; /** * Created by kleba on 03.04.2018. */ public class PunctMarks implements TextPart{ private String punctMarc; public PunctMarks(String punctMarc){ this.punctMarc=punctMarc; } public void setPunctMarc(String punctMarc) { this.punctMarc = punctMarc; } public String getPunctMarc() { return punctMarc; } @Override public String toString() { return "PunctMarks{" + "punctMarc=" + punctMarc + '}'; } }
package bis.project.services; import java.util.Set; import bis.project.model.BankMessages; public interface BankMessagesServices { public Set<BankMessages> getBankMessages(); public BankMessages getBankMessage(Integer id); public BankMessages addBankMessage(BankMessages bankMessage); public BankMessages updateBankMessage(BankMessages bankMessage); public void deleteBankMessage(Integer id); }
/* * Created on Jul 26, 2015 */ package basics; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.Set; import java.util.stream.Collectors; import javafx.application.Application; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.scene.Scene; import javafx.scene.chart.LineChart; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.scene.control.ListView; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; public class UnemployPlotting extends Application { private static class AreaInfo { public final String code; public final String desc; public AreaInfo(String c, String d) { code = c; desc = d; } @Override public String toString() { return desc + " (" + code + ")"; } } private static class UnemployInfo { public final String code; public final String series; public final int year; public final int month; public final double value; public UnemployInfo(String c, String s, int y, int m, double v) { code = c; series = s; year = y; month = m; value = v; } } private final List<AreaInfo> areas; private final List<UnemployInfo> unemployInfo; public UnemployPlotting() { unemployInfo = readUnemployment(); Set<String> codes = unemployInfo.stream().map(ui -> ui.code).collect(Collectors.toSet()); areas = readAreas(codes); } @Override public void start(Stage stage) { NumberAxis xAxis = new NumberAxis(); xAxis.setAutoRanging(false); xAxis.setLowerBound(1976); xAxis.setUpperBound(2016); NumberAxis yAxis = new NumberAxis(); yAxis.setAutoRanging(false); yAxis.setLowerBound(0); yAxis.setUpperBound(15); final ObservableList<XYChart.Series<Number, Number>> data = FXCollections.observableList(new ArrayList<>()); data.add(new XYChart.Series<Number, Number>()); setData(areas.get(0).code,data); ListView<AreaInfo> areaList = new ListView<>(FXCollections.observableList(areas)); areaList.getSelectionModel().getSelectedItems().addListener((ListChangeListener.Change<? extends AreaInfo> change) -> { setData(areas.get(areaList.selectionModelProperty().getValue().getSelectedIndex()).code,data); }); LineChart<Number, Number> chart = new LineChart<>(xAxis, yAxis, data); chart.animatedProperty().set(true); BorderPane root = new BorderPane(); root.setLeft(areaList); root.setCenter(chart); Scene scene = new Scene(root, 800, 500); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(args); } private void setData(final String code, ObservableList<XYChart.Series<Number, Number>> data) { List<XYChart.Data<Number, Number>> filtered = unemployInfo.stream() .filter(ui -> ui.code.equals(code) && "03".equals(ui.series)) .map(ui -> new XYChart.Data<Number, Number>(ui.year+ui.month/12.0, ui.value)).collect(Collectors.toList()); data.get(0).getData().clear(); data.get(0).getData().addAll(filtered); } private List<AreaInfo> readAreas(Set<String> codes) { List<AreaInfo> ret = new ArrayList<>(); try (Scanner sc = new Scanner(new File("la.area"))) { sc.nextLine(); while (sc.hasNextLine()) { String line = sc.nextLine(); String[] parts = line.split("\t+"); if (codes.contains(parts[1])) { AreaInfo ai = new AreaInfo(parts[1].trim(), parts[2].trim()); ret.add(ai); } } } catch (FileNotFoundException e) { e.printStackTrace(); } return ret; } private List<UnemployInfo> readUnemployment() { List<UnemployInfo> ret = new ArrayList<>(); try (Scanner sc = new Scanner(new File("la.data.51.Texas"))) { sc.nextLine(); while (sc.hasNextLine()) { String line = sc.nextLine(); String[] parts = line.split("\\s+"); int year = Integer.parseInt(parts[1]); int month = Integer.parseInt(parts[2].substring(1)); double value = Double.parseDouble(parts[3]); UnemployInfo ui = new UnemployInfo(parts[0].substring(3, parts[0].length() - 2), parts[0].substring(parts[0].length() - 2), year, month, value); ret.add(ui); } } catch (FileNotFoundException e) { e.printStackTrace(); } return ret; } }
package com.bistel.mq; import java.util.HashMap; import java.util.Map; public class QueueInfo { private String name; private boolean durable; private boolean autoDelete; private boolean exclusive; private Map<String, Object> args; public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isDurable() { return durable; } public void setDurable(boolean durable) { this.durable = durable; } public boolean isAutoDelete() { return autoDelete; } public void setAutoDelete(boolean autoDelete) { this.autoDelete = autoDelete; } public boolean isExclusive() { return exclusive; } public void setExclusive(boolean exclusive) { this.exclusive = exclusive; } public Map<String, Object> getArgs() { return args; } public void setArgs(Map<String, Object> args) { this.args = args; } public void addArg(String key, Object value) { if(args==null) { args = new HashMap<String, Object>(); } args.put(key, value); } }
package com.sinodynamic.hkgta.entity.crm; import java.io.Serializable; import java.util.Date; 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.NamedQuery; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import javax.persistence.Version; /** * The persistent class for the corporate_profile database table. * */ @Entity @Table(name="corporate_profile") @NamedQuery(name="CorporateProfile.findAll", query="SELECT c FROM CorporateProfile c") public class CorporateProfile implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="corporate_id", unique=true, nullable=false) private Long corporateId; @Column(name="br_no", nullable=false, length=50) private String brNo; @Column(length=250) private String address1; @Column(length=250) private String address2; @Column(name="business_nature_code", length=50) private String businessNatureCode; @Column(name="company_name", length=100) private String companyName; @Column(name="company_name_nls", length=100) private String companyNameNls; @Column(name="contact_email") private String contactEmail; @Column(name="contact_person_firstname") private String contactPersonFirstname; @Column(name="contact_person_lastname") private String contactPersonLastname; @Column(name="contact_phone", length=50) private String contactPhone; @Column(name="contact_phone_mobile") private String contactPhoneMobile; @Column(name="create_by", length=50) private String createBy; @Column(name="create_date", nullable=false) private Date createDate; @Column(nullable=false, length=30) private String district; @Column(length=10) private String status; @Column(name="update_by", length=50) private String updateBy; @Version @Column(name="ver_no", nullable = false) private Long version; @Temporal(TemporalType.TIMESTAMP) @Column(name="update_date") private Date updateDate; @OneToOne(mappedBy="corporateProfile") private CorporateAdditionAddress corporateAdditionAddress; @Transient private List<CorporateMember> corporateMembers; @Transient private List<CorporateServiceAcc> corporateServiceAccs; public CorporateProfile() { } public Long getCorporateId() { return this.corporateId; } public void setCorporateId(Long corporateId) { this.corporateId = corporateId; } public String getBrNo() { return this.brNo; } public void setBrNo(String brNo) { this.brNo = brNo; } public String getBusinessNatureCode() { return this.businessNatureCode; } public void setBusinessNatureCode(String businessNatureCode) { this.businessNatureCode = businessNatureCode; } public String getCompanyName() { return this.companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public String getCompanyNameNls() { return this.companyNameNls; } public void setCompanyNameNls(String companyNameNls) { this.companyNameNls = companyNameNls; } public String getContactPhone() { return this.contactPhone; } public void setContactPhone(String contactPhone) { this.contactPhone = contactPhone; } public String getCreateBy() { return this.createBy; } public void setCreateBy(String createBy) { this.createBy = createBy; } public Date getCreateDate() { return this.createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public String getDistrict() { return this.district; } public void setDistrict(String district) { this.district = district; } public String getStatus() { return this.status; } public void setStatus(String status) { this.status = status; } public String getUpdateBy() { return this.updateBy; } public void setUpdateBy(String updateBy) { this.updateBy = updateBy; } public Date getUpdateDate() { return this.updateDate; } public Long getVersion() { return this.version; } public void setVersion(Long version) { this.version = version; } public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } public List<CorporateMember> getCorporateMembers() { return this.corporateMembers; } public CorporateAdditionAddress getCorporateAdditionAddress() { return corporateAdditionAddress; } public void setCorporateAdditionAddress( CorporateAdditionAddress corporateAdditionAddress) { this.corporateAdditionAddress = corporateAdditionAddress; } public List<CorporateServiceAcc> getCorporateServiceAccs() { return corporateServiceAccs; } public void setCorporateServiceAccs( List<CorporateServiceAcc> corporateServiceAccs) { this.corporateServiceAccs = corporateServiceAccs; } public void setCorporateMembers(List<CorporateMember> corporateMembers) { this.corporateMembers = corporateMembers; } public String getAddress1() { return address1; } public void setAddress1(String address1) { this.address1 = address1; } public String getAddress2() { return address2; } public void setAddress2(String address2) { this.address2 = address2; } public String getContactEmail() { return contactEmail; } public void setContactEmail(String contactEmail) { this.contactEmail = contactEmail; } public String getContactPersonFirstname() { return contactPersonFirstname; } public void setContactPersonFirstname(String contactPersonFirstname) { this.contactPersonFirstname = contactPersonFirstname; } public String getContactPersonLastname() { return contactPersonLastname; } public void setContactPersonLastname(String contactPersonLastname) { this.contactPersonLastname = contactPersonLastname; } public String getContactPhoneMobile() { return contactPhoneMobile; } public void setContactPhoneMobile(String contactPhoneMobile) { this.contactPhoneMobile = contactPhoneMobile; } public boolean equals(CorporateProfile c){ if (!compare(this.address1, c.getAddress1())) { return false; } if (!compare(this.address2, c.getAddress2())) { return false; } if (!compare(this.brNo, c.getBrNo())) { return false; } if (!compare(this.businessNatureCode, c.getBusinessNatureCode())) { return false; } if (!compare(this.companyName, c.getCompanyName())) { return false; } if (!compare(this.companyNameNls, c.getCompanyNameNls())) { return false; } if (!compare(this.contactEmail, c.getContactEmail())) { return false; } if (!compare(this.district, c.getDistrict())) { return false; } CorporateAdditionAddress address = c.getCorporateAdditionAddress(); if (null != this.corporateAdditionAddress && null != address && this.corporateAdditionAddress.getAddressType().equals(address.getAddressType())) { if (!compare(this.corporateAdditionAddress.getAddress1(), address.getAddress1())) { return false; } if (!compare(this.corporateAdditionAddress.getAddress2(), address.getAddress2())) { return false; } if (!compare(this.corporateAdditionAddress.getHkDistrict(), address.getHkDistrict())) { return false; } } return true; } public boolean compare(Object source,Object target){ if (null != source) { if(!source.equals(target)){ return false; } }else { if (null != target){ return false; } } return true; } }
package ntou.cs.java2021.hw2; /** * HandOfCards(手牌) 可以存五張牌和一個對應的牌型名稱 * * @author 00857005周固廷 */ public class HandOfCards { private Card[] cards; private CardType type; public Card[] getCards() { return cards; } public void setCards(Card[] cards) { this.cards = cards.clone(); } public CardType getType() { return type; } public void setType(CardType type) { this.type = type; } @Override public String toString() { String str = "Your Cards: "; for (int i = 0; i < this.cards.length; i++) { str += this.cards[i]; if (i != this.cards.length - 1) str += ","; } str += "\n"; str += "Card type: "; str += this.type.getName(); return str; } }
/** * www.yiji.com Inc. * Copyright (c) 2012 All Rights Reserved. */ package com.yjf.common.cache; /** * * @Filename LocalCache.java * * @Description <p>本地缓存必须实现的接口,提供刷新机制;减少大量的远程访问开销</p> * * @Version 1.0 * * @Author peigen * * @Email peigen@yiji.com * * @History *<li>Author: peigen</li> *<li>Date: 2012-2-6</li> *<li>Version: 1.0</li> *<li>Content: create</li> * */ public interface LocalCache { /** * 初始化本地缓存 */ void initLocalCache(); /** * 刷新本地缓存信息 */ void refreshLocalCache(); /** * 获取本地缓存的名称 * @return */ String getLocalCacheName(); /** * 打印缓存信息 * @return */ void dump(); }
package com.himanshu.poc.spring.samples.springbootwebreactive.repository; import com.himanshu.poc.spring.samples.springbootwebreactive.domain.User; import org.springframework.data.repository.CrudRepository; public interface UserRepository extends CrudRepository<User, Long> { }
package io.datawire.labs.hellospring; import java.util.concurrent.TimeUnit; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { private static long start = System.currentTimeMillis(); @GetMapping("/") public String sayHello() { long millis = System.currentTimeMillis() - start; String uptime = String.format("%02d:%02d", TimeUnit.MILLISECONDS.toMinutes(millis), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))); String environment = System.getenv("BUILD_PROFILE"); // environment = "TEST"; return String.format("%s (%s)", uptime, environment); } }
package com.nit.order.service; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.nit.order.model.OrderItem; import com.nit.order.repository.OrderItemRepository; @Service public class OrderItemService { @Autowired private OrderItemRepository orderItemRepository; public OrderItem saveOrderItem(OrderItem orderiteam) { return orderItemRepository.save(orderiteam); } public Iterable<OrderItem> getAllOderIeams() { return orderItemRepository.findAll(); } public Optional<List<OrderItem>> findByNameProductname(String productname) { return orderItemRepository.findByProductname(productname); } }
package SalarySheet; import jdk.nashorn.internal.runtime.Version; import java.io.File; import java.sql.*; import java.sql.ResultSet; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; import org.h2.jdbcx.JdbcConnectionPool; /** * Created by famed on 5/6/16. */ public class SqlConnect { public static Connection con() throws ClassNotFoundException, SQLException { /* Connection con = null; Statement st = null; ResultSet rs = null; Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/SalarySheet?useUnicode=yes&characterEncoding=UTF-8"; String user = "root"; String password = "admin"; */ String dbfile = (new File("").getAbsolutePath()+"/salarymakerfile/db/salarysheet"); Connection con = null; Statement st = null; ResultSet rs = null; Class.forName("org.h2.Driver"); System.out.println(dbfile); String url = "jdbc:h2:"+dbfile; //For unicode ?useUnicode=yes&characterEncoding=UTF-8 String user = "root"; String password = "admin"; try { con = DriverManager.getConnection(url, user, password); } catch (SQLException ex) { ConnectionError connectionError = new ConnectionError(); connectionError.alertError(); System.out.println(ex); } return con; } }
/* * Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.jet.beam.transforms; import org.apache.beam.sdk.PipelineResult; import org.apache.beam.sdk.coders.BigEndianIntegerCoder; import org.apache.beam.sdk.coders.KvCoder; import org.apache.beam.sdk.coders.NullableCoder; import org.apache.beam.sdk.coders.StringUtf8Coder; import org.apache.beam.sdk.testing.PAssert; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.transforms.KvSwap; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; import org.junit.Test; import java.util.Arrays; import static junit.framework.TestCase.assertEquals; /* "Inspired" by org.apache.beam.sdk.transforms.KvSwapTest */ @SuppressWarnings("ALL") public class KvSwapTest extends AbstractTransformTest { private static final KV<String, Integer>[] TABLE = new KV[]{ KV.of("one", 1), KV.of("two", 2), KV.of("three", 3), KV.of("four", 4), KV.of("dup", 4), KV.of("dup", 5), KV.of("null", null), }; @Test public void testKvSwap() { PCollection<KV<String, Integer>> input = pipeline.apply( Create.of(Arrays.asList(TABLE)) .withCoder( KvCoder.of( StringUtf8Coder.of(), NullableCoder.of(BigEndianIntegerCoder.of())))); PCollection<KV<Integer, String>> output = input.apply(KvSwap.create()); PAssert.that(output) .containsInAnyOrder( KV.of(1, "one"), KV.of(2, "two"), KV.of(3, "three"), KV.of(4, "four"), KV.of(4, "dup"), KV.of(5, "dup"), KV.of(null, "null")); PipelineResult.State state = pipeline.run().waitUntilFinish(); assertEquals(PipelineResult.State.DONE, state); } }
package com.database.table; import javax.persistence.*; import java.io.Serializable; import java.util.Date; import java.util.UUID; @MappedSuperclass public abstract class BaseEntity implements Serializable { private static final long serialVersionUID = 4042124750892130622L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private UUID id; @Column(name = "deleted") private boolean deleted = false; @Column(name = "created_at", updatable = false) @Temporal(TemporalType.TIMESTAMP) private Date createdAt; @Temporal(TemporalType.TIMESTAMP) @Column(name = "updated_at") private Date updatedAt; @PrePersist protected void onCreate() { createdAt = new Date(); updatedAt = new Date(); } @PreUpdate protected void onUpdate() { updatedAt = new Date(); } public boolean isDeleted() { return deleted; } public void setDeleted(boolean deleted) { this.deleted = deleted; } public void setId(UUID id) { this.id = id; } public UUID getId() { return id; } public Date getCreatedAt() { return createdAt; } }
package dao.impl; import dao.ConfigurationDao; import entities.Configuration; import org.apache.log4j.Logger; import org.springframework.stereotype.Repository; import java.io.Serializable; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @Repository public class ConfigurationDaoImpl extends AbstractDao implements ConfigurationDao { private static Logger log = Logger.getLogger(ConfigurationDaoImpl.class); private static final String SAVE_CONFIGURATION_SQL = "INSERT INTO Configuration (id, `value`) VALUES (?,?)"; private static final String GET_CONFIGURATION_BY_ID_SQL = "SELECT * FROM Configuration WHERE id=?"; private static final String UPDATE_CONFIGURATION_BY_ID_SQL = "UPDATE Configuration SET `value`=? WHERE id=?"; private static final String DELETE_CONFIGURATION_BY_ID_SQL = "DELETE FROM Configuration WHERE id=?"; private PreparedStatement psSave = null; private PreparedStatement psGet = null; private PreparedStatement psUpdate = null; private PreparedStatement psDelete = null; public ConfigurationDaoImpl() {} /** * Saves the entity type <Configuration> in the database * * @param configuration determine entity with type <Configuration> * @return saved entity with not null id or * null if configuration is null or configuration.id is null * @throws SQLException if can't save entity */ @Override public Configuration save(Configuration configuration) throws SQLException { if (configuration != null && configuration.getId() != null) { try { if (psSave == null) { psSave = psSave = prepareStatement(SAVE_CONFIGURATION_SQL); } psSave.setString(1, configuration.getId()); psSave.setString(2, configuration.getValue()); psSave.executeUpdate(); } catch (SQLException e) { String errorMessage = "Can't execute SQL: " + psSave + e.getMessage(); log.error(errorMessage); throw new SQLException(errorMessage); } return configuration; } else { return null; } } /** * returns an entity with an id from the database * * @param id determine id of entity in database * @return entity with type <Configuration> from the database, * or null if such an entity was not found * @throws SQLException if there is an error connecting to the database */ @Override public Configuration get(Serializable id) throws SQLException { if (psGet == null) { psGet = prepareStatement(GET_CONFIGURATION_BY_ID_SQL); } psGet.setString(1, (String) id); psGet.executeQuery(); try (ResultSet rs = psGet.getResultSet()) { if (rs.next()) { return populateEntity(rs); } } catch (SQLException e) { String errorMessage = "Can't execute SQL: " + psGet + e.getMessage(); log.error(errorMessage); throw new SQLException(errorMessage); } return null; } /** * update an entity with an id = configuration.id in the database * * @param configuration determine a new entity to be updated * in the database with id = configuration.id * @throws SQLException if there is an error updating entity in the database */ @Override public void update(Configuration configuration) throws SQLException { if (configuration == null) { return; } try { if (psUpdate == null) { psUpdate = prepareStatement(UPDATE_CONFIGURATION_BY_ID_SQL); } psUpdate.setString(2, configuration.getId()); psUpdate.setString(1, configuration.getValue()); psUpdate.executeUpdate(); } catch (SQLException e) { String errorMessage = "Can't execute SQL: " + psUpdate + e.getMessage(); log.error(errorMessage); throw new SQLException(errorMessage); } } /** * removes from the database an entity with type <Configuration> and id * * @param id determine id of entity in database * @return returns the number of deleted rows from the database * @throws SQLException if there is an error deleting entity from the database */ @Override public int delete(Serializable id) throws SQLException { try { if (psDelete == null) { psDelete = prepareStatement(DELETE_CONFIGURATION_BY_ID_SQL); } psDelete.setString(1, (String) id); return psDelete.executeUpdate(); } catch (SQLException e) { String errorMessage = "Can't execute SQL: " + psDelete + e.getMessage(); log.error(errorMessage); throw new SQLException(errorMessage); } } private Configuration populateEntity(ResultSet rs) throws SQLException { Configuration entity = new Configuration(); entity.setId(rs.getString(1)); entity.setValue(rs.getString(2) ); return entity; } }
package com.tech42.callrecorder.views; import android.Manifest; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.IntentSender; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.IBinder; import android.support.annotation.NonNull; import android.util.Log; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.drive.DriveId; import com.google.api.client.extensions.android.http.AndroidHttp; import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential; import com.google.api.client.http.FileContent; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.ExponentialBackOff; import com.google.api.services.drive.DriveScopes; import com.tech42.callrecorder.adapters.CallRecordAdapter; import com.tech42.callrecorder.adapters.RealmCallRecordsAdapter; import com.tech42.callrecorder.model.CallRecord; import com.tech42.callrecorder.realm.RealmController; import java.io.File; import java.util.Arrays; import java.util.Collections; import java.util.List; import io.realm.Realm; import io.realm.RealmResults; import pub.devrel.easypermissions.AfterPermissionGranted; import pub.devrel.easypermissions.EasyPermissions; /** * Created by sathish on 15/07/17. */ public class AutomaticSyncActivity extends Service implements GoogleApiClient.ConnectionCallbacks{ // Drive API GoogleAccountCredential mCredential; ProgressDialog mProgress; static final int REQUEST_ACCOUNT_PICKER = 1000; static final int REQUEST_AUTHORIZATION = 1001; static final int REQUEST_GOOGLE_PLAY_SERVICES = 1002; static final int REQUEST_PERMISSION_GET_ACCOUNTS = 1003; private static final String PREF_ACCOUNT_NAME = "accountName"; private static final String[] SCOPES = {DriveScopes.DRIVE_METADATA_READONLY}; private com.google.api.services.drive.Drive mService = null; private int size, totalSize = 0, rowIndex = 0; private CallRecordAdapter callRecordAdapter; private Realm realm; private CallRecord callRecordUpdate; SharedPreferences pref; SharedPreferences.Editor editor; private String EXISTING_FOLDER_ID; private static final int REQUEST_CODE_RESOLUTION = 3; private GoogleApiClient mGoogleApiClient; private DriveId mFolderDriveId; private String FILE_NAME, FILEPATH; private static final String TAG = AutomaticSyncActivity.class.getName(); @Override public void onCreate() { mCredential = GoogleAccountCredential.usingOAuth2( getApplicationContext(), Arrays.asList(SCOPES)) .setBackOff(new ExponentialBackOff()); callRecordAdapter = new CallRecordAdapter(getApplicationContext()); pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode editor = pref.edit(); EXISTING_FOLDER_ID = pref.getString("EXISTING_FOLDER_ID", ""); getRealmInstance(); refreshRealmInstance(); callRecordUpdate = new CallRecord(); getResultsFromApi(); } public void getRealmInstance() { realm = RealmController.with(getApplication()).getRealm(); } public void refreshRealmInstance() { RealmController.with(getApplication()).refresh(); setRealmAdapter(RealmController.with(getApplication()).queryedCallRecords("storage", "Local")); size = (RealmController.with(getApplication()).queryedCallRecords("storage", "Local").size()); } public void setRealmAdapter(RealmResults<CallRecord> CallRecords) { RealmCallRecordsAdapter realmAdapter = new RealmCallRecordsAdapter(getApplicationContext(), CallRecords, true); // Set the data and tell the RecyclerView to draw callRecordAdapter.setRealmAdapter(realmAdapter); callRecordAdapter.notifyDataSetChanged(); } public void getResultsFromApi() { if (!isGooglePlayServicesAvailable()) { acquireGooglePlayServices(); } else if (mCredential.getSelectedAccountName() == null) { chooseAccount(); } else if (!isDeviceOnline()) { Toast.makeText(getApplicationContext(), "No network connection available. So this record stored in your mobile", Toast.LENGTH_LONG).show(); } else { if (!pref.getString("EXISTING_FOLDER_ID", "").isEmpty()) { totalSize = callRecordAdapter.getItemCount(); for (int i = 0; i < totalSize; i++) { new AutomaticSyncActivity.AddFileTask(mCredential, callRecordAdapter.getItem(0).getFileName()).execute(); } } } } @AfterPermissionGranted(REQUEST_PERMISSION_GET_ACCOUNTS) private void chooseAccount() { if (EasyPermissions.hasPermissions( this, Manifest.permission.GET_ACCOUNTS)) { String accountName = pref.getString("ACCOUNT_NAME", ""); if (!accountName.isEmpty()) { mCredential.setSelectedAccountName(accountName); getResultsFromApi(); } else { // Start a dialog from which the user can choose an account } } else { // Request the GET_ACCOUNTS permission via a user dialog EasyPermissions.requestPermissions( this, "This app needs to access your Google account (via Contacts).", REQUEST_PERMISSION_GET_ACCOUNTS, Manifest.permission.GET_ACCOUNTS); } } @Override public void onConnected(Bundle connectionHint) { Log.i(TAG, "API client connected."); } @Override public void onConnectionSuspended(int cause) { Log.i(TAG, "GoogleApiClient connection suspended"); } private boolean isDeviceOnline() { ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); return (networkInfo != null && networkInfo.isConnected()); } private boolean isGooglePlayServicesAvailable() { GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance(); final int connectionStatusCode = apiAvailability.isGooglePlayServicesAvailable(this); return connectionStatusCode == ConnectionResult.SUCCESS; } private void acquireGooglePlayServices() { GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance(); final int connectionStatusCode = apiAvailability.isGooglePlayServicesAvailable(this); if (apiAvailability.isUserResolvableError(connectionStatusCode)) { } } public String AddFile(String fileName, String filePath) { String id = ""; HttpTransport transport = AndroidHttp.newCompatibleTransport(); JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); mService = new com.google.api.services.drive.Drive.Builder( transport, jsonFactory, mCredential) .setApplicationName("Crucial Conversation App") .build(); System.out.println("File Name : " + fileName); System.out.println("File Path : " + filePath); try { com.google.api.services.drive.model.File fileMetadata = new com.google.api.services.drive.model.File(); fileMetadata.setName(fileName); EXISTING_FOLDER_ID = pref.getString("EXISTING_FOLDER_ID", ""); fileMetadata.setParents(Collections.singletonList(EXISTING_FOLDER_ID)); java.io.File audioFilePath = new java.io.File(filePath); FileContent mediaContent = new FileContent("audio/amr", audioFilePath); com.google.api.services.drive.model.File file = mService.files().create(fileMetadata, mediaContent) .setFields("id, parents") .execute(); id = file.getId(); System.out.println("File ID: " + id); } catch (Exception e) { System.out.println("Error -------->" + e.getMessage()); } return id; } private class AddFileTask extends AsyncTask<Void, Void, String> { String FILE_NAME = ""; AddFileTask(GoogleAccountCredential credential, String fileName) { HttpTransport transport = AndroidHttp.newCompatibleTransport(); JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); mService = new com.google.api.services.drive.Drive.Builder( transport, jsonFactory, credential) .setApplicationName("Drive API Android Quickstart") .build(); FILE_NAME = fileName; } @Override protected String doInBackground(Void... params) { try { FILEPATH = "/storage/emulated/0/CallRecorder/" + FILE_NAME; return AddFile(FILE_NAME, FILEPATH); } catch (Exception e) { cancel(true); return null; } } @Override protected void onPreExecute() { } @Override protected void onPostExecute(String output) { updateRecord(output); } } private void updateRecord(String id) { callRecordUpdate = callRecordAdapter.getItem(rowIndex); realm.beginTransaction(); callRecordUpdate.setFileId(id); callRecordUpdate.setStorage("Cloud"); realm.copyToRealmOrUpdate(callRecordUpdate); realm.commitTransaction(); if (callRecordAdapter.getItemCount() == 0) { Toast.makeText(getApplicationContext(), "Sync Completed Successfully", Toast.LENGTH_SHORT).show(); String dir = pref.getString("FOLDER_PATH",""); System.out.println("--------->"+ dir); File fileList = new File( dir ); if (fileList != null) { File[] filenames = fileList.listFiles(); for (File tmpf : filenames) { tmpf.delete(); } } rowIndex = 0; } } @Override public IBinder onBind(Intent arg0) { Log.i(TAG, "Service onBind"); return null; } }
package com.dev.service; import com.dev.model.User; import com.dev.repository.UserRepository; import org.apache.log4j.Logger; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; /** * @author OlgaPrylypko * date: 30.12.2015 */ @Service public class InitDbService { private static final Logger LOG = Logger.getLogger(InitDbService.class); @Autowired private UserRepository userRepository; @PostConstruct public void init() { LOG.info("init db"); if (userRepository.findByFirstNameAndLastName("Tom", "Jonson") == null) { LOG.info("add user Tom Jonson"); User user = new User(); user.setFirstName("Tom"); user.setLastName("Jonson"); user.setCreatedDate(new DateTime(2015, 12, 6, 0, 0)); user.setHomeAddress("London"); userRepository.save(user); } if (userRepository.findByFirstNameAndLastName("Kate", "Mayson") == null) { LOG.info("add user Kate Mayson"); User user = new User(); user.setFirstName("Kate"); user.setLastName("Mayson"); user.setCreatedDate(new DateTime(2015, 12, 7, 0, 0)); user.setHomeAddress("New York"); userRepository.save(user); } } }
package com.mibo.modules.data.model; import com.mibo.modules.data.base.BaseAppVersion; @SuppressWarnings("serial") public class AppVersion extends BaseAppVersion<AppVersion> { /* 10 */ public static final AppVersion dao = (AppVersion) new AppVersion().dao(); public AppVersion queryAppVersionByTypeVersionNo(String appType, int version) { /* 19 */ String sql = "SELECT app_mark,is_forcibly,content,app_package,update_date FROM t_app_version WHERE del_flag = '0' AND is_publish = '1' AND app_type = ? AND app_mark > ? "; /* 23 */ return (AppVersion) findFirst(sql, new Object[] { appType, Integer.valueOf(version) }); } }
package com.letscrawl.base.bean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class AbstractObject { public final Logger logger = LoggerFactory.getLogger(this.getClass()); }
package by.htp.carparking.web.controller.admin; import java.applet.AppletContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; //import org.json.simple.JSONObject; //import org.json.simple.parser.JSONParser; //import org.json.simple.parser.ParseException; //import org.json.simple.JSONObject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import by.htp.carparking.service.impl.CarServiceImpl; @Controller @RequestMapping(value = "/admin") public class AdminMainController { @Autowired private CarServiceImpl carServiceImpl; @RequestMapping(value="/") public String mainPage() { // return "{\"name\" : \"John\"}"; //ApplicationContext context = //getBean(); carServiceImpl.getCarsList(); return "admin_main"; } @RequestMapping(value="/json") public @ResponseBody String mainPageJson() { return "{\"name\" : \"John\"}"; // JSONObject json = new JSONObject(); // json.put("name", "John"); // return json.toJSONString(); } @RequestMapping(value="/json2") public @ResponseBody String mainPageJson2(@RequestParam String login){ // JSONParser parser=new JSONParser(); // JSONObject jsonObj=(JSONObject) parser.parse(login); // String log=(String) jsonObj.get("login"); return "{\"key\" : \"good login\"}"; } }
import java.io.*; import java.lang.*; import java.util.*; // #!/usr/bin/python -O // #include <stdio.h> // #include <stdlib.h> // #include <string.h> // #include<stdbool.h> // #include<limits.h> // #include<iostream> // #include<algorithm> // #include<string> // #include<vector> //using namespace std; /* # Author : @RAJ009F # Topic or Type : GFG/LinkedList # Problem Statement : Merge Sort # Description : # Complexity : ======================= #sample output ---------------------- ======================= */ class Node { int data; Node next; Node(int data) { this.data = data; } } class AddTwoLists { Node head; public Node addLists(Node a, Node b) { int carry = 0; Node res = null; Node cur = res; while(a !=null || b!=null) { int data = ((a!=null)?a.data:0) + ((b!=null) ? b.data:0); data +=carry; carry = data/10; data = data%10; Node node = new Node(data); if(res ==null) { res = node; cur = res; }else { cur.next = node; cur = cur.next; } if(a !=null) a = a.next; if(b != null) b = b.next; } return res; } public void printList(Node list) { while(list !=null) { System.out.print(list.data+" "); list = list.next; } } public static void main(String args[]) { AddTwoLists l1 = new AddTwoLists(); l1.head = new Node(5); l1.head.next = new Node(6); l1.head.next.next = new Node(3); AddTwoLists l2 = new AddTwoLists(); l2.head = new Node(8); l2.head.next = new Node(4); l2.head.next.next = new Node(2); AddTwoLists res = new AddTwoLists(); res.head = res.addLists(l1.head, l2.head); l1.printList(l1.head); System.out.println(); l2.printList(l2.head); System.out.println(); res.printList(res.head); l1.head = new Node(7); l1.head.next = new Node(5); l1.head.next.next = new Node(9); l1.head.next.next.next = new Node(4); l1.head.next.next.next.next = new Node(6); l1.printList(l1.head); System.out.println(); l2.head = new Node(8); l2.head.next = new Node(4); l2.printList(l2.head); System.out.println(); res.head = res.addLists(l1.head, l2.head); res.printList(res.head); } }
package mtuci.nikitakutselay.mobileapplicationprogrammingcourse; import android.app.ListActivity; import android.app.ProgressDialog; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.os.AsyncTask; import android.os.Bundle; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class ApplicationListActivity extends ListActivity { private List<ApplicationInfo> applicationList = null; private PackageManager packageManager = null; private ArrayAdapter<String> applicationListAdapter = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_application_list); ListView listView = findViewById(android.R.id.list); registerForContextMenu(listView); packageManager = getPackageManager(); new LoadApplicationList().execute(); } @Override public void onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { if (v.getId() == android.R.id.list) { menu.add(0, ApplicationListMenuItem.COPY_APPLICATION_NAME, 0, getText(R.string.copy_application_name_menu_item) ); menu.add(0, ApplicationListMenuItem.COPY_PACKAGE_NAME, 0, getText(R.string.copy_application_package_menu_item) ); menu.add(0, ApplicationListMenuItem.SHOW_APPLICATION_INFO, 0, getText(R.string.show_application_info_menu_item) ); } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo(); ApplicationInfo info = null; switch (item.getItemId()) { case ApplicationListMenuItem.COPY_APPLICATION_NAME: info = applicationList.get(menuInfo.position); notifyAboutCopying(info.loadLabel(packageManager).toString()); return true; case ApplicationListMenuItem.COPY_PACKAGE_NAME: info = applicationList.get(menuInfo.position); notifyAboutCopying(info.packageName); return true; case ApplicationListMenuItem.SHOW_APPLICATION_INFO: return true; default: return super.onContextItemSelected(item); } } private void notifyAboutCopying(String data) { String notification = String.format("%s: %s", getString(R.string.copying_notification), data); Toast toast = Toast.makeText(getApplicationContext(), notification, Toast.LENGTH_SHORT); toast.show(); } private class LoadApplicationList extends AsyncTask<Void, Void, Void> { private ProgressDialog progress = null; @Override protected Void doInBackground(Void... params) { applicationList = packageManager.getInstalledApplications(PackageManager.GET_META_DATA); List<String> applicationNames = new ArrayList<>(); for (ApplicationInfo info : applicationList) { applicationNames.add(info.loadLabel(packageManager).toString()); } applicationListAdapter = new ArrayAdapter<String>(ApplicationListActivity.this, android.R.layout.simple_list_item_1, applicationNames); return null; } @Override protected void onPostExecute(Void result) { setListAdapter(applicationListAdapter); progress.dismiss(); super.onPostExecute(result); } @Override protected void onPreExecute() { progress = ProgressDialog.show(ApplicationListActivity.this, null, getString(R.string.application_list_loading)); super.onPreExecute(); } } }
package org.giddap.dreamfactory.leetcode.onlinejudge; /** * http://oj.leetcode.com/problems/largest-rectangle-in-histogram/ * <p/> * Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find * the area of largest rectangle in the histogram. * <p/> * Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]. * <p/> * The largest rectangle is shown in the shaded area, which has area = 10 unit. * <p/> * For example, * Given height = [2,1,5,6,2,3], * return 10. * <p/> * Links: * http://www.geeksforgeeks.org/largest-rectangle-under-histogram/ * http://www.geeksforgeeks.org/largest-rectangular-area-in-a-histogram-set-1/ * http://www.informatik.uni-ulm.de/acm/Locals/2003/html/judge.html */ public interface LargestRectangleInHistogram { int largestRectangleArea(int[] height); }
package com.comunisolve.androidmvvmachitecturecomponents.Room; import android.app.Application; import android.os.AsyncTask; import androidx.lifecycle.LiveData; import java.util.List; // Repository is just a werehouse of our data that is fetch from room Database or from RESTFULL APIs Services, VIEWMODEL doesn't know where the data comes from? it just access from ViewModel public class NoteRepository { private NoteDao noteDao; private LiveData<List<Note>> allNotes; //construcor to intialize these values public NoteRepository(Application application) { //application is subpart of context NoteDatabase database = NoteDatabase.getInstance(application); noteDao = database.noteDao(); // return instance of our db allNotes = noteDao.getAllNotes(); } /* these four methods run of main thread, Room doesn't allow us to run on Main Thread. It will freee our app. To avoid this. we will create different Asynctask for each Method. */ public void insert(Note note) { new InserNoteAsyncTask(noteDao).execute(note); } public void update(Note note) { new UpdateNoteAsyncTask(noteDao).execute(note); } public void delete(Note note) { new DeleteNoteAsyncTask(noteDao).execute(note); } public void deleteAllNotes() { new DeleteAllNotesAsyncTask(noteDao).execute(); } public LiveData<List<Note>> getAllNotes() { //LiveData always run on Background Thread return allNotes; } private static class InserNoteAsyncTask extends AsyncTask<Note, Void, Void> { private NoteDao noteDao; private InserNoteAsyncTask(NoteDao noteDao) { this.noteDao = noteDao; } @Override protected Void doInBackground(Note... notes) { noteDao.insert(notes[0]); return null; } } private static class UpdateNoteAsyncTask extends AsyncTask<Note, Void, Void> { private NoteDao noteDao; private UpdateNoteAsyncTask(NoteDao noteDao) { this.noteDao = noteDao; } @Override protected Void doInBackground(Note... notes) { noteDao.update(notes[0]); return null; } } private static class DeleteNoteAsyncTask extends AsyncTask<Note, Void, Void> { private NoteDao noteDao; private DeleteNoteAsyncTask(NoteDao noteDao) { this.noteDao = noteDao; } @Override protected Void doInBackground(Note... notes) { noteDao.delete(notes[0]); return null; } } private static class DeleteAllNotesAsyncTask extends AsyncTask<Void, Void, Void> { private NoteDao noteDao; private DeleteAllNotesAsyncTask(NoteDao noteDao) { this.noteDao = noteDao; } @Override protected Void doInBackground(Void... voids) { noteDao.deleteAllNotes(); return null; } } }
package com.rabo.customerstatementprocessor.controller; import static com.rabo.customerstatementprocessor.constant.MessageCodeConstants.IO_EXCEPTION_WHEN_READING_INPUT_STREAM_CODE; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.rabo.customerstatementprocessor.config.RaboMessageResolver; import com.rabo.customerstatementprocessor.exception.RaboSystemException; import com.rabo.customerstatementprocessor.model.ErrorResponse; import com.rabo.customerstatementprocessor.model.StatementValidationResponse; import com.rabo.customerstatementprocessor.model.TransactionRecordFailure; import com.rabo.customerstatementprocessor.service.validation.TransactionIOBasedValidationService; import com.rabo.customerstatementprocessor.util.MimeTypeUtils; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; /** * This class is the controller that has the REST API endpoints for validating * customer statement records. * * @author rutvijr@gmail.com * */ @RestController public class TransactionValidationController { private final RaboMessageResolver messageResolver; private final TransactionIOBasedValidationService ioBasedValidationService; public TransactionValidationController(RaboMessageResolver messageResolver, TransactionIOBasedValidationService ioBasedValidationService) { this.messageResolver = messageResolver; this.ioBasedValidationService = ioBasedValidationService; } /** * It validates the customer transaction statement records in the given * MultipartFile. * * Currently supported file types are CSV and XML. * * @param file * @return */ @ApiResponses({@ApiResponse(code = 400, message = "Bad Request", response = ErrorResponse.class), @ApiResponse(code = 500, message = "Internal Server Error", response = ErrorResponse.class)}) @PostMapping("/validate") public StatementValidationResponse validate(@RequestPart MultipartFile file) { try (InputStream inputStream = file.getInputStream()) { String fileType = MimeTypeUtils.getSubTypeOf(file.getContentType()); List<TransactionRecordFailure> failures = ioBasedValidationService.validate(inputStream, fileType); return new StatementValidationResponse(failures); } catch (IOException exception) { String message = messageResolver.getMessage(IO_EXCEPTION_WHEN_READING_INPUT_STREAM_CODE); throw new RaboSystemException(IO_EXCEPTION_WHEN_READING_INPUT_STREAM_CODE, message, exception); } } }
package com.hwj.config; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer; @Configuration public class RedisConfig { @Bean public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); // 设置value的序列化规则和 key的序列化规则 redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new StringRedisSerializer()); redisTemplate.afterPropertiesSet(); return redisTemplate; } }
package OnlinemusicstoreClasses; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.stage.Stage; import java.io.IOException; public class LogInController { @FXML TextField UserName; @FXML Button Signin; @FXML TextField PassWord; DatabaseManager db = DatabaseManager.getInstance(); public void signInAction(javafx.event.ActionEvent event){ boolean password=db.passwordCheck(UserName.getText().trim() , PassWord.getText().trim()); //Get a boolean from the DB to check if password is correct for the username if (UserName.getText().trim().isEmpty() || PassWord.getText().trim().isEmpty()){ return; } if (password==true){ //if it is, go to main menu and save the current users data in a singleton class db.updateCurrentUser(UserName.getText().trim()); LogInController l=new LogInController(); l.changeToMainMenu(event); } else if (password==false){ //else we show an error message Alert wrongPasswordAlert = new Alert(Alert.AlertType.ERROR, "Wrong username or password"); wrongPasswordAlert.show(); PassWord.clear(); } } @FXML public void changeToCreateNewUser(javafx.event.ActionEvent event){ try { Node node = (Node) event.getSource(); Stage stage = (Stage) node.getScene().getWindow(); FXMLLoader loader = new FXMLLoader(getClass().getResource("../OnlinemusicstoreFxml/sampleTwo.fxml")); Parent root = loader.load(); Scene scene = new Scene(root); stage.setScene(scene); } catch (NullPointerException ne){ ne.getSuppressed(); } catch (IOException e) { e.printStackTrace(); } } @FXML public void changeToMainMenu(ActionEvent event){ try { Node node = (Node) event.getSource(); Stage stage = (Stage) node.getScene().getWindow(); FXMLLoader loader = new FXMLLoader(getClass().getResource("../OnlinemusicstoreFxml/mainMenu.fxml")); Parent root = loader.load(); Scene scene = new Scene(root); stage.setScene(scene); } catch (Exception e){ e.printStackTrace(); } } @FXML public void changeToLostPassword(ActionEvent event){ try { Node node = (Node) event.getSource(); Stage stage = (Stage) node.getScene().getWindow(); FXMLLoader loader = new FXMLLoader(getClass().getResource("../OnlinemusicstoreFxml/LostPasswordScene.fxml")); Parent root = loader.load(); Scene scene = new Scene(root); stage.setScene(scene); } catch (Exception e){ e.printStackTrace(); } } @FXML public void onEnter(ActionEvent ae){ signInAction(ae); } @FXML void helpMenuPressed(ActionEvent event) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Login"); alert.setHeaderText("Information about the login screen. "); alert.setContentText("If you don't already have an account you can create one by pressing the \"Sign up\" button." + "This is necessary for logging in. If you can't remember your password you can get a new one by pressing the " + "\"Forgot password\" button and then follow the instructions. "); alert.showAndWait(); } }
package org.shujito.cartonbox.view.listener; public interface TagListItemSelectedCallback { public void tagListItemSelected(String tag); }
package com.virtusa.sai.control; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.simple.SimpleJdbcCall; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import com.virtusa.sai.dao.UserRegistration; import com.virtusa.sai.jdbc.UserRegistrationJDBC; //WeatherUserRegistration is a Controller @Controller public class WeatherUserRegistration { private static final Logger LOGGER = LoggerFactory.getLogger(WeatherUserRegistration.class); // Logging for WeatherUserRegistration class. @Autowired private DataSource datasource; // Datasource used is Hikari Connection Pool. @Autowired JdbcTemplate jdbctemplate; // Use to perform operations on Database(MySQL). @GetMapping("/weatherreg")//URL pattern for getting values from Registration page public String GetRegister(Model model,HttpServletRequest request) { HttpSession session=request.getSession(); LOGGER.trace("Entering Method GetRegister"); LOGGER.debug("Enter your Details to create an account"); UserRegistration user =new UserRegistration(); model.addAttribute("user", user); session.setAttribute("user", user); return "WeatherRegister"; } @PostMapping("/weatherreg")//URL pattern for inserting the new user details in database. public String PostRegister(@ModelAttribute("user") UserRegistration user,Model model,HttpServletRequest request) { HttpSession session=request.getSession(); LOGGER.trace("Entering Method PostRegister"); LOGGER.debug("Register as new user"); try { // Stored Procedure to insert a new user details in Database. SimpleJdbcCall simpleJdbcCall = new SimpleJdbcCall(jdbctemplate) .withProcedureName("UserReg"); Map<String, Object> inParamMap = new HashMap<String, Object>(); inParamMap.put("emailid", user.getEmail()); inParamMap.put("fname", user.getFirstname()); inParamMap.put("lname", user.getLastname()); inParamMap.put("phone", user.getMobile()); inParamMap.put("pass", user.getPassword()); inParamMap.put("country", user.getCountry()); inParamMap.put("response", "@response"); System.out.println(user.getPassword()); SqlParameterSource in = new MapSqlParameterSource(inParamMap); Map<String, Object> simpleJdbcCallResult = simpleJdbcCall.execute(in); System.out.println(simpleJdbcCallResult.get("response")); model.addAttribute("response",simpleJdbcCallResult.get("response")); session.setAttribute("response",simpleJdbcCallResult.get("response")); System.out.println("DataSource:"+datasource); LOGGER.info("Response Created for Registration"); } catch(Exception e) { LOGGER.error("Registration Failed"); model.addAttribute("response","Failed"); session.setAttribute("response","Failed"); return "WeatherRegister"; } return "WeatherRegister"; } }
package com.algorithm.tree; import java.util.List; /** * #894 所有可能的满二叉树 */ public class AllPossibleFBT { public List<TreeNode> allPossibleFBT(int N) { //如果n>=3 return null; } }
package org.kevin.model; import lombok.Getter; import lombok.Setter; import lombok.ToString; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * @author kevin * @ClassName * @Date 2020/1/1819:06 */ @Getter @Setter @ToString @Entity public class Employee { @Id @GeneratedValue private Long id; private String name; }
package models; public class Balcony extends Seat { public Balcony(int number, int row) { super(number, row); visibility = 2; price = 100; type = "Balcony"; } public Balcony(int number, int row, String type){ super(number, row); visibility = 2; this.type = type; } public Balcony() { visibility = 2; price = 100; } @Override void setType(){ type = "Balcony"; } @Override public double getPrice() { return 100; } @Override public String toString() { return (super.toString() + " Balcony seat"); } }
package demoOn20August2016_JDBC; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; public class Twotables { Connection conn; PreparedStatement pst; ResultSet rs; int Result; public static void main(String[] args) { } }
package com.dq.police.controller.actions.CrimePast; import com.dq.police.controller.Action; import com.dq.police.helpers.ConstraintsUtil; import com.dq.police.model.PersistenceManager; import com.dq.police.model.entities.Cop; import com.dq.police.model.entities.CrimePast; import com.dq.police.view.View; import lombok.AllArgsConstructor; import java.util.List; @AllArgsConstructor public class FindCrimePastAction extends Action { private PersistenceManager persistence; private View view; @Override public String execute() { String id = view.getPropertyCancellable("identifier"); String val = view.getPropertyCancellable("identifier value"); List<String> results; try { results = persistence.find(id, Integer.valueOf(val), CrimePast.class); } catch (NumberFormatException e) { results = persistence.find(id, val, CrimePast.class); } view.showGroup("Crime Past", results); return ConstraintsUtil.OPERATION_SUCCESS_MESSAGE; } @Override public String getName() { return "Find Crime Past"; } }
package com.jyn.language.设计模式.三种工厂.抽象工厂; /** * 椰果奶茶 加冰 */ public class CocoIceTea extends CocoTea { public CocoIceTea(String name, String price) { super(name, price); } }
package com.example.tyzzer.android_projectweek1_googlebooks; import android.os.Parcel; import android.os.Parcelable; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class Book implements Parcelable { private String id, title, author, imageUrl, review; private int read; private boolean selected; public Book(String title, String author, String imageUrl, String review, int read) { this.title = title; this.author = author; this.imageUrl = imageUrl; this.review = review; this.read = read; } public Book(JSONObject jsonObject) { try { this.id = jsonObject.getString("id"); } catch (JSONException e) { e.printStackTrace(); } try { JSONObject json = jsonObject.getJSONObject("volumeInfo"); try { this.title = json.getString("title"); } catch (JSONException e) { e.printStackTrace(); } try { JSONArray authorsJsonArray = json.getJSONArray("authors"); this.author = parseAuthors(authorsJsonArray); } catch (JSONException e) { e.printStackTrace(); this.author = ""; } try { JSONObject links = json.getJSONObject("imageLinks"); this.imageUrl = links.getString("smallThumbnail"); } catch (JSONException e) { e.printStackTrace(); } } catch (JSONException e) { e.printStackTrace(); } this.review = ""; this.selected = false; this.read = 0; } private static String parseAuthors(JSONArray authorsAry) { StringBuilder authorsString = new StringBuilder(); for (int i = 0; i < authorsAry.length(); i++) { try { if (i == 0) { authorsString.append(authorsAry.getString(i)); } else { authorsString.append(" - ").append(authorsAry.getString(i)); } } catch (JSONException e) { e.printStackTrace(); } } return authorsString.toString(); } protected Book(Parcel in) { title = in.readString(); author = in.readString(); review = in.readString(); imageUrl = in.readString(); read = in.readInt(); selected = in.readByte() != 0; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(title); dest.writeString(author); dest.writeString(review); dest.writeString(imageUrl); dest.writeInt(read); dest.writeByte((byte)(selected ? 1 : 0)); } public static final Creator<Book> CREATOR = new Creator<Book>() { @Override public Book createFromParcel(Parcel in) { return new Book(in); } @Override public Book[] newArray(int size) { return new Book[size]; } }; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getReview() { return review; } public void setReview(String review) { this.review = review; } public int isRead() { return read; } public void setRead(int read) { this.read = read; } public boolean isSelected() { return selected; } public void setSelected(boolean selected) { this.selected = selected; } }
package com.javarush.task.task20.task2022; import java.io.*; /* Переопределение сериализации в потоке */ public class Solution implements Serializable, AutoCloseable { private transient FileOutputStream stream; String fileName; public Solution(String fileName) throws FileNotFoundException { this.stream = new FileOutputStream(fileName); this.fileName = fileName; } public void writeObject(String string) throws IOException { stream.write(string.getBytes()); stream.write("\n".getBytes()); stream.flush(); } private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); stream = new FileOutputStream(fileName, true); writeObject("yo"); } @Override public void close() throws Exception { System.out.println("Closing everything!"); stream.close(); } public static void main(String[] args) throws IOException, ClassNotFoundException { Solution solution = new Solution("C:\\Users\\Igor\\Desktop\\test1.txt"); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(byteArrayOutputStream); out.writeObject(solution); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); ObjectInputStream in = new ObjectInputStream(byteArrayInputStream); Solution solution1 = (Solution)in.readObject(); System.out.println(solution1.stream); } }
package com.hrm.controller; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.hrm.domain.Dept; import com.hrm.domain.Employee; import com.hrm.domain.Job; import com.hrm.domain.Salary; import com.hrm.domain.Pages; import com.hrm.domain.Salary; import com.hrm.domain.User; import com.hrm.service.DeptService; import com.hrm.service.JobService; import com.hrm.service.SalaryService; import com.hrm.service.SalaryService; /*处理用户请求控制器*/ @Controller public class SalaryController { /*自动注入SalaryService*/ @Autowired @Qualifier("salaryService") SalaryService salaryService; @Autowired @Qualifier("deptService") DeptService deptService; @Autowired @Qualifier("jobService") JobService jobService; //动态查询 @RequestMapping("main/selectSalary") public String selectSalary(Integer job_id,Integer dept_id,Dept dept,Job job,Salary salary,Model model,Integer pageNow){ this.genericAssciation(job_id, dept_id, salary); Map params=new HashMap(); if(pageNow==null) pageNow=1; params.put("salary",salary); params.put("pageSize",pageSize); params.put("pageNow",pageNow); int totalSize=salaryService.countList(); Pages page=new Pages(pageNow,pageSize,totalSize); System.out.println(pageNow+""+pageSize+""+totalSize); List<Salary> list=salaryService.countSalary(params); model.addAttribute("salaryList",list); List<Dept> list2=deptService.selectDept(dept); model.addAttribute("deptList",list2); List<Job> list3=jobService.selectJob(job); model.addAttribute("jobList",list3); model.addAttribute("page",page); System.out.println("selectSalary"); return "salary/lookSalaryself"; } int pageSize=3; //动态查询 @RequestMapping("main/selectSalary2") public String countSalary(Integer job_id,Integer dept_id,Dept dept,Job job,Salary salary,Model model,Integer pageNow){ this.genericAssciation(job_id, dept_id, salary); Map params=new HashMap(); if(pageNow==null) pageNow=1; params.put("salary",salary); params.put("pageSize",pageSize); params.put("pageNow",pageNow); int totalSize=salaryService.countList(); Pages page=new Pages(pageNow,pageSize,totalSize); System.out.println(pageNow+""+pageSize+""+totalSize); List<Salary> list=salaryService.countSalary(params); model.addAttribute("salaryList",list); List<Dept> list2=deptService.selectDept(dept); model.addAttribute("deptList",list2); List<Job> list3=jobService.selectJob(job); model.addAttribute("jobList",list3); model.addAttribute("page",page); System.out.println("selectSalary"); return "salary/lookSalary"; } //插入 @RequestMapping("main/insertSalaryView") public String insertSalaryView(Integer job_id,Integer dept_id,Salary salary,Model model){ this.genericAssciation(job_id, dept_id, salary); List<Salary> list=salaryService.selectSalary(salary); model.addAttribute("salaryList",list); List<Dept> list2=deptService.findAllDept(); model.addAttribute("deptList",list2); List<Job> list3=jobService.findAllJob(); model.addAttribute("jobList",list3); return "salary/addSalary"; } @RequestMapping("salary/insertSalary") public String insertSalary(Integer job_id,Integer dept_id,Dept dept,Job job,Salary salary,Model model,User user){ this.genericAssciation(job_id, dept_id, salary); System.out.println("123456789"); salaryService.insertSalary(salary); System.out.println("123456"); return "redirect:../main/selectSalary2"; } //删除 @RequestMapping("/deleteSalary") public String deleteSalary(int id){ salaryService.deleteById(id); return "redirect:main/selectSalary2"; } //修改 @RequestMapping("/updateSalary") public String updateSalary(Integer job_id,Integer dept_id,Dept dept,Job job,Salary salary,Model model){ this.genericAssciation(job_id, dept_id, salary); List<Dept> list2=deptService.selectDept(dept); model.addAttribute("deptList",list2); List<Job> list3=jobService.selectJob(job); model.addAttribute("jobList",list3); //根据id查询 返回页面 Salary target=salaryService.selectById(salary.getId()); model.addAttribute("salary",target); return "salary/updateSalary"; } @RequestMapping("/updateSalaryView") public String updateSalaryView(Salary salary,Integer job_id,Integer dept_id,Dept dept,Job job){ this.genericAssciation(job_id, dept_id, salary); salaryService.updateSalary(salary); return "redirect:main/selectSalary2"; } /*关联映射*/ public void genericAssciation(Integer job_id,Integer dept_id,Salary salary){ if(job_id!=null){ Job job=new Job(); job.setId(job_id); salary.setJob(job); } if(dept_id!=null){ Dept dept=new Dept(); dept.setId(dept_id); salary.setDept(dept); } } }
package org.giddap.dreamfactory.leetcode.onlinejudge.implementations; import org.giddap.dreamfactory.leetcode.commons.RandomListNode; import org.giddap.dreamfactory.leetcode.onlinejudge.CopyListWithRandomPointer; import java.util.HashMap; import java.util.Map; /** * Algorithm: * 1. Clone nodes connected by 'next' while at the same time map the cloned ones to the original ones. * 2. Build the 'random' links based on the mapping. */ public class CopyListWithRandomPointerNextFirstWithMapImpl implements CopyListWithRandomPointer { public RandomListNode copyRandomList(RandomListNode head) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if (head == null) return null; Map<RandomListNode, RandomListNode> hm = new HashMap<RandomListNode, RandomListNode>(); RandomListNode p = head; while (p != null) { RandomListNode n = new RandomListNode(p.label); hm.put(p, n); p = p.next; } p = head; while (p != null) { RandomListNode n = hm.get(p); n.next = null; n.random = null; if (p.next != null) n.next = hm.get(p.next); if (p.random != null) n.random = hm.get(p.random); p = p.next; } return hm.get(head); } }
package serve.serveup.dataholder.session; /* @author: urban.jagodic */ public interface SessionManager { // add Session info to object to Shared prefrences void addToSession(SessionContent type, Object data); // delete data from Session object from Shared prefrences void deleteFromSession(SessionContent type, Object... data); // erase whole session void eraseSession(); // get session from shared prefrences Session getSession(); }
package com.god.gl.vaccination.util; import android.text.TextUtils; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; import java.util.ArrayList; import java.util.List; /** * @author gl * @date 2018/5/22 * @desc Gson工具 */ public class GsonUtil { public static <T> T jsonToBean(String json, Class<T> clazz) { Gson gson = new Gson(); return gson.fromJson(json, clazz); } public static <T> List<T> jsonArrayToList(String jsonData, Class<T> type) { Gson gson = new Gson(); JsonParser parser = new JsonParser(); JsonArray array = parser.parse(jsonData).getAsJsonArray(); ArrayList<T> lcs = new ArrayList<T>(); for (JsonElement obj : array) { T cse = gson.fromJson(obj, type); lcs.add(cse); } return lcs; } // 将Json数组解析成相应的映射对象列表 public static <T> List<T> parseJsonArrayToList(String jsonData, Class<T> type) { ArrayList<T> result = new ArrayList<>(); if (TextUtils.isEmpty(jsonData)) { jsonData = "[]"; } try { Gson gson = new Gson(); JsonParser parser = new JsonParser(); JsonArray jArray = parser.parse(jsonData).getAsJsonArray(); for (JsonElement obj : jArray) { T cse = gson.fromJson(obj, type); result.add(cse); } } catch (JsonSyntaxException e) { e.printStackTrace(); } return result; } //将列表数据转成json public static <T> String convertListToJson(List<T> datalist) { Gson gson = new Gson(); //转换成json数据,再保存 String strJson = gson.toJson(datalist); return strJson; } }
package sources; public class StepSizeValues { static int[] stepSizeValues = { 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408 }; public static int getStepSizeValueFrom(int index) { int maxIndex = stepSizeValues.length - 1; if (index > maxIndex){ return stepSizeValues[maxIndex]; } else if (index < 0) { return stepSizeValues[0]; } else { return stepSizeValues[index]; } } public static int calcuateStepSizeValueFor(ADPCMFrame adpcmFrame, int previousStepSize) { String adpcmValue = adpcmFrame.getValue(); int index = 0; int indexChange = 0; if (adpcmValue.equals("1111") || adpcmValue.equals("0111")) { indexChange = 8; } else if (adpcmValue.equals("1110") || adpcmValue.equals("0110")) { indexChange = 4; } else if (adpcmValue.equals("1101") || adpcmValue.equals("0101")) { indexChange = 2; } else if (adpcmValue.equals("1100") || adpcmValue.equals("0100")) { indexChange = 1; } else if (adpcmValue.equals("1011") || adpcmValue.equals("0011")) { indexChange = -1; } else if (adpcmValue.equals("1010") || adpcmValue.equals("0010")) { indexChange = -1; } else if (adpcmValue.equals("1001") || adpcmValue.equals("0001")) { indexChange = -1; } else if (adpcmValue.equals("1000") || adpcmValue.equals("0000")) { indexChange = -1; }; index = getIndexFromStepSizeTable(previousStepSize) + indexChange; return getStepSizeValueFrom(index); } public static int getIndexFromStepSizeTable(int stepSize) { int index = 0; for (int searchedIndex = 0; searchedIndex < stepSizeValues.length-1 ; searchedIndex++) { if (stepSizeValues[searchedIndex] == stepSize){ index = searchedIndex; } } return index; } }
public class Refrigerator extends Appliance { private static int defaultElectricityUse = 1; private static int defaultGasUse = 0; private static int defaultWaterUse = 0; public Refrigerator(int electricityUse, int gasUse, int waterUse, int timeOn, House myhouse) { super(electricityUse > 0 ? electricityUse : defaultElectricityUse, gasUse > 0 ? gasUse : defaultGasUse, waterUse > 0 ? waterUse : defaultWaterUse, timeOn = -1, myhouse); /** * It must have a name event if it is never used. * Otherwise it is not possible to assign an appliance to a task. */ taskName = "Refrigerate!"; } protected void setMeter(House myhouse) { this.electricMeter = myhouse.getElectricMeter(); } /** * as this appliance is always on, the use method will not do anything. * still i had to overide it because it is abstract in Appliance.java class. */ }
package com.mike.blog.repository; import com.mike.blog.modal.Blog; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.Optional; /** * This is the repository for blog * * @author Michael Ng * */ @Repository public interface BlogRepository extends JpaRepository<Blog, Long> { Optional<Blog> findBlogById(long id); void deleteById(Long aLong); }
package org.garret.perst.fulltext; import java.io.Reader; /** * Implementation of string reader for J2ME */ public class StringReader extends Reader { public void close() { str = null; } public int read() { return (currPos < str.length()) ? str.charAt(currPos++) : -1; } public int read(char[] cbuf, int off, int len) { int rest = str.length() - currPos; if (rest <= 0) { return -1; } if (len > rest) { len = rest; } str.getChars(currPos, currPos + len, cbuf, 0); currPos += len; return len; } public long skip(long n) { return currPos += n; } public StringReader(String str) { this.str = str; } int currPos; String str; };
package com.kaka.blog.service; import com.kaka.blog.dao.TypeRepository; import com.kaka.blog.po.Type; import com.kaka.blog.web.ClassNotFoundException; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * @author Kaka */ @Service public class TypeServiceImpl implements TypeService { @Autowired TypeRepository typeRepository; @Transactional @Override public Type saveType(Type type) { return typeRepository.save(type); } @Transactional @Override public Type getTypeName(String typeName) { return typeRepository.findTypeByTypeName(typeName); } @Transactional @Override public Type getType(Long id) { return typeRepository.getOne(id); } @Override public List<Type> listType() { return typeRepository.findAll(); } @Transactional @Override public Type updateType(Long id, Type type) { Type typeTarget = typeRepository.findById(id).orElse(null); if (typeTarget == null) { throw new ClassNotFoundException("找不到type"); } BeanUtils.copyProperties(type, typeTarget); return typeRepository.save(typeTarget); } @Override public Page<Type> typeList(Pageable pageable) { return typeRepository.findAll(pageable); } @Transactional @Override public void deleteType(Long id) { typeRepository.deleteById(id); } }
/******************************************************************************* * Copyright (c) 2012 itemis AG (http://www.itemis.eu) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ package org.xtext.builddsl; import org.eclipse.xtext.service.SingletonBinding; import org.eclipse.xtext.xbase.scoping.featurecalls.StaticImplicitMethodsFeatureForTypeProvider; import org.eclipse.xtext.xbase.scoping.featurecalls.StaticImplicitMethodsFeatureForTypeProvider.ExtensionClassNameProvider; import org.xtext.builddsl.scoping.AllImportsAreStaticFeatureProvider; import org.xtext.builddsl.scoping.BuildDSLExtensionClassNameProvider; import org.xtext.builddsl.validation.BuildDSLValidator; /** * Use this class to register components to be used at runtime / without the Equinox extension registry. */ public class BuildDSLRuntimeModule extends org.xtext.builddsl.AbstractBuildDSLRuntimeModule { @SingletonBinding(eager = true) public Class<? extends BuildDSLValidator> bindValidator() { return BuildDSLValidator.class; } public Class<? extends ExtensionClassNameProvider> bindExtensionClassNameProvider() { return BuildDSLExtensionClassNameProvider.class; } public Class<? extends StaticImplicitMethodsFeatureForTypeProvider> bindStaticImplicitMethodsFeatureForTypeProvider() { return AllImportsAreStaticFeatureProvider.class; } }
package com.esum.comp.dbc.job.log; import org.apache.ibatis.session.SqlSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.esum.comp.dbc.DbcConfig; import com.esum.comp.dbc.job.event.JobEvent; import com.esum.comp.dbc.job.event.JobInstanceEvent; import com.esum.comp.dbc.job.event.JobResult; import com.esum.comp.dbc.utils.BatchUtils; import com.esum.framework.common.util.DateUtil; import com.esum.framework.jdbc.JdbcSqlSessionFactoryManager; /** * Copyright(c) eSum Technologies., Inc. All rights reserved. */ public class JobEventLogTable { private final Logger log = LoggerFactory.getLogger(getClass()); private JobInstanceEvent instEvent; private String traceId; public JobEventLogTable(JobEvent event) { this.instEvent = (JobInstanceEvent) event; this.traceId = "[Logger][" + instEvent.getJobName() + "][" + instEvent.getInstanceId() + "] "; } public void process() { if (log.isDebugEnabled()) log.debug(traceId + "Event processing..."); if(DbcConfig.INSERT_EMPTY_LOG) { if(instEvent.getStatus() == JobEvent.ON_STARTED) { recordLogTB(JobInstanceEvent.STRD); } else if(instEvent.getStatus() == JobEvent.ON_FINISHED) { recordLogTB(instEvent.getJobResult().getStatus()); } else if(instEvent.getStatus() == JobEvent.ON_ERROR) { instEvent.getJobResult().setStatus(JobInstanceEvent.FAIL); recordLogTB(instEvent.getJobResult().getStatus()); } } else { if(instEvent.getStatus()==JobEvent.ON_STARTED) return; JobResult jobResult = instEvent.getJobResult(); if(jobResult==null) return; if(jobResult.getReadCount()==0 && jobResult.getWriteCount()==0 && jobResult.getErrorCount()==0) return; if(instEvent.getStatus() == JobEvent.ON_FINISHED) { recordLogTB(instEvent.getJobResult().getStatus()); } else if(instEvent.getStatus() == JobEvent.ON_ERROR) { instEvent.getJobResult().setStatus(JobInstanceEvent.FAIL); recordLogTB(instEvent.getJobResult().getStatus()); } } } private void recordLogTB(String status) { SqlSession session = null; try { session = JdbcSqlSessionFactoryManager.getInstance().createDefaultSqlSessionFactory().openSession(false); if (!BatchLogger.findInstanceLog(session, instEvent.getInstanceId(), instEvent.getJobName())) { BatchLogger.insertInstanceLog( session, instEvent.getString(JobInstanceEvent.CREATE_DATE), instEvent.getString(JobInstanceEvent.CREATE_TIME), instEvent.getInstanceId(), instEvent.getJobName(), instEvent.getJobType(), DbcConfig.NODE_ID, instEvent.getString(JobInstanceEvent.START_TIME), instEvent.getTime(), instEvent.getJobResult().getReadCount(), instEvent.getJobResult().getWriteCount(), instEvent.getJobResult().getErrorCount(), status, instEvent.getString(JobInstanceEvent.ERROR_CODE, ""), instEvent.getString(JobInstanceEvent.ERROR_MESSAGE, ""), instEvent.getString(JobInstanceEvent.CONVERSATION_ID, "")); } else { String startTime = instEvent.getString(JobInstanceEvent.START_TIME); String endTime = DateUtil.format("yyyyMMddHHmmss"); BatchLogger.updateInstanceLog( session, instEvent.getInstanceId(), instEvent.getJobName(), endTime, BatchUtils.calcurateElapsedTime(startTime, endTime), instEvent.getJobResult().getReadCount(), instEvent.getJobResult().getWriteCount(), instEvent.getJobResult().getErrorCount(), status, instEvent.getString(JobInstanceEvent.ERROR_CODE, ""), instEvent.getString(JobInstanceEvent.ERROR_MESSAGE, ""), instEvent.getString(JobInstanceEvent.CONVERSATION_ID, "")); } session.commit(); log.debug(traceId + "JobEvent is stored. (" + status + ")"); } catch (Throwable e) { if (session != null) { try {session.rollback();} catch (Throwable ignored){} } log.error(traceId + "JobEvent store failed.", e); } finally { if (session != null) { try { session.close(); } catch (Throwable ignored){} } session = null; } } }
/* * 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 Core; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.Paths; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Sahan */ public class Drawer { static String currentPath = System.getProperty("user.dir"); private static final String HEAD_LOCATION_IMAGE_URI = Paths.get(currentPath).toString() + "/src/images/head_locations.png"; // private static final String HEAD_LOCATION_IMAGE_URI = Paths.get(currentPath).toString() + "\\lib\\resources\\images\\head_locations.png"; private static final String EEG_SIGNAL_IMAGE_URI = Paths.get(currentPath).toString() + "/src/images/eeg_signal.png"; // private static final String EEG_SIGNAL_IMAGE_URI = Paths.get(currentPath).toString() + "\\lib\\resources\\images\\eeg_signal.png"; private String path_for_head = ""; private String path_for_signal = ""; private static final Drawer INSTANCE = new Drawer(); private Drawer(){} public static Drawer getInstance(){ return INSTANCE; } public String getEEGHeadLocationImage(){ if(!this.path_for_head.equals(EEGFile.getInstance().getFilePath())){ this.path_for_head = EEGFile.getInstance().getFilePath(); String ret, output; ProcessBuilder pb = new ProcessBuilder(PythonPathFinder.getPythonPath(), PythonScriptFinder.getHeadLocationPlotScript(), EEGFile.getInstance().getFilePath(), HEAD_LOCATION_IMAGE_URI); try { Process p = pb.start(); BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); while((ret = in.readLine()) != null){ output = ret.trim(); } } catch (IOException ex) { Logger.getLogger(Drawer.class.getName()).log(Level.SEVERE, null, ex); } } return HEAD_LOCATION_IMAGE_URI; } public String getEEGSignalImage(){ if(!this.path_for_signal.equals(EEGFile.getInstance().getFilePath())){ this.path_for_signal = EEGFile.getInstance().getFilePath(); String ret, output; ProcessBuilder pb = new ProcessBuilder(PythonPathFinder.getPythonPath(), PythonScriptFinder.getEEGSignalPlotScript(),EEGFile.getInstance().getFilePath(), EEG_SIGNAL_IMAGE_URI); try { Process p = pb.start(); BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); while((ret = in.readLine()) != null){ output = ret.trim(); } } catch (IOException ex) { Logger.getLogger(Drawer.class.getName()).log(Level.SEVERE, null, ex); } } return EEG_SIGNAL_IMAGE_URI; } }
//package com.mabang.android.activity.user; // //import android.content.Intent; //import android.graphics.Color; //import android.support.annotation.IdRes; //import android.text.TextUtils; //import android.view.View; //import android.widget.AdapterView; //import android.widget.ImageView; //import android.widget.LinearLayout; //import android.widget.ListView; //import android.widget.RadioButton; //import android.widget.RadioGroup; //import android.widget.TextView; // //import com.baidu.mapapi.map.MapView; //import com.baidu.mapapi.map.Marker; //import com.baidu.mapapi.model.LatLng; //import com.baidu.mapapi.search.geocode.GeoCodeResult; //import com.baidu.mapapi.search.geocode.GeoCoder; //import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener; //import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption; //import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult; //import com.mabang.android.R; //import com.mabang.android.activity.base.MapActivity; //import com.mabang.android.adapter.HomeAdListAdapter; //import com.mabang.android.adapter.HomeAdTypeListAdapter; //import com.mabang.android.config.Api; //import com.mabang.android.config.Constants; //import com.mabang.android.entity.vo.AddressInfo; //import com.mabang.android.entity.vo.AreaInfo; //import com.mabang.android.entity.vo.BillboardInfo; //import com.mabang.android.entity.vo.Message; //import com.mabang.android.entity.vo.SearchInfo; //import com.mabang.android.okhttp.HttpReuqest; //import com.mabang.android.utils.BDMapUtils; //import com.mabang.android.utils.DialogManager; //import com.mabang.android.utils.MapUtils; //import com.mabang.android.utils.PopupWindowManager; //import com.mabang.android.widget.DropDownAlertDialog; //import com.mabang.android.widget.HomeUserTopView; //import com.mabang.android.widget.MyEditText; // //import java.util.ArrayList; //import java.util.List; // //import walke.base.tool.NetWorkUtil; //import walke.base.widget.ImageTextView; // ///** // * Created by walke on 2018/2/3. // * email:1032458982@qq.com // * 查询请求 区号一定要传 // * ①默认进来传经纬度+(地图左上角经纬度、地图右下角经纬度 // * ②地址选择弹窗,传四级联动地址id dialogSearchRequest // * ③用户输入信息(模糊地址),传区号id, // */ // //public class UserHomeActivity2 extends MapActivity implements HomeUserTopView.HomeTopViewClickListener, RadioGroup.OnCheckedChangeListener, DropDownAlertDialog.OnDropDownAlertDialogEvent, DropDownAlertDialog.OnAlertDialogEvent { // private HomeUserTopView mTopView; // private ImageTextView itvExit, itvPreselect; // private RadioGroup mRadioGroup; // private ListView lvAds; // // private SearchInfo mSearchInfo; // private List<BillboardInfo> mBillboardInfoList; // private ImageView lvAdMenu, ivLocation; // // private DropDownAlertDialog changeAddressDialog; // // // /** // * ①默认进来传经纬度+(地图左上角经纬度、地图右下角经纬度 // */ // protected static final int SEARCH_WAY_LOCATION = 0x00; // /** // * ②地址选择弹窗,传四级联动地址id dialogSearchRequest // */ // protected static final int SEARCH_WAY_DIALOG = 0x01; // /** // * ③用户输入信息(模糊地址),传区号id, // */ // protected static final int SEARCH_WAY_INPUT = 0x02; // // // protected int last_search_way = SEARCH_WAY_LOCATION; // private AreaInfo infoProvince, infoCity, infoZone, infoStreet; // private String mInputAddress; // // private RadioButton rbCanBooking, rbMineBooked, rbMineUsing, rbUsed; // private TextView tvEmptyView; // private LinearLayout lvAdLayout; // private MyEditText etSearch; // private TextView tvCity; // /** // * 点击搜索时能否根据输入文本获取经纬度 // */ // private boolean inputTextGetLatLng; // private HomeAdListAdapter mAdapter; // private List<BillboardInfo> mTypeList; // // @Override // protected int rootLayoutId() { // return R.layout.activity_home_user; // } // // @Override // protected void initView() { // mTopView = ((HomeUserTopView) findViewById(R.id.homeUser_topView)); // mTopView.setHomeTopViewClickListener(this); // etSearch = mTopView.getEtSearch(); // tvCity = mTopView.getTvCity(); // itvExit = ((ImageTextView) findViewById(R.id.homeUser_exit)); // itvPreselect = ((ImageTextView) findViewById(R.id.homeUser_preselect)); // mRadioGroup = ((RadioGroup) findViewById(R.id.homeUser_RadioGroup)); // rbCanBooking = ((RadioButton) findViewById(R.id.home_rbCanBooking)); // rbMineBooked = ((RadioButton) findViewById(R.id.home_rbMineBooked)); // rbMineUsing = ((RadioButton) findViewById(R.id.home_rbMineUsing)); // rbUsed = ((RadioButton) findViewById(R.id.home_rbUsed)); // lvAds = ((ListView) findViewById(R.id.homeUser_lvAdPosition)); // lvAdMenu = ((ImageView) findViewById(R.id.homeUser_menu)); // ivLocation = ((ImageView) findViewById(R.id.homeUser_ivLocation)); // tvEmptyView = ((TextView) findViewById(R.id.homeUser_lvAdEmptyView)); // lvAdLayout = ((LinearLayout) findViewById(R.id.homeUser_lvAdLayout)); // // mRadioGroup.setOnCheckedChangeListener(this); // itvExit.setOnClickListener(this); // itvPreselect.setOnClickListener(this); // lvAdMenu.setOnClickListener(this); // ivLocation.setOnClickListener(this); // // lvAds.setEmptyView(tvEmptyView); // // lvAds.setOnItemClickListener(new AdapterView.OnItemClickListener() { // @Override // public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // etSearch.clearFocus(); // if (mBillboardInfoList != null && mBillboardInfoList.size() > 0) {//当mBillboardInfoList有正常的多个数据是 // if (position <= mBillboardInfoList.size() - 1) { // final BillboardInfo info = mBillboardInfoList.get(position); // LatLng latLng = getLatLng(info); // if (latLng != null) {//当被点击的有坐标 // moveToNewCenter(latLng); //// initTypeOverlay(mSearchInfo, info); // if (mTypeList == null) // initOverlay(mSearchInfo, info); // else // initTypeOverlay(mSearchInfo, mTypeList, info); // } // } // } // } // }); // // // 地图初始化 // initMapView((MapView) findViewById(R.id.homeUser_mapView)); // // } // // @Override // protected void initData() { // // etSearch.setMyFocusChangeListener(new MyEditText.MyFocusChangeListener() { // @Override // public void focusChange(View v, boolean hasFocus) { // logI("etSearch 焦点动态: hasFocus = " + hasFocus); // String etText = etSearch.getText().toString().trim(); // if (hasFocus) {//获取焦点 // // 搜索输入框里的值是定位地址时,获得焦点时直接清空,是其他地址就不清空 // if (!TextUtils.isEmpty(etText)) { // if (etText.equals(locationAddress)) { // etSearch.setText(""); // etSearch.setHint(""); // etSearch.setHint("请输入地址"); // etSearch.setHintTextColor(Color.parseColor("#cccccc")); // } else { // //光标移动到最后 // etSearch.setSelection(etText.length()); // } // } else { // etSearch.setHint(""); // etSearch.setHint("请输入地址"); // etSearch.setHintTextColor(Color.parseColor("#cccccc")); // } // } else {//失去焦点 // logI("etSearch 失去焦点动态: hasFocus = " + hasFocus); // if (TextUtils.isEmpty(etText)) { // etSearch.setHint(""); // etSearch.setHint(locationAddress); // etSearch.setHintTextColor(Color.parseColor("#000000")); // } // } // } // }); // // } // // // @Override // protected void enterFirstData(SearchInfo result) { // super.enterFirstData(result); // setSearchInfoData(result); // } // // @Override // protected void mapMarkerClick(Marker marker, final BillboardInfo markerInfo) { // etSearch.clearFocus(); // if (mTypeList == null) // initOverlay(mSearchInfo, markerInfo); // else // initTypeOverlay(mSearchInfo, mTypeList, markerInfo); // setMapCenter(marker.getPosition(), new LocateDoneListener() { // @Override // public void done() { // DialogManager.dialogBillboardInfoOneButton(UserHomeActivity2.this, markerInfo, "详情", new DialogManager.OneButtonClickListener() { // @Override // public void onClicked(BillboardInfo billboardInfo) { // Intent intent = new Intent(getApplicationContext(), AdDetailsActivity.class); // intent.putExtra(Constants.BILLBOARD_INFO, billboardInfo); // startActivity(intent); // } // }); // } // }); // // } // // @Override // public void onCityClick() { // etSearch.clearFocus(); // if (this.changeAddressDialog != null) { // String chooseText = this.changeAddressDialog.getChooseText(); // if (!TextUtils.isEmpty(chooseText)) {//没加载到数据 // this.changeAddressDialog.show(); // } else { // this.changeAddressDialog = new DropDownAlertDialog(this); // this.changeAddressDialog.setOnItemChangeEvent(this); // this.changeAddressDialog.setOnAlertDialogEvent(this); // this.changeAddressDialog.show(); // this.loadAddressInfo(-1); // } // } else { // this.changeAddressDialog = new DropDownAlertDialog(this); // this.changeAddressDialog.setOnItemChangeEvent(this); // this.changeAddressDialog.setOnAlertDialogEvent(this); // this.changeAddressDialog.show(); // this.loadAddressInfo(-1); // } // return; // } // // @Override // public void onSearchClick() {//搜索按钮点击事件 // etSearch.clearFocus(); // resetRadioButton(); // mInputAddress = etSearch.getText().toString().trim(); // if (TextUtils.isEmpty(mInputAddress) || mInputAddress.equals(locationAddress)) { // last_search_way = SEARCH_WAY_LOCATION;// // /** 查询 ①默认进来传经纬度+(地图左上角经纬度、地图右下角经纬度 */ // resetLocation(); // } else {/** 查询 ③用户输入信息(模糊地址),传区号id, */ // //①先通过文本信息获取经纬度然后 // LatLng latLngBystr = getLatLngBystrAndMoveTo(mInputAddress); // if (latLngBystr == null) { // inputTextGetLatLng = false; //// toast("获取对应地理位置失败,请重试"); // //todo 加没取成功就直接用文本请求服务器查? // inputSearchRequest(mInputAddress, locationZoneCode);//③再请求模糊查询 // return; // } // inputTextGetLatLng = true; // GeoCoder mSearch = GeoCoder.newInstance();//②用GeoCoder获取区号 // mSearch.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() { // @Override // public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) { // } // // @Override // public void onGetReverseGeoCodeResult(ReverseGeoCodeResult geoCodeResult) { // locationZoneCode = geoCodeResult.getAdcode(); // inputSearchRequest(mInputAddress, locationZoneCode);//③再请求模糊查询 // } // }); // if (!NetWorkUtil.isNetworkConnected(UserHomeActivity2.this)) { // toast("网络连接不可用"); // }else { // // // mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(latLngBystr)); // } // // BDMapUtils.getCityName(latLngBystr, new BDMapUtils.BDGetCityListener() { // @Override // public void success(String cityName) { // logI("BDMapUtils api cityName = " + cityName); // } // // @Override // public void fail(Exception exc) { // logI("BDMapUtils api exc = " + exc); // } // }); // // String cityName = BDMapUtils.getCityName(this, latLngBystr); // logI(" BDMapUtils.getCityName city=" + cityName); // if (tvCity != null && !TextUtils.isEmpty(cityName)) { // if (cityName.endsWith("市")) { // cityName = cityName.substring(0, cityName.length() - 1); // } // tvCity.setText(cityName); // } else { //// toast("获取对应地理位置失败,请重试"); // } // // } // } // // /** // * ③用户输入信息(模糊地址),传区号id, // */ // // private void inputSearchRequest(final String etAddress, int zoneId) { // SearchInfo searchInfo = new SearchInfo(); // // TODO: 2018/2/14 设置对应参数 // searchInfo.setAccount(getMemberInfo().getAccount()); // searchInfo.setToken(getMemberInfo().getToken()); // if (zoneId == 0) { // toast("无法准确获取当前位置,请到网络较好的地方重试"); // return; // } // searchInfo.setAddress(etAddress + ""); // searchInfo.setZoneId(zoneId); // last_search_way = SEARCH_WAY_INPUT; // logI("inputSearchRequest 用户输入信息(模糊地址) address=" + etAddress); // httpReuqest.sendMessage(Api.User_search, searchInfo, true, new HttpReuqest.CallBack<SearchInfo>() { // @Override // public void onSuccess(Message message, SearchInfo result) { // setInputOrDialogSearchResult(result); // } // // @Override // public void onError(Exception exc) { // logI(exc + ""); // } // // @Override // public void onFinish() { // // } // }); // } // // @Override // public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) { // try { // if (etSearch != null) // etSearch.removeFocus(); // switch (checkedId) { // case R.id.home_rbCanBooking://可预订 // if (rbCanBooking.isChecked()) // searchRequestType(SearchInfo.SearchType.CAN_BESPEAK); // break; // case R.id.home_rbMineBooked:// // if (rbMineBooked.isChecked()) // searchRequestType(SearchInfo.SearchType.MY_BESPEAK); // break; // case R.id.home_rbMineUsing://我占用的 // boolean checked = rbMineUsing.isChecked(); // if (checked) // searchRequestType(SearchInfo.SearchType.MY_OCCUPY); // break; // case R.id.home_rbUsed://已占用 //// rbUsed.setChecked(true); //// mRadioGroup.check(checkedId); // if (rbUsed.isChecked()) // searchRequestType(SearchInfo.SearchType.OCCUPY); // break; // } // // } catch (Exception exc) { // logE(exc.getMessage()); // } // // // } // // /** // * 筛选查询请求 区号一定要传 // * 默认进来传经纬度+(地图左上角经纬度、地图右下角经纬度 // * ①地址选择弹窗,传四级联动地址id // * ②输入用户信息(模糊地址),传区号id, // */ // private void searchRequestType(final SearchInfo.SearchType searchType) { // SearchInfo searchInfo = new SearchInfo(); // // TODO: 2018/2/14 设置对应参数 // searchInfo.setAccount(getMemberInfo().getAccount()); // searchInfo.setToken(getMemberInfo().getToken()); // searchInfo.setSearchType(searchType); // if (last_search_way == SEARCH_WAY_DIALOG) { // logI("searchRequestType 地址栏查询:" + searchType.getText()); // if (infoProvince != null) // searchInfo.setProvinceId(infoProvince.getAreaId()); // if (infoProvince != null) // searchInfo.setCityId(infoCity.getAreaId()); // if (infoProvince != null) // searchInfo.setZoneId(infoZone.getAreaId()); // if (infoProvince != null) // searchInfo.setStreetId(infoStreet.getAreaId()); // } else if (last_search_way == SEARCH_WAY_INPUT) { // if (locationZoneCode == 0) { // toast("无法准确获取当前位置,请到网络较好的地方重试"); // return; // } // logI("searchRequestType 用户输入信息(模糊地址):" + searchType.getText()); // searchInfo.setAddress(mInputAddress + ""); // searchInfo.setZoneId(locationZoneCode); // } else { // logI("searchRequestType 初始进入查询mStartPoint+mEndPoint:" + searchType.getText()); // if (mStartPoint != null && mEndPoint != null) { // searchInfo.setStartPoint(mStartPoint); // searchInfo.setEndPoint(mEndPoint); // } else { // toast("无法准确获取当前位置,请到网络较好的地方重试"); // return; // } // } // httpReuqest.sendMessage(Api.User_search, searchInfo, true, new HttpReuqest.CallBack<SearchInfo>() { // @Override // public void onSuccess(Message message, SearchInfo result) { // if (Api.OK == result.getCode()) { // String text = result.getText(); // logI(text + ""); // // TODO: 2018/2/16 获取相应数据做对应显示 // if (searchType.equals(SearchInfo.SearchType.CAN_BESPEAK)) // setSearchTypeInfoData(result); // else // setSearchInfoData(result); // // List<BillboardInfo> biList = result.getBillboardInfoList(); // if (biList != null && biList.size() > 0) {//当有广告位列表时遍历列表,若其中一个广告位带经纬度就移动到该位置 // for (BillboardInfo billboardInfo : biList) { // LatLng latLng = getLatLng(billboardInfo); // if (latLng != null) { // moveToNewCenter(latLng); // break; // } // } // } // // } // // } // // @Override // public void onError(Exception exc) { // logI(exc + ""); // } // // @Override // public void onFinish() { // // } // }); // } // // private void setSearchInfoData(SearchInfo result) { // mSearchInfo = result; // //广告位列表 // mBillboardInfoList = result.getBillboardInfoList(); // // mAdapter = null;//先回收 // mTypeList = null;//重置 // // if (mBillboardInfoList == null) { // mAdapter = new HomeAdListAdapter(new ArrayList<BillboardInfo>()); // lvAds.setAdapter(mAdapter); // } else { // mAdapter = new HomeAdListAdapter(mBillboardInfoList); // lvAds.setAdapter(mAdapter); // initOverlay(result); // for (BillboardInfo billboardInfo : mBillboardInfoList) { // logI("billboardInfo = " + billboardInfo); // } // } // // } // // /** // * 条件搜索返回处理 // * // * @param typeResult // */ // private void setSearchTypeInfoData(SearchInfo typeResult) { // if (mSearchInfo == null) // return; // //广告位列表 // mBillboardInfoList = mSearchInfo.getBillboardInfoList(); // mTypeList = typeResult.getBillboardInfoList(); // if (mTypeList == null||mTypeList.size()<1){ // toast("筛选没有结果"); // if (mBillboardInfoList == null) // mAdapter = new HomeAdTypeListAdapter(mBillboardInfoList, mTypeList); // else { // mAdapter = new HomeAdTypeListAdapter(mBillboardInfoList, mTypeList); // initTypeOverlay(mSearchInfo, mTypeList); // } // lvAds.setAdapter(mAdapter); // return; // } // // mAdapter = null;//先回收 // // if (mBillboardInfoList == null) { // mAdapter = new HomeAdTypeListAdapter(new ArrayList<BillboardInfo>(), null); // lvAds.setAdapter(mAdapter); // } else { // mAdapter = new HomeAdTypeListAdapter(mBillboardInfoList, mTypeList); // lvAds.setAdapter(mAdapter); // initTypeOverlay(mSearchInfo, mTypeList); // for (BillboardInfo billboardInfo : mTypeList) { // logI("mTypeList: billboardInfo = " + billboardInfo.toString()); // } //// if (mTypeList == null||mTypeList.size()<1) { //// mAdapter = new HomeAdTypeListAdapter(new ArrayList<BillboardInfo>(), null); //// lvAds.setAdapter(mAdapter); //// } else { //// mAdapter = new HomeAdTypeListAdapter(mBillboardInfoList, mTypeList); //// lvAds.setAdapter(mAdapter); //// initTypeOverlay(mSearchInfo, mTypeList); //// for (BillboardInfo billboardInfo : mTypeList) { //// logI("mTypeList: billboardInfo = " + billboardInfo.toString()); //// } //// } // // } // // } // // /** // * @param address 定位成功后回调 // * @param cityName // */ // @Override // protected void locationAddress(String address, String cityName) { // super.locationAddress(address, cityName); // if (mTopView != null && !TextUtils.isEmpty(address)) { // etSearch.setText(""); // etSearch.setHint(address); // etSearch.setHintTextColor(Color.parseColor("#000000")); //// this.etSearch.setText(address); //// this.etSearch.setSelection(address.length()); // } // if (tvCity != null && !TextUtils.isEmpty(cityName)) { // if (cityName.endsWith("市")) { // cityName = cityName.substring(0, cityName.length() - 1); // } // tvCity.setText(cityName); // } // // } // // @Override // public void onClick(View v) { // super.onClick(v); // switch (v.getId()) { // case R.id.homeUser_exit://退出 // etSearch.clearFocus(); // PopupWindowManager.showExitTips(this, itvExit, Api.User_Exit); // break; // case R.id.homeUser_preselect://预选 // etSearch.clearFocus(); // Intent intent = new Intent(this, AdPreselectActivity.class); // startActivity(intent); // break; // case R.id.homeUser_menu://底部列表上的图片 // etSearch.clearFocus(); // if (lvAdLayout.getVisibility() == View.VISIBLE) { // lvAdLayout.setVisibility(View.GONE); // } else { // lvAdLayout.setVisibility(View.VISIBLE); // } // break; // case R.id.homeUser_ivLocation://地位图标 // last_search_way = SEARCH_WAY_LOCATION;// // etSearch.clearFocus(); // resetRadioButton(); // //重新地位 // /** 查询 ①默认进来传经纬度+(地图左上角经纬度、地图右下角经纬度 */ // resetLocation(); // break; // } // } // // /** // * 原来清除选中状态后最后一个点击 // */ // private void resetRadioButton() { //// rbCanBooking.setChecked(false); //// rbMineUsing.setChecked(false); //// rbMineBooked.setChecked(false); //// rbUsed.setChecked(false); //// rbCanBooking.clearFocus(); //// rbMineBooked.clearFocus(); //// rbMineUsing.clearFocus(); //// rbUsed.clearFocus(); // mRadioGroup.clearCheck();//解决、有效 // } // // /** // * @param panelIndex 加载地址信息 // */ // public void loadAddressInfo(final int panelIndex) { // this.changeAddressDialog.showLoad(); // AreaInfo provinceInfo = null; // AreaInfo cityInfo = null; // AreaInfo zoneInfo = null; // if (panelIndex > -1) { // provinceInfo = this.changeAddressDialog.provincePanel.getDropDownItemInfo(); // if (panelIndex > 0) { // cityInfo = this.changeAddressDialog.cityPanel.getDropDownItemInfo(); // if (panelIndex > 1) // zoneInfo = this.changeAddressDialog.zonePanel.getDropDownItemInfo(); // } // } // AddressInfo addressInfo = new AddressInfo(); // // TODO: 2018/2/14 设置对应参数 // addressInfo.setAccount(getMemberInfo().getAccount()); // addressInfo.setToken(getMemberInfo().getToken()); // if (provinceInfo != null) // addressInfo.setProvinceId(provinceInfo.getAreaId()); // if (cityInfo != null) // addressInfo.setCityId(cityInfo.getAreaId()); // if (zoneInfo != null) // addressInfo.setZoneId(zoneInfo.getAreaId()); // // this.httpReuqest.sendMessage(Api.User_address, addressInfo, false, new HttpReuqest.CallBack<AddressInfo>() { // @Override // public void onSuccess(Message message, AddressInfo result) { // if (result == null) // return; // if (Api.OK == result.getCode()) { // List<AreaInfo> provinceList = result.getProvinceList(); // 省份列表--全部 // List<AreaInfo> cityList = result.getCityList(); // 城市列表--省份ID下的所有城市 // List<AreaInfo> zoneList = result.getZoneList(); // 区域列表--城市ID下的所有区域 // List<AreaInfo> streetList = result.getStreetList(); // 街道列表--区域下的所有街道(注:有些区域没有街道数据) // // UserHomeActivity2.this.changeAddressDialog.provincePanel.append(provinceList, result.getProvinceId()); // if (panelIndex == -1) { // UserHomeActivity2.this.changeAddressDialog.provincePanel.scrollActive(); // } // // UserHomeActivity2.this.changeAddressDialog.cityPanel.append(cityList, result.getCityId()); // if (panelIndex <= 1) { // UserHomeActivity2.this.changeAddressDialog.cityPanel.scrollActive(); // } // // UserHomeActivity2.this.changeAddressDialog.zonePanel.append(zoneList, result.getZoneId()); // if (panelIndex <= 2) { // UserHomeActivity2.this.changeAddressDialog.zonePanel.scrollActive(); // } // // if (streetList != null && streetList.size() > 0) { // UserHomeActivity2.this.changeAddressDialog.streetPanel.setVisibility(View.VISIBLE); // UserHomeActivity2.this.changeAddressDialog.streetPanel.append(streetList, result.getStreetId()); // UserHomeActivity2.this.changeAddressDialog.streetPanel.scrollActive(); // } else // UserHomeActivity2.this.changeAddressDialog.streetPanel.setVisibility(View.GONE); // UserHomeActivity2.this.changeAddressDialog.changeSize(); // } // return; // } // // @Override // public void onError(Exception exc) { // logI(exc + ""); // } // // @Override // public void onFinish() { // UserHomeActivity2.this.changeAddressDialog.hideLoad(); // return; // } // }); // // return; // } // // /** // * @param dialog 地址下拉框选择事件 // * @param panel // * @param item // */ // @Override // public void onItemChange(DropDownAlertDialog dialog, DropDownAlertDialog.DropDownAlertDialogPanel panel, DropDownAlertDialog.DropDownAlertDialogItem item) { // if (dialog == this.changeAddressDialog && panel.getIndex() < 3) { // this.loadAddressInfo(panel.getIndex()); // } // return; // } // // /** // * 选择下拉框子项确定事件 // */ // @Override // public void onEnter(DropDownAlertDialog dialog) { // if (dialog == this.changeAddressDialog) { // this.changeAddressDialog.cancel(); // String text = this.changeAddressDialog.getChooseText(); // if (!TextUtils.isEmpty(text)) { //// this.etSearch.setHint(text); // etSearch.setHint(""); // etSearch.setHint("请输入地址"); // etSearch.setHintTextColor(Color.parseColor("#cccccc"));//先重置hint // // this.etSearch.setText(text);//再查询②中用到 // this.etSearch.setSelection(text.length()); // } // AreaInfo areaInfo = dialog.cityPanel.getDropDownItemInfo();//当断网选择会为null // if (areaInfo!=null) { // String cityName = areaInfo.getAreaName(); // locationZoneCode = dialog.zonePanel.getDropDownItemInfo().getAreaId(); // if (!TextUtils.isEmpty(cityName)) { // if (cityName.endsWith("市")) { // cityName = cityName.substring(0, cityName.length() - 1); // } // tvCity.setText(cityName); // } // logI("locationZoneCode = " + locationZoneCode + " -----cityName = " + cityName); // resetRadioButton(); // /** 查询 ② 地址选择弹窗,传四级联动地址id dialogSearchRequest*/ // dialogSearchRequest(this.changeAddressDialog); // } // } // return; // } // // /** // * ② 地址选择弹窗,传四级联动地址id dialogSearchRequest // */ // private void dialogSearchRequest(DropDownAlertDialog addressDialog) { // if (addressDialog == null) { // toast("地址选择异常,请重试"); // return; // } // SearchInfo searchInfo = new SearchInfo(); // // TODO: 2018/2/14 设置对应参数 // searchInfo.setAccount(getMemberInfo().getAccount()); // searchInfo.setToken(getMemberInfo().getToken()); // infoProvince = addressDialog.provincePanel.getDropDownItemInfo(); // infoCity = addressDialog.cityPanel.getDropDownItemInfo(); // infoZone = addressDialog.zonePanel.getDropDownItemInfo(); // infoStreet = addressDialog.streetPanel.getDropDownItemInfo(); // if (infoProvince != null) // searchInfo.setProvinceId(infoProvince.getAreaId()); // if (infoCity != null) // searchInfo.setCityId(infoCity.getAreaId()); // if (infoZone != null) // searchInfo.setZoneId(infoZone.getAreaId()); // if (infoStreet != null) // searchInfo.setStreetId(infoStreet.getAreaId()); // logI("dialogSearchRequest 地址栏选择后查询:"); // last_search_way = SEARCH_WAY_DIALOG; // httpReuqest.sendMessage(Api.User_search, searchInfo, true, new HttpReuqest.CallBack<SearchInfo>() { // @Override // public void onSuccess(Message message, SearchInfo result) { // // TODO: 2018/2/16 获取相应数据做对应显示 // setInputOrDialogSearchResult(result); // } // // @Override // public void onError(Exception exc) { // logI(exc + ""); // } // // @Override // public void onFinish() { // // } // }); // } // // private void setInputOrDialogSearchResult(SearchInfo result) { // if (Api.OK == result.getCode()) { // // String text = result.getText(); // logI(text + ""); // // TODO: 2018/2/16 获取相应数据做对应显示 // setSearchInfoData(result); // List<BillboardInfo> biList = result.getBillboardInfoList(); // if (biList != null && biList.size() > 0) {//当有广告位列表时遍历列表,//若其中一个广告位带经纬度就移动到该位置 // // //遍历广告位列表获取经纬度列表,然后计算距离做自动缩放级别适配 // List<LatLng> latLngList = getLatLngList(result); // if (latLngList != null && latLngList.size() > 0) { // double distance = MapUtils.getDistance(latLngList); // LatLng center = MapUtils.getCenter(latLngList); // moveToNewCenter(center.latitude, center.longitude); // setLevel(distance); // } // //// for (BillboardInfo billboardInfo : biList) { //// LatLng latLng = getLatLng(billboardInfo); //// if (latLng != null) { //// moveToNewCenter(latLng.latitude, latLng.longitude); //// break; //// } //// } // } else {//可能地址栏选择,或者 // if (last_search_way == SEARCH_WAY_INPUT) {//用户输入 // if (!inputTextGetLatLng) {// 点击搜索时不能能根据输入文本获取经纬度 // toast("获取对应地理位置失败,请重试"); // } // // } else { // String addressTrim = etSearch.getText().toString().trim();//可能地址栏选择,或者 // LatLng latLngBystr = getLatLngBystrAndMoveTo(addressTrim); // if (latLngBystr == null) { // toast("获取对应地理位置失败,请重试"); // } // } // } // //// List<LatLng> latLngList = getLatLngList(result); //// if (latLngList != null && latLngList.size() > 0) { //// double distance = MapUtils.getDistance(latLngList); //// LatLng center = MapUtils.getCenter(latLngList); //// moveToNewCenter(center.latitude, center.longitude); //// setLevel(distance); //// } // // } // } // // private List<LatLng> getLatLngList(SearchInfo result) { // List<LatLng> llList = new ArrayList<>(); // List<BillboardInfo> billboardInfoList = result.getBillboardInfoList(); // if (billboardInfoList != null && billboardInfoList.size() > 0) { // for (BillboardInfo billboardInfo : billboardInfoList) { // Double lat = billboardInfo.getLocationLat(); // Double lng = billboardInfo.getLocationLng(); // if (lat!=null && lng!=null) { // llList.add(new LatLng(lat, lng)); // } // } // } // return llList; // } // //}
package com.example.aizat.alarmclock.screen.main.third; import android.app.Fragment; import android.os.Bundle; import android.os.PersistableBundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.example.aizat.alarmclock.screen.base.BaseActivity; /** * Created by Aizat on 09.11.2017. */ public class StopActivity extends BaseActivity { @NonNull @Override protected Fragment makeFragment() { return StopFragment.newInstance(); } }
package com.finahub.coding.server.airtable; public class AirtableConfiguration { private String ENDPOINT_URL; private String AIRTABLE_BASE; private String AIRTABLE_API_KEY; private String AIRTABLE_PROXY; public AirtableConfiguration(String ENDPOINT_URL, String AIRTABLE_API_KEY) { this(ENDPOINT_URL,AIRTABLE_API_KEY,null); } public AirtableConfiguration(String ENDPOINT_URL, String AIRTABLE_API_KEY,String AIRTABLE_PROXY) { super(); this.ENDPOINT_URL = ENDPOINT_URL; this.AIRTABLE_API_KEY = AIRTABLE_API_KEY; this.AIRTABLE_PROXY = AIRTABLE_PROXY; } public String getENDPOINT_URL() { return ENDPOINT_URL; } public void setENDPOINT_URL(String eNDPOINT_URL) { ENDPOINT_URL = eNDPOINT_URL; } public String getAIRTABLE_BASE() { return AIRTABLE_BASE; } public void setAIRTABLE_BASE(String aIRTABLE_BASE) { AIRTABLE_BASE = aIRTABLE_BASE; } public String getAIRTABLE_API_KEY() { return AIRTABLE_API_KEY; } public void setAIRTABLE_API_KEY(String aIRTABLE_API_KEY) { AIRTABLE_API_KEY = aIRTABLE_API_KEY; } public String getAIRTABLE_PROXY() { return AIRTABLE_PROXY; } public void setAIRTABLE_PROXY(String aIRTABLE_PROXY) { AIRTABLE_PROXY = aIRTABLE_PROXY; } }
package com.dg.android.syncnotes.domain; import com.fasterxml.jackson.annotation.JsonProperty; public class Note { @JsonProperty(value = "created_at") String createdAt; @JsonProperty String description; @JsonProperty String id; @JsonProperty String name; @JsonProperty String title; @JsonProperty(value = "updated_at") String updatedAt; public String getCreatedAt() { return createdAt; } public void setCreatedAt(String createdAt) { this.createdAt = createdAt; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getUpdatedAt() { return updatedAt; } public void setUpdatedAt(String updatedAt) { this.updatedAt = updatedAt; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Note [createdAt="); builder.append(createdAt); builder.append(", description="); builder.append(description); builder.append(", id="); builder.append(id); builder.append(", name="); builder.append(name); builder.append(", title="); builder.append(title); builder.append(", updatedAt="); builder.append(updatedAt); builder.append("]"); return builder.toString(); } }
package com.loneless.fourth_task.comparator; import com.loneless.fourth_task.entity.TravelVoucher; import java.util.Comparator; public class CompareByCost implements Comparator<TravelVoucher> { @Override public int compare(TravelVoucher o1, TravelVoucher o2) { return Double.compare(o1.getCost(),o2.getCost()); } }
package com.xwolf.eop.system.dao; import com.xwolf.eop.system.entity.Permissions; import java.util.List; public interface PermissionsMapper { int deleteByPrimaryKey(Integer pid); int insert(Permissions record); int insertSelective(Permissions record); Permissions selectByPrimaryKey(Integer pid); int updateByPrimaryKeySelective(Permissions record); int updateByPrimaryKey(Permissions record); List<Permissions> getPermissionsByUserCode(String usercode); }
class Person<T>{ T persontype; public T getPersontype() { return persontype; } public void setPersontype(T persontype) { this.persontype = persontype; } } class student{ } class employee{ } public class generic_example_2 { public static void main(String[] args) { Person<student> p = new Person<>(); p.setPersontype(new student()); student student1= p.getPersontype(); System.out.println(student1); Person<employee> e= new Person<employee>(); e.setPersontype(new employee()); employee emp=e.getPersontype(); System.out.println(emp); } }
package com.jkm.databsqllite; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by HP on 05-06-2018. */ public class DB extends SQLiteOpenHelper { public static final String dbn="DBSQLite.db"; public static final String tbn="ITEMS"; public static final String c1="ID"; public static final String c2="Name"; public static final String c3="Batch_No"; public static final String c4="Price"; public DB(Context context) { super(context,dbn,null,2); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("Create table "+(tbn)+" (ID TEXT PRIMARY KEY UNIQUE,Name TEXT,Batch_No TEXT,Price TEXT)"); } @Override public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion) { db.execSQL("DROP TABLE IF EXISTS "+tbn); onCreate(db); } public Boolean dataInsert(String id,String i,String bn,String p) { SQLiteDatabase db=this.getWritableDatabase(); ContentValues cv=new ContentValues(); cv.put(c1,id); cv.put(c2,i); cv.put(c3,bn); cv.put(c4,p); long result=db.insert(tbn,null,cv); if(result==-1) return false; else return true; } public Cursor dataShow() { SQLiteDatabase db=this.getReadableDatabase(); Cursor cursor=db.rawQuery("SELECT * FROM "+tbn,null); return cursor; } public Boolean dataUpdate(String id,String i,String bn,String p) { SQLiteDatabase db=this.getWritableDatabase(); ContentValues cv=new ContentValues(); cv.put(c1,id); cv.put(c2,i); cv.put(c3,bn); cv.put(c4,p); //int rowsAffected= db.update(tbn,cv,"ID=?",new String[]{id}); return true; } public Integer dataDelete(String id) { SQLiteDatabase db=getWritableDatabase(); //int rowsAffected= return db.delete(tbn,"ID=?",new String[]{id}); } }
package com.alibaba.druid.bvt.sql; import com.alibaba.druid.DbType; import com.alibaba.druid.sql.PagerUtils; import com.alibaba.druid.util.JdbcUtils; import junit.framework.TestCase; import org.junit.Assert; public class PagerUtilsTest_Limit_hive_0 extends TestCase { public void test_hive_0() throws Exception { String result = PagerUtils.limit("SELECT * FROM test", DbType.hive, 0, 10); System.out.println(result); Assert.assertEquals("SELECT *\n" + "FROM test\n" + "LIMIT 10", result); } public void test_odps_0() throws Exception { String result = PagerUtils.limit("SELECT * FROM test", DbType.odps, 0, 10); System.out.println(result); Assert.assertEquals("SELECT *\n" + "FROM test\n" + "LIMIT 10", result); } }
package com.karya.bean; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotEmpty; public class AppraisalBean { private int apprId; @NotNull @NotEmpty(message = "Please enter the Series") private String series; @NotNull @NotEmpty(message = "Please select the appraisal Temp") private String appraisalTemp; public int getApprId() { return apprId; } public void setApprId(int apprId) { this.apprId = apprId; } public String getSeries() { return series; } public void setSeries(String series) { this.series = series; } public String getAppraisalTemp() { return appraisalTemp; } public void setAppraisalTemp(String appraisalTemp) { this.appraisalTemp = appraisalTemp; } }
import java.util.stream.IntStream; class Hamming { private int hamming; Hamming(String leftStrand, String rightStrand) { if (leftStrand.length() == rightStrand.length()) { hamming = IntStream .range(0, leftStrand.length()) .reduce(0, (sum, position) -> leftStrand.charAt(position) != rightStrand.charAt(position) ? ++sum : sum); } else { if (leftStrand.isEmpty()) throw new IllegalArgumentException("left strand must not be empty."); if (rightStrand.isEmpty()) throw new IllegalArgumentException("right strand must not be empty."); throw new IllegalArgumentException("leftStrand and rightStrand must be of equal length."); } } int getHammingDistance() { return hamming; } }
package org.dizitart.nitrite.datagate.auth; import java.util.logging.Logger; /* * 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. */ /** * * @author tareq */ public abstract class DatagateAuthenticator { private static final Logger LOG = Logger.getLogger(DatagateAuthenticator.class.getName()); /** * Authenticates a user's session. If they are authenticated, then this marks the session as authenticated and inserts the username into * the session properties * * @param session the session to authenticate * @param username the username of the user * @param password the password of the user * @return whether the session was authenticated or not */ public boolean authenticate(String username, String password) { try { return doAuthentication(username, password); } catch (Exception ex) { LOG.info(ex.getMessage()); return false; } } /** * Do the authentication for the session * * @param username the username to check * @param password the password to check * @return true if the user is authenticated, false otherwise */ protected abstract boolean doAuthentication(String username, String password); }
/* * Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.webui.common; import pl.edu.icm.unity.server.utils.UnityMessageSource; import pl.edu.icm.unity.types.basic.AttributeType; /** * Shared helpers for attribute(types) * @author K. Benedyczak */ public class AttributeTypeUtils { public static String getBoundsDesc(UnityMessageSource msg, Integer min, Integer max) { String from = (min == null || min == Integer.MIN_VALUE) ? msg.getMessage("AttributeType.noLimit") : min+""; String to = (max == null || max == Integer.MAX_VALUE) ? msg.getMessage("AttributeType.noLimit") : max+""; return "[" + from + ", " + to + "]"; } public static String getBoundsDesc(UnityMessageSource msg, Long min, Long max) { String from = (min == null || min == Long.MIN_VALUE) ? msg.getMessage("AttributeType.noLimit") : min+""; String to = (max == null || max == Long.MAX_VALUE) ? msg.getMessage("AttributeType.noLimit") : max+""; return "[" + from + ", " + to + "]"; } public static String getBoundsDesc(UnityMessageSource msg, Double min, Double max) { String from = (min == null || min == Double.MIN_VALUE) ? msg.getMessage("AttributeType.noLimit") : min+""; String to = (max == null || max == Double.MAX_VALUE) ? msg.getMessage("AttributeType.noLimit") : max+""; return "[" + from + ", " + to + "]"; } public static String getBooleanDesc(UnityMessageSource msg, boolean val) { return val ? msg.getMessage("yes") : msg.getMessage("no"); } public static String getVisibilityDesc(UnityMessageSource msg, AttributeType type) { return msg.getMessage("AttributeType.visibility." + type.getVisibility().toString()); } public static String getFlagsDesc(UnityMessageSource msg, AttributeType type) { StringBuilder sb = new StringBuilder(); int flags = type.getFlags(); boolean needSep = false; if ((flags & AttributeType.INSTANCES_IMMUTABLE_FLAG) != 0) { sb.append(msg.getMessage("AttributeType.instancesImmutable")); needSep = true; } if ((flags & AttributeType.TYPE_IMMUTABLE_FLAG) != 0) { if (needSep) sb.append("; "); sb.append(msg.getMessage("AttributeType.typeImmutable")); needSep = true; } return sb.toString(); } }
package abc.pages; import abc.core.PageObject; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.Select; import org.testng.Assert; import java.util.List; /** * Created by mrinalirao on 16/03/17. */ public class RadioHomePage extends PageObject { By programList = By.xpath("//div[@id='rn-navigation']/ul/li[2]/a"); By lastItem = By.xpath(".//*[@id='content']/div[1]/div/div/div[2]/ul/li[22]/a/div"); By searchInput = By.xpath("//input[@id='search-simple-input-query']"); public RadioHomePage() { super(conf); } public void WaitForRadioHomePageLoad() { // opening the abc URL driver.get(conf.getConfig("abcBaseUrl") + "/radionational"); waitForLoad(driver); } public BigIdeaPage navigateToBigIdeaPage() { WebElement program = driver.findElement(programList); Actions action = new Actions(driver); action.moveToElement(program).perform(); WebElement subElement = driver.findElement(By.linkText("Big Ideas")); action.moveToElement(subElement); action.click(); action.perform(); return new BigIdeaPage(); } // horizontal scrolling in the program guide public void scrollToLastItem() { int size = 1; while (!(driver.findElement(lastItem).isDisplayed())) { WebElement arrow = driver.findElement(By.cssSelector("#right-arrow")); arrow.click(); } List<WebElement> lis = driver.findElements(By.xpath(".//*[@id='content']/div[1]/div/div/div[2]/ul/li")); int s = lis.size()-1; //selecting the last element WebElement lastButOne= driver.findElement(By.xpath(".//*[@id='content']/div[1]/div/div/div[2]/ul/li[" + s + "]/a/div")); lastButOne.click(); } public void searchItem(){ By searchResult = By.xpath("//p[starts-with(text(),'Your search for')]"); driver.findElement(searchInput).sendKeys("sydney" + "\n"); String searchPara = driver.findElement(searchResult).getText(); String res = searchPara.substring(searchPara.indexOf("matched") + 8, searchPara.indexOf("items")-1); Assert.assertNotSame(0,res); } }
import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; public class Graph<T extends Comparable<T>> implements GraphADT<T> { private class Vertex { private HashSet<T> edges; Vertex(T data) { this.edges = new HashSet<T>(); } } int order, size; HashMap<T, Vertex> vertices; Graph() { this.order = this.size = 0; this.vertices = new HashMap<T, Vertex>(); } @Override public void addVertex(T vertex) throws IllegalArgumentException { if (vertex == null) { throw new IllegalArgumentException("Cannot insert null vertex."); } else if (!vertices.containsKey(vertex)) { vertices.put(vertex, new Vertex(vertex)); order++; } } @Override public void removeVertex(T vertex) throws IllegalArgumentException { // TODO Auto-generated method stub if (vertex == null) { throw new IllegalArgumentException("Cannot remove null vertex."); } else if (vertices.containsKey(vertex)) { for (T edge : vertices.get(vertex).edges) { vertices.get(edge).edges.remove(vertex); size--; } vertices.remove(vertex); order--; } } @Override public void addEdge(T vertex1, T vertex2) throws IllegalArgumentException { // TODO Auto-generated method stub if(vertex1 == null || vertex2 == null) { throw new IllegalArgumentException("Cannot add edge to null vertex."); }else if (vertices.containsKey(vertex1) && vertices.containsKey(vertex2)) { vertices.get(vertex1).edges.add(vertex2); vertices.get(vertex2).edges.add(vertex1); size++; } } @Override public void removeEdge(T vertex1, T vertex2) throws IllegalArgumentException { // TODO Auto-generated method stub if (vertex1 == null || vertex2 == null) { throw new IllegalArgumentException("Cannot remove edge from null vertex."); }else if (vertices.containsKey(vertex1) && vertices.containsKey(vertex2)) { vertices.get(vertex1).edges.remove(vertex2); vertices.get(vertex2).edges.remove(vertex1); size--; } } @Override public List<T> getAllVertices() { // TODO Auto-generated method stub return new ArrayList<T>(vertices.keySet()); } @Override public List<T> getAdjacentVerticesOf(T vertex) throws IllegalArgumentException { // TODO Auto-generated method stub if (vertex == null) { throw new IllegalArgumentException("Cannot find adjacent vertices of null verticy"); }else if (vertices.containsKey(vertex)) { return new ArrayList<T>(vertices.get(vertex).edges); } return new ArrayList<T>(); } @Override public int size() { return size; } @Override public int order() { return order; } // TODO: implement this class }
package ex4; class Tv { private String name; private int year; private int size; void show(){ System.out.println(name + "에서 만든 " + year + "년형 " + size + "인치 TV"); } public Tv() { // TODO Auto-generated constructor stub } public Tv(String name, int year, int size) { this.name = name; this.year = year; this.size = size; } public static void main(String[] args) { Tv myTv = new Tv("LG", 2017, 32); myTv.show(); } }
package com.generatethumbnail; import android.content.ContentProviderClient; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.net.Uri; import android.os.Environment; import android.os.ParcelFileDescriptor; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import com.activity.ThumbnailLayoutActivity; import com.bumptech.glide.Glide; import com.facebook.react.uimanager.LayoutShadowNode; import com.facebook.react.uimanager.SimpleViewManager; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.annotations.ReactProp; import com.rnanimation.R; import com.shockwave.pdfium.PdfDocument; import com.shockwave.pdfium.PdfiumCore; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import javax.annotation.Nullable; public class GenerateThumbnailManager extends SimpleViewManager<ThumbnailLayout> { ThemedReactContext context; ThumbnailView thumbnail; private String resourceType = "video"; private String resource = ""; @Override public String getName() { return "GenerateThumbnail"; } @Override protected ThumbnailLayout createViewInstance(ThemedReactContext reactContext) { context = reactContext; ThumbnailLayout layout = new ThumbnailLayout(reactContext); layout.setOrientation(LinearLayout.VERTICAL); layout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)); thumbnail = new ThumbnailView(reactContext); thumbnail.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)); thumbnail.setBackgroundColor(Color.GRAY); layout.addView(thumbnail); return layout; } @ReactProp(name="url") public void setUrl(View view, String url){ Log.e("URL------>",url); this.resource = url; if(url != "" && this.resourceType.equals("video")){ generateThumbnailForVideo(context, this.resource, thumbnail); } } @ReactProp(name="type") public void setType(View view,String type){ Log.e("TYPE------>",type); this.resourceType = type; if(resource != "" && type.equals("video")){ generateThumbnailForVideo(context, resource, thumbnail); } } public void generateThumbnailForVideo(Context context, String videoUrl, ImageView thumbnail){ Glide.with(context) .load(videoUrl) .thumbnail(0.2f) .error(R.drawable.littlegirl) .into(thumbnail); } public void generateImageFromPdf(Context context , String pdfUri, ImageView thumbnail) { int pageNumber = 0; Uri uri = Uri.parse(pdfUri); PdfiumCore pdfiumCore = new PdfiumCore(context); try { //http://www.programcreek.com/java-api-examples/index.php?api=android.os.ParcelFileDescriptor ContentResolver resolver = context.getContentResolver(); ContentProviderClient providerClient = resolver.acquireUnstableContentProviderClient(uri); ParcelFileDescriptor fd = providerClient.openFile(uri, "r"); PdfDocument pdfDocument = pdfiumCore.newDocument(fd); pdfiumCore.openPage(pdfDocument, pageNumber); int width = pdfiumCore.getPageWidthPoint(pdfDocument, pageNumber); int height = pdfiumCore.getPageHeightPoint(pdfDocument, pageNumber); Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); pdfiumCore.renderPageBitmap(pdfDocument, bmp, pageNumber, 0, 0, width, height); pdfiumCore.closeDocument(pdfDocument); // important! thumbnail.setImageBitmap(bmp); } catch(Exception e) { e.printStackTrace(); } } }
package com.example.android.scorekeeper; import android.content.res.TypedArray; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; public class MainActivity extends AppCompatActivity { int pointsTeamA = 0; int pointsTeamB = 0; String color_check; // spinner change image variables private String[] listOfObjects; private TypedArray images; private ImageView itemImageA; private ImageView itemImageB; // variables for changing button shape background private TypedArray team_colors; private Button team_a_td_color; private Button team_a_xp_color; private Button team_a_tpc_color; private Button team_a_fg_color; private Button team_a_saf_color; private Button team_b_td_color; private Button team_b_xp_color; private Button team_b_tpc_color; private Button team_b_fg_color; private Button team_b_saf_color; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); displayForTeamA(pointsTeamA); displayForTeamB(pointsTeamB); //change image with spinner listOfObjects = getResources().getStringArray(R.array.nfl_teams_array); images = getResources().obtainTypedArray(R.array.team_image); team_colors = getResources().obtainTypedArray(R.array.team_color_array); // Team A spinner itemImageA = (ImageView)findViewById(R.id.team_a_image); team_a_td_color = (Button)findViewById(R.id.team_a_td); team_a_xp_color = (Button)findViewById(R.id.team_a_xp); team_a_tpc_color = (Button)findViewById(R.id.team_a_tpc); team_a_fg_color = (Button)findViewById(R.id.team_a_fg); team_a_saf_color = (Button)findViewById(R.id.team_a_saf); final Spinner spinnerA = (Spinner)findViewById(R.id.team_a_spinner); ArrayAdapter<String> spinnerAdapterA = new ArrayAdapter<String>(this,R.layout.spinner_item, listOfObjects); spinnerAdapterA.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerA.setAdapter(spinnerAdapterA); spinnerA.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { itemImageA.setImageResource(images.getResourceId(spinnerA.getSelectedItemPosition(), -1)); team_a_td_color.setBackgroundResource(team_colors.getResourceId(spinnerA.getSelectedItemPosition(),-1)); team_a_xp_color.setBackgroundResource(team_colors.getResourceId(spinnerA.getSelectedItemPosition(),-1)); team_a_tpc_color.setBackgroundResource(team_colors.getResourceId(spinnerA.getSelectedItemPosition(),-1)); team_a_fg_color.setBackgroundResource(team_colors.getResourceId(spinnerA.getSelectedItemPosition(),-1)); team_a_saf_color.setBackgroundResource(team_colors.getResourceId(spinnerA.getSelectedItemPosition(),-1)); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); // Team B spinner itemImageB = (ImageView)findViewById(R.id.team_b_image); team_b_td_color = (Button)findViewById(R.id.team_b_td); team_b_xp_color = (Button)findViewById(R.id.team_b_xp); team_b_tpc_color = (Button)findViewById(R.id.team_b_tpc); team_b_fg_color = (Button)findViewById(R.id.team_b_fg); team_b_saf_color = (Button)findViewById(R.id.team_b_saf); final Spinner spinnerB = (Spinner)findViewById(R.id.team_b_spinner); ArrayAdapter<String> spinnerAdapterB = new ArrayAdapter<String>(this,R.layout.spinner_item, listOfObjects); spinnerAdapterB.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerB.setAdapter(spinnerAdapterB); spinnerB.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { itemImageB.setImageResource(images.getResourceId(spinnerB.getSelectedItemPosition(), -1)); team_b_td_color.setBackgroundResource(team_colors.getResourceId(spinnerB.getSelectedItemPosition(),-1)); team_b_xp_color.setBackgroundResource(team_colors.getResourceId(spinnerB.getSelectedItemPosition(),-1)); team_b_tpc_color.setBackgroundResource(team_colors.getResourceId(spinnerB.getSelectedItemPosition(),-1)); team_b_fg_color.setBackgroundResource(team_colors.getResourceId(spinnerB.getSelectedItemPosition(),-1)); team_b_saf_color.setBackgroundResource(team_colors.getResourceId(spinnerB.getSelectedItemPosition(),-1)); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("pointsTeamA", pointsTeamA); outState.putInt("pointsTeamB", pointsTeamB); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); pointsTeamA = savedInstanceState.getInt("pointsTeamA"); pointsTeamB = savedInstanceState.getInt("pointsTeamB"); displayForTeamA(pointsTeamA); displayForTeamB(pointsTeamB); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * Increase the score for Team A by 1 point. */ public void addOneForTeamA(View v) { pointsTeamA = pointsTeamA + 1; displayForTeamA(pointsTeamA); } /** * Increase the score for Team A by 2 points. */ public void addTwoForTeamA(View v) { pointsTeamA = pointsTeamA + 2; displayForTeamA(pointsTeamA); } /** * Increase the score for Team A by 3 points. */ public void addThreeForTeamA(View v) { pointsTeamA = pointsTeamA +3; displayForTeamA(pointsTeamA); } /** * Increase the score for Team A by 6 points. */ public void addSixForTeamA(View v) { pointsTeamA = pointsTeamA +6; displayForTeamA(pointsTeamA); } /** * Displays the given score for Team A. */ public void displayForTeamA(int score) { TextView scoreView = (TextView) findViewById(R.id.team_a_score); scoreView.setText(String.valueOf(score)); } /** * Increase the score for Team B by 1 point. */ public void addOneForTeamB(View v) { pointsTeamB = pointsTeamB + 1; displayForTeamB(pointsTeamB); } /** * Increase the score for Team B by 2 points. */ public void addTwoForTeamB(View v) { pointsTeamB = pointsTeamB + 2; displayForTeamB(pointsTeamB); } /** * Increase the score for Team B by 3 points. */ public void addThreeForTeamB(View v) { pointsTeamB = pointsTeamB +3; displayForTeamB(pointsTeamB); } /** * Increase the score for Team B by 6 points. */ public void addSixForTeamB(View v) { pointsTeamB = pointsTeamB +6; displayForTeamB(pointsTeamB); } /** * Displays the given score for Team B. */ public void displayForTeamB(int score) { TextView scoreView = (TextView) findViewById(R.id.team_b_score); scoreView.setText(String.valueOf(score)); } /** * Resets the given score for both teams to 0. */ public void resetScore(View v) { pointsTeamA = 0; pointsTeamB = 0; displayForTeamA(pointsTeamA); displayForTeamB(pointsTeamB); } }
package com.ifeng.recom.mixrecall.core.channel.impl; import com.ifeng.recom.mixrecall.common.constant.RecallConstant; import com.ifeng.recom.mixrecall.common.constant.UserProfileEnum.TagPeriod; import com.ifeng.recom.mixrecall.common.model.RecallResult; import com.ifeng.recom.mixrecall.common.model.UserModel; import com.ifeng.recom.mixrecall.common.model.request.LogicParams; import com.ifeng.recom.mixrecall.common.model.request.MixRequestInfo; import com.ifeng.recom.mixrecall.common.tool.ServiceLogUtil; import com.ifeng.recom.mixrecall.common.util.UserProfileUtils; import com.ifeng.recom.mixrecall.core.channel.excutor.csc.DocpicScRecall; import com.ifeng.recom.mixrecall.core.threadpool.ExecutorThreadPool; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Future; @Service public class DocpicScChannelImpl { private static final org.slf4j.Logger logger = LoggerFactory.getLogger(DocpicScChannelImpl.class); private static final int TIMEOUT = 300; private RecallResult.WeightAndPreloadPositionComparator weightAndPreloadPositionComparator = new RecallResult.WeightAndPreloadPositionComparator(); public List<RecallResult> doRecall(MixRequestInfo mixRequestInfo) { long startTime = System.currentTimeMillis(); String uid = mixRequestInfo.getUid(); UserModel userModel = mixRequestInfo.getUserModel(); LogicParams logicParams = mixRequestInfo.getLogicParams(); List<RecallResult> result = callDocpicSc(mixRequestInfo, logicParams, userModel); long cost = System.currentTimeMillis() - startTime; if (cost > 50) { ServiceLogUtil.debug("DocpicScChannelImpl {} cost:{}", uid, cost); } return result; } private List<RecallResult> callDocpicSc(MixRequestInfo mixRequestInfo, LogicParams logicParams, UserModel userModel) { List<RecallResult> recallResults = new ArrayList<>(); Map<String, Future<List<RecallResult>>> threadResultMap = new HashMap<>(); Future<List<RecallResult>> docpicScResult = null; try { docpicScResult = ExecutorThreadPool.submitExecutorTask(new DocpicScRecall(mixRequestInfo, UserProfileUtils.profileTagWeightFilter(userModel.getDocpic_subcate(),RecallConstant.PROFILE_CUT_OFF_WEIGHT), TagPeriod.LONG, logicParams.docpicScNum)); if (docpicScResult != null) { threadResultMap.put(TagPeriod.LONG.toString(), docpicScResult); } Map<String, List<RecallResult>> result = ExecutorThreadPool.getExecutorResult(threadResultMap, TIMEOUT); recallResults = result.values().stream().collect(ArrayList::new, List::addAll, List::addAll); recallResults.sort(weightAndPreloadPositionComparator); if("3619988e26104ce99bb230d2d0335a91".equals(mixRequestInfo.getUid())) { logger.info("@@docpicScChannelImpl@@ uid:{} recallResults.size:{}", mixRequestInfo.getUid(), recallResults.size()); } } catch (Exception e) { e.printStackTrace(); logger.error("{} callDocpicSc ERROR:{}", mixRequestInfo.getUid(), e.toString()); } return recallResults; } }
package pt.utl.ist.bw.elements; public class CaseInstanceID { private String instanceID; public CaseInstanceID(String id) { if(id == null) this.instanceID = ""; if(id.contains(".")) { this.instanceID = id.split("\\.")[0]; } else { this.instanceID = id; } } @Override public String toString() { return this.instanceID; } @Override public boolean equals(Object anObject) { if(!(anObject instanceof CaseInstanceID)) { return false; } return ((CaseInstanceID) anObject).toString().equals(this.toString()); } @Override public int hashCode() { int hash = 1; hash = hash * 31 + instanceID.hashCode(); hash = hash * 31; return hash; } }
package com.freakybyte.movies.control.movie.ui; import android.content.res.ColorStateList; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.FloatingActionButton; import android.support.v4.widget.NestedScrollView; import android.support.v7.graphics.Palette; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.format.DateUtils; import android.util.Log; import android.view.View; import android.widget.TextView; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.drawee.backends.pipeline.PipelineDraweeController; import com.facebook.drawee.view.SimpleDraweeView; import com.facebook.imagepipeline.request.BasePostprocessor; import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.imagepipeline.request.ImageRequestBuilder; import com.facebook.imagepipeline.request.Postprocessor; import com.freakybyte.movies.R; import com.freakybyte.movies.control.BaseActivity; import com.freakybyte.movies.control.adapter.ReviewRecyclerViewAdapter; import com.freakybyte.movies.control.movie.constructor.MovieDetailPresenter; import com.freakybyte.movies.control.movie.constructor.MovieDetailView; import com.freakybyte.movies.control.movie.impl.MovieDetailPresenterImpl; import com.freakybyte.movies.data.dao.FavoriteDao; import com.freakybyte.movies.model.movie.MovieResponseModel; import com.freakybyte.movies.model.review.ReviewMovieModel; import com.freakybyte.movies.util.DateTimeUtils; import com.freakybyte.movies.util.ImageUtils; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class MovieDetailActivity extends BaseActivity implements MovieDetailView { public static final String TAG = "MovieDetailActivity"; public static final String TAG_REVIEW_PAGE = "MovieReviewPage"; @BindView(R.id.toolbar) public Toolbar mToolbar; @BindView(R.id.sv_movie_backdrop) public SimpleDraweeView svMovieBackdrop; @BindView(R.id.sv_movie_poster) public SimpleDraweeView svMoviePoster; @BindView(R.id.collapsing_toolbar) public CollapsingToolbarLayout mCollapsingToolbar; @BindView(R.id.tv_movie_description) public TextView tvMovieDescription; @BindView(R.id.tv_movie_date) public TextView tvMovieDate; @BindView(R.id.tv_movie_duration) public TextView tvMovieDuration; @BindView(R.id.tv_movie_rating) public TextView tvMovieRating; @BindView(R.id.conversation) public RecyclerView gridImages; @BindView(R.id.scroll_view_movie_detail) public NestedScrollView scrollViewMovieDetail; @BindView(R.id.fb_movie_favorite) public FloatingActionButton fbMovieFavorite; private LinearLayoutManager mLayoutManager; private ReviewRecyclerViewAdapter mAdapter; private MovieResponseModel mMovie; private MovieDetailPresenter mPresenter; private FavoriteDao mFavoriteDao; private int iMoviePage = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_movie_detail); ButterKnife.bind(this); mPresenter = new MovieDetailPresenterImpl(this, this); mFavoriteDao = FavoriteDao.getInstance(this); setSupportActionBar(mToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); mToolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back_black)); mToolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); mMovie = getIntent().getParcelableExtra(MovieResponseModel.TAG); setToolbarContent(); updateMovieContent(); gridImages.setLayoutManager(getStageGridLayoutManager()); gridImages.setAdapter(getMoviesAdapter()); gridImages.setHasFixedSize(true); if (savedInstanceState != null) { iMoviePage = savedInstanceState.getInt(TAG_REVIEW_PAGE, 0); ArrayList<ReviewMovieModel> savedList = savedInstanceState.getParcelableArrayList(MovieResponseModel.TAG); updateMovieReview(savedList); } else { mPresenter.getMovieReviews(mMovie.getId(), iMoviePage); } refreshFavButton(mFavoriteDao.isMovieFavorite(mMovie.getId())); Log.d(TAG, "Movie:: " + mMovie.getId()); } public void setToolbarContent() { mCollapsingToolbar.setTitle(mMovie.getTitle()); mCollapsingToolbar.setExpandedTitleColor(getResources().getColor(android.R.color.black)); mCollapsingToolbar.setCollapsedTitleTextColor(getResources().getColor(android.R.color.white)); final Postprocessor redMeshPostprocessor = new BasePostprocessor() { @Override public void process(Bitmap bitmap) { Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() { @SuppressWarnings("ResourceType") @Override public void onGenerated(Palette palette) { Palette.Swatch dominantSwatch = palette.getDominantSwatch(); if (dominantSwatch != null) { mToolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back)); mCollapsingToolbar.setContentScrimColor(dominantSwatch.getRgb()); mCollapsingToolbar.setCollapsedTitleTextColor(dominantSwatch.getTitleTextColor()); mCollapsingToolbar.setExpandedTitleColor(dominantSwatch.getTitleTextColor()); } updateBackground(fbMovieFavorite, palette); mCollapsingToolbar.setStatusBarScrimColor(palette.getDarkMutedColor(getResources().getColor(R.color.colorPrimary))); } }); } }; final ImageRequest request = ImageRequestBuilder.newBuilderWithSource(Uri.parse(ImageUtils.getMovieUri(false, mMovie.getBackdropPath()))) .setPostprocessor(redMeshPostprocessor) .build(); final PipelineDraweeController controller = (PipelineDraweeController) Fresco.newDraweeControllerBuilder() .setImageRequest(request) .setOldController(svMovieBackdrop.getController()) .build(); svMovieBackdrop.setController(controller); svMoviePoster.setImageURI(ImageUtils.getMovieUri(false, mMovie.getPosterPath())); } private void updateBackground(FloatingActionButton fab, Palette palette) { int lightVibrantColor = palette.getLightVibrantColor(getResources().getColor(android.R.color.white)); int vibrantColor = palette.getVibrantColor(getResources().getColor(R.color.colorAccent)); fab.setRippleColor(lightVibrantColor); fab.setBackgroundTintList(ColorStateList.valueOf(vibrantColor)); } private void updateMovieContent() { tvMovieDescription.setText(mMovie.getOverview()); tvMovieDate.setText(DateTimeUtils.getYearByDate(mMovie.getReleaseDate())); tvMovieDuration.setText(String.format(getResources().getString(R.string.detail_movie_duration), mMovie.getRuntime())); tvMovieRating.setText(String.format(getResources().getString(R.string.detail_movie_rating), mMovie.getVoteAverage())); } @Override public void showLoader() { } @Override public void refreshFavButton(boolean isFavorite) { fbMovieFavorite.setImageResource(isFavorite ? R.drawable.ic_favorite_selected : R.drawable.ic_favorite_no_selected); } @Override public void closeLoaders() { } @OnClick(R.id.fb_movie_favorite) public void setMovieFavorite() { if (mFavoriteDao.isMovieFavorite(mMovie.getId())) { mFavoriteDao.deleteFavorite(mMovie.getId()); refreshFavButton(false); } else { mFavoriteDao.insertFavoriteMovie(mMovie.getId()); refreshFavButton(true); } } @Override public void onSaveInstanceState(Bundle savedInstanceState) { savedInstanceState.putParcelableArrayList(MovieResponseModel.TAG, getMoviesAdapter().getReviews()); savedInstanceState.putInt(TAG_REVIEW_PAGE, iMoviePage); super.onSaveInstanceState(savedInstanceState); } @Override protected void onDestroy() { super.onDestroy(); mPresenter.onDestroy(); } private LinearLayoutManager getStageGridLayoutManager() { if (mLayoutManager == null) mLayoutManager = new LinearLayoutManager(this); return mLayoutManager; } private ReviewRecyclerViewAdapter getMoviesAdapter() { if (mAdapter == null) mAdapter = new ReviewRecyclerViewAdapter(); return mAdapter; } @Override public void updateMovieReview(ArrayList<ReviewMovieModel> aReviews) { getMoviesAdapter().swapItems(aReviews); scrollViewMovieDetail.scrollTo(0, 0); iMoviePage += iMoviePage; } }
package net.tascalate.concurrent; import java.util.Collections; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; public class Promises { public static <T> Promise<T> readyValue(T value) { final CompletablePromise<T> result = new CompletablePromise<>(); result.onSuccess(value); return result; } public static <T> Promise<T> from(CompletionStage<T> stage) { if (stage instanceof Promise) { return (Promise<T>) stage; } if (stage instanceof CompletableFuture) { return new CompletablePromise<>((CompletableFuture<T>)stage); } final CompletablePromise<T> result = createLinkedPromise(stage); stage.whenComplete(handler(result::onSuccess, result::onError)); return result; } static <T, R> Promise<R> from(CompletionStage<T> stage, Function<? super T, ? extends R> resultConverter, Function<? super Throwable, ? extends Throwable> errorConverter) { final CompletablePromise<R> result = createLinkedPromise(stage); stage.whenComplete(handler( acceptConverted(result::onSuccess, resultConverter), acceptConverted(result::onError, errorConverter) )); return result; } private static <T, R> CompletablePromise<R> createLinkedPromise(CompletionStage<T> stage) { return new CompletablePromise<R>() { @Override public boolean cancel(boolean mayInterruptIfRunning) { if (super.cancel(mayInterruptIfRunning)) { cancelPromise(stage, mayInterruptIfRunning); return true; } else { return false; } } }; } @SafeVarargs public static <T> Promise<List<T>> all(final CompletionStage<? extends T>... promises) { return atLeast(promises.length, 0, true, promises); } @SafeVarargs public static <T> Promise<T> any(final CompletionStage<? extends T>... promises) { return unwrap(atLeast(1, promises.length - 1, true, promises), false); } @SafeVarargs public static <T> Promise<T> anyStrict(final CompletionStage<? extends T>... promises) { return unwrap(atLeast(1, 0, true, promises), true); } @SafeVarargs public static <T> Promise<List<T>> atLeast(final int minResultsCount, final CompletionStage<? extends T>... promises) { return atLeast(minResultsCount, promises.length - minResultsCount, true, promises); } @SafeVarargs public static <T> Promise<List<T>> atLeastStrict(final int minResultsCount, final CompletionStage<? extends T>... promises) { return atLeast(minResultsCount, 0, true, promises); } @SafeVarargs public static <T> Promise<List<T>> atLeast(final int minResultsCount, final int maxErrorsCount, final boolean cancelRemaining, final CompletionStage<? extends T>... promises) { if (minResultsCount > promises.length) { throw new IllegalArgumentException( "The number of futures supplied is less than a number of futures to await"); } else if (minResultsCount == 0) { return readyValue(Collections.emptyList()); } else if (promises.length == 1) { return from(promises[0], Collections::singletonList, Function.<Throwable> identity()); } else { return new AggregatingPromise<>(minResultsCount, maxErrorsCount, cancelRemaining, promises); } } private static <T> Promise<T> unwrap(final CompletionStage<List<T>> original, final boolean unwrapException) { return from( original, c -> c.stream().filter(el -> null != el).findFirst().get(), unwrapException ? ex -> ex instanceof MultitargetException ? MultitargetException.class.cast(ex).getFirstException().get() : ex : Function.identity() ); } private static <T> BiConsumer<T, ? super Throwable> handler(Consumer<? super T> onResult, Consumer<? super Throwable> onError) { return (r, e) -> { if (null != e) { onError.accept(e); } else { try { onResult.accept(r); } catch (final Exception ex) { onError.accept(ex); } } }; } private static <T, U> Consumer<? super T> acceptConverted(Consumer<? super U> target, Function<? super T, ? extends U> converter) { return t -> target.accept(converter.apply(t)); } }
package dev.nowalk.services; import java.util.List; import dev.nowalk.models.Employee; import dev.nowalk.models.Event; import dev.nowalk.models.Request; import dev.nowalk.repositories.RequestRepo; public class RequestServicesImpl implements RequestServices { public RequestRepo rr; public RequestServicesImpl(RequestRepo rr) { this.rr = rr; } @Override public void addRequest(Request r) { rr.addRequest(r); } @Override public List<Request> getAllRequests() { return rr.getAllRequests(); } @Override public Request getRequestById(int id) { return rr.getRequest(id); } @Override public Request updateRequest(Request change) { return rr.updateRequest(change); } @Override public Request deleteRequest(Request r) { return rr.deleteRequest(r); } @Override public Request addEventToRequest(Request r, Event e) { r.setEvent(e); return r; } @Override public Request superRequestApproval(Request r) { r.setSuper_approval(true); return r = rr.updateRequest(r); } @Override public Request bencoRequestApproval(Request r) { r.setBen_co_approval(true); return r = rr.updateRequest(r); } @Override public Request depHeadRequestApproval(Request r) { r.setDep_head_approval(true); return r = rr.updateRequest(r); } @Override public Request setIsUrgent(Request r) { r.setIs_urgent(true); return r = rr.updateRequest(r); } @Override public Request getAllRequestsForEmployee(int id) { //get all requests //sort the ones which are per employee return null; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.innovaciones.reporte.serviceRest; import com.innovaciones.reporte.model.TipoVisita; import com.innovaciones.reporte.service.TipoVisitaService; import static com.innovaciones.reporte.util.Utilities.headers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * * @author pisama */ @RestController @RequestMapping("/tipoVisitaService") public class TipoVisitaServiceRest { @Autowired private TipoVisitaService tipoVisitaService; @RequestMapping(value = "/getAllTipoVisitas", method = RequestMethod.GET, produces = "application/json") public ResponseEntity<List<TipoVisita>> getAllTipoVisitas() { return new ResponseEntity<List<TipoVisita>>(tipoVisitaService.getAllTipoVisitas(), headers(), HttpStatus.OK); } @RequestMapping(value = "/getByTipo/{parametro}", method = RequestMethod.GET, produces = "application/json") public ResponseEntity<List<TipoVisita>> getAllTipoVisitas(@PathVariable("parametro") String tipo) { return new ResponseEntity<List<TipoVisita>>(tipoVisitaService.getByTipo(tipo), headers(), HttpStatus.OK); } }
package com.cs.tu.findrefactor.model; import java.util.ArrayList; import java.util.List; import CFG.AbstractNode; public class VarPath { private List<AbstractNode> nodePathList = new ArrayList<AbstractNode>(); public List<AbstractNode> getNodePathList() { return nodePathList; } }
/* * 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 comparc.Instruction; /** * * @author Danica */ public class WB { private String REG; private String value; private String HI; private String LO; public WB(String reg, String value, String hi, String lo) { this.REG = reg; this.value = value; this.HI = hi; this.LO = lo; } public String getREG() { return REG; } public void setREG(String REG) { this.REG = REG; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getHI() { return HI; } public void setHI(String HI) { this.HI = HI; } public String getLO() { return LO; } public void setLO(String LO) { this.LO = LO; } }
package Ch14; public class TreeS { public static void main(String[] args) { int[] arr = { 50, 30, 70, 15, 7, 62, 22, 35, 87, 31 }; TreeSort TS = new TreeSort(arr[0]); System.out.printf("정렬 전 : "); printArray(arr); TS.Sorting(arr); System.out.printf("정렬 후 : "); printArray(arr); } static void printArray(int arr[]) { for (int i = 0; i < arr.length ; i++) { System.out.print(arr[i] + " "); } System.out.println(); } } class Node { int value; Node left; Node right; Node (int value) { this.value = value; left = null; right = null; } } class TreeSort { Node node; TreeSort(int value) { node = new Node(value); } int count = 0; public void Sorting(int arr[]) { for (int i = 0; i < arr.length; i++) { insertBST(node, arr[i]); } inOrder(node, arr); } public Node insertBST(Node node, int value) { if (node == null) { return new Node(value); } if (value < node.value) { node.left = insertBST(node.left, value); } else if (value > node.value) { node.right = insertBST(node.right, value); } return node; } public void inOrder(Node node, int arr[]) { if (node != null) { inOrder(node.left, arr); arr[count++] = node.value; inOrder(node.right, arr); } } }
package com.ecolife.ApirestEcolife.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; 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.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.ecolife.ApirestEcolife.models.Ecocliente; import com.ecolife.ApirestEcolife.models.Residuo; import com.ecolife.ApirestEcolife.repository.ResiduoRepository; @RestController @RequestMapping(value="/api") @CrossOrigin(origins="*") //Libera todos os dominios de acessar a API / ou coloca o link "http..." public class ResiduoResource { @Autowired ResiduoRepository residuoRepository; @GetMapping("/residuos") public List<Residuo> listaResiduos(){ return residuoRepository.findAll(); } @GetMapping("/residuos/{id}") public Residuo listaResiduoUnico(@PathVariable(value="id")long id){ return residuoRepository.findById(id); } @GetMapping("/residuos_cb/{codigoBarra}") public Residuo listaResiduoCodBarra(@PathVariable(value="codigoBarra")String codigoBarra){ return residuoRepository.findByCodigoBarras(codigoBarra); } @PostMapping("/residuo") public ResponseEntity<Residuo> salvaResiduo(@RequestBody Residuo residuo){ boolean ret = consultaResiduoExistente(residuo); if(ret == false){ Residuo novoEcoResiduo = residuoRepository.save(residuo); return ResponseEntity.ok(novoEcoResiduo); }else{ return ResponseEntity.badRequest().build(); } } @DeleteMapping("/residuo") public void DeletaResiduo(@RequestBody Residuo residuo){ residuoRepository.delete(residuo); } @PutMapping("/residuo") public Residuo AtualizaResiduo(@RequestBody Residuo residuo){ return residuoRepository.save(residuo); } public boolean consultaResiduoExistente(Residuo residuo){ Residuo eco = residuoRepository.findByCodigoBarras(residuo.getCodigoBarras()); if(eco == null){ return false; }else{ return true; } } }
package com.demo.observer.guava; import com.google.common.eventbus.Subscribe; /** * @author: Maniac Wen * @create: 2020/4/17 * @update: 7:29 * @version: V1.0 * @detail: **/ public class GuavaEventListener { @Subscribe public void subscribe(String str){ System.out.println("开始执行 subscribe 方法,传入的参数是:" + str); } }
package com.qst.chapter03; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; import android.widget.TextView; /** * RadioButton和RadioGroup的使用 */ public class RadioButtonActivity extends AppCompatActivity { private TextView chooseTxt; private RadioGroup radioGroup; private RadioButton radioButton1; private RadioButton radioButton2; private Button radioClearBtn; private Button radioAddBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.radiobutton_demo); chooseTxt = findViewById(R.id.chooseTxt); radioGroup = findViewById(R.id.radioGroup); radioButton1 = findViewById(R.id.radioButton1); radioButton2 = findViewById(R.id.radioButton2); radioClearBtn = findViewById(R.id.radio_clearBtn); radioAddBtn = findViewById(R.id.radio_addBtn); radioGroup.setOnCheckedChangeListener(onCheckedChangeListener); radioClearBtn.setOnClickListener(onClickListener); radioAddBtn.setOnClickListener(onClickListener); } private OnCheckedChangeListener onCheckedChangeListener = new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { int id = group.getCheckedRadioButtonId(); switch (id) { case R.id.radioButton1: chooseTxt.setText("我选择的是:" + radioButton1.getText()); break; case R.id.radioButton2: chooseTxt.setText("我选择的是:" + radioButton2.getText()); break; default: chooseTxt.setText("我选择的是:新增"); break; } } }; private OnClickListener onClickListener = new OnClickListener() { @Override public void onClick(View view) { switch (view.getId()) { case R.id.radio_clearBtn: radioGroup.check(-1); chooseTxt.setText("我选择的是...?"); break; case R.id.radio_addBtn: RadioButton newRadio = new RadioButton(RadioButtonActivity.this); newRadio.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); newRadio.setText("新增"); radioGroup.addView(newRadio, radioGroup.getChildCount()); break; } } }; }
package walnoot.dodgegame; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; public class Main{ public static void main(String[] args){ LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration(); cfg.title = "DodgeGame"; cfg.useGL20 = false; cfg.width = 960; cfg.height = 640; cfg.vSyncEnabled = false; new LwjglApplication(new DodgeGame(), cfg); } }
package com.vincent.algorithm.basic.array; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * leetcode 15 * 给你一个包含 n 个整数的数组nums,判断nums中是否存在三个元素 a,b,c ,使得a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。 * * 注意:答案中不可以包含重复的三元组。 * * * * 示例 1: * * 输入:nums = [-1,0,1,2,-1,-4] * 输出:[[-1,-1,2],[-1,0,1]] * 示例 2: * * 输入:nums = [] * 输出:[] * 示例 3: * * 输入:nums = [0] * 输出:[] * * * 提示: * * 0 <= nums.length <= 3000 * -105 <= nums[i] <= 105 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/3sum * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ public class ThreeSum { public static void main(String[] args) { int[] nums = {-1,0,1,2,-1,-4}; threeSum(nums); } /** 解题答案;极客时间的覃超,对这个问题有讲解 解题思路: 1.对数组按从小到大的顺序排序 2.从0开始Loop结果集 3.将数组分为还当前loop的变量,和剩余还未loop的数组两部分 4.由于还未loop的剩余部分也是有序的。从还未loop的数组的两端各找一个变量,跟当前迭代变量相加,看是否等于0 5.如果等于0返回,如果大于0,则将还未loop的数组右边的指针左移,由于数组是有序的,左移势必会减小三个数相加的结果 6.反之,则将将未loop数组的左指针右移, 7.如此循环 */ public static List<List<Integer>> threeSum(int[] nums) { if(nums.length == 0) { return new ArrayList<>(); } Arrays.sort(nums); List<List<Integer>> result = new ArrayList<>(); for(int i=0;i<nums.length;i++) { int j = i+1; int k = nums.length-1; while (j<k && j<nums.length ) { int sum = nums[i] + nums[k] + nums[j]; if(sum == 0) { List<Integer> tempResult = new ArrayList(); tempResult.add(nums[i]); tempResult.add(nums[j]); tempResult.add(nums[k]); result.add(tempResult); break;//这里一定要break,因为nums[i] 是确定的。那么nums[j]和nums[k]可能的组合也是确定,只是顺序不同而已,而我们要返回的结果不关心顺序,所以如果找到了组合。那么就跳出循环,进行笑一次查找 } else if(sum>0) { k--; } else { j++; } } } return result; } }
package star1; public class Star2App { static void main(String[] args) { Marine m = new Marine(); Dragoon d = new Dragoon("µå¶ó±º1", 100, 20); } }
package com.example.demo.myapplication; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.example.demo.myapplication.Components.Interface.DBCommunicator; public class RegistrationActivity extends AppCompatActivity implements DBCommunicator{ private Button mRegisterButton; private TextView mUsernameField, mPasswordField, mPassword2Field; private MainController mMainController; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registration); mRegisterButton = (Button)findViewById(R.id.register_button_registration); mUsernameField = (TextView)findViewById(R.id.register_edit_text_username); mPasswordField = (TextView)findViewById(R.id.register_edit_text_userpassword); mPassword2Field = (TextView)findViewById(R.id.register_edit_text_userpassword2); mMainController = new MainController(this); mRegisterButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String username = mUsernameField.getText().toString().trim(); String userpassword = mPasswordField.getText().toString().trim(); String userpassword2 = mPassword2Field.getText().toString().trim(); //Toast.makeText(getApplicationContext(),"username: " + username + "\n" + "password: " + userpassword,Toast.LENGTH_LONG).show(); if (username.isEmpty()) { Toast.makeText(getApplicationContext(),"Error: Username is missing",Toast.LENGTH_LONG).show(); } else if (userpassword.isEmpty()) { Toast.makeText(getApplicationContext(),"Error: Password is missing",Toast.LENGTH_LONG).show(); } else if (userpassword2.isEmpty()) { Toast.makeText(getApplicationContext(),"Error: Confirmed password is missing",Toast.LENGTH_LONG).show(); } else if (!userpassword.equals(userpassword2)) { Toast.makeText(getApplicationContext(),"Error: Unmatched Password",Toast.LENGTH_LONG).show(); } else { mMainController.register(username,userpassword); } } }); } public void onResultReceived(String text){ Toast.makeText(getApplicationContext(),"Register successfully with: " + text,Toast.LENGTH_LONG).show(); startActivity(new Intent(RegistrationActivity.this, HomeActivity.class)); finish(); } public void onErrorReceived(String text){ Toast.makeText(getApplicationContext(), "Error: " + "Username is being used already.", Toast.LENGTH_LONG).show(); } }
package com.najasoftware.fdv.model; import java.io.Serializable; /** * Created by Lemoel Marques - NajaSoftware on 17/03/2016. * lemoel@gmail.com */ public class ConfigFtp implements Serializable { private String login; private String senha; private String host; private int porta; public ConfigFtp(String login, String senha, String host, int porta) { this.login = login; this.senha = senha; this.host = host; this.porta = porta; } public ConfigFtp() {} public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPorta() { return porta; } public void setPorta(int porta) { this.porta = porta; } }
package BrazilCenter.DaoUtils.dao; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import BrazilCenter.DaoUtils.Utils.LogUtils; import BrazilCenter.DaoUtils.Utils.Utils; import BrazilCenter.DaoUtils.model.FKT_DPS01_IIG_L31_STP; import BrazilCenter.DaoUtils.model.SZT_ISM01_DNP_L01_30M; import BrazilCenter.DaoUtils.persistence.BrazilCenterDAOServiceImpl; import BrazilCenter.DaoUtils.storeDataService.StoreDataService; import BrazilCenter.models.FileObj; /** * * * * @author maful * */ public class Storager { private String rootDir; private BrazilCenterDAOServiceImpl BrazilCenterDaoService; public Storager() { this.BrazilCenterDaoService = new BrazilCenterDAOServiceImpl(); } public String getRootDir() { return rootDir; } public void setRootDir(String rootDir) { this.rootDir = rootDir; } /** */ private boolean StoreIntoDB(String fullName) { File file = new File(fullName); String filePath = fullName.substring(0, fullName.lastIndexOf(File.separator)); String fileName = fullName.substring(fullName.lastIndexOf(File.separator) + 1); String curTime = (new SimpleDateFormat(Utils.dateFormat24)).format(new Date()).toString(); String[] infolist = fileName.split("_"); if (infolist.length == 6) { String dataTime = infolist[5].substring(0, infolist[5].indexOf('.')); String tableName = infolist[0] + '_' + infolist[1] + '_' + infolist[2] + '_' + infolist[3] + '_' + infolist[4]; if (fullName.contains("FKT_DPS01_IIG_L31_STP")) { FKT_DPS01_IIG_L31_STP obj = new FKT_DPS01_IIG_L31_STP(); obj.setFileName(fileName); obj.setFilePath(filePath); obj.setDataTime(dataTime); obj.setFileSize(file.length()); obj.setInTime(new Date()); this.BrazilCenterDaoService.getFTK_DPS01_IIG_L31_STP_DAO().insertOrUpdate(obj); } else if (fullName.contains("SZT_ISM01_DNP_L01_30M")) { SZT_ISM01_DNP_L01_30M obj = new SZT_ISM01_DNP_L01_30M(); obj.setFileName(fileName); obj.setFilePath(filePath); obj.setDataTime(dataTime); obj.setFileSize(file.length()); obj.setInTime(new Date()); this.BrazilCenterDaoService.getSZT_ISM01_DNP_L01_30M_DA0().insertOrUpdate(obj); } else { } } return true; } /*** * (1) store the data into the file system (2) store the data information * into the database * * @param fileobj * @param rootDir */ public void Store(FileObj fileobj, String rootDir) { /** 1. store into the file system. */ String storeFileNameWithPath = StoreDataService.storeData(fileobj, rootDir); /** 2. store into the database. */ if (storeFileNameWithPath != null) { if (this.StoreIntoDB(storeFileNameWithPath) == false) { } } else { LogUtils.logger.error("Failed to store the data into filesystem : " + fileobj.getName()); } } }
package com.example.service.impl; import com.example.service.WeatherService; import org.springframework.stereotype.Component; /** * Created by bartosz on 15.03.17. */ @Component public class CuteWeatherServImpl implements WeatherService{ @Override public String getWeather() { return "It's shiny weather!"; } }
package com.example.weatherforcastproject.repository.network; import com.example.weatherforcastproject.pojo.forecast.ForecastFiveDays; import com.example.weatherforcastproject.pojo.weather.WeatherPojo; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; // http://api.openweathermap.org/data/2.5/weather?id=112931&units=metric&APPID=70224ba51fd21c4b9ff96c4ad7e2288c //http://api.openweathermap.org/data/2.5/forecast?q=tehran&units=metric&APPID=70224ba51fd21c4b9ff96c4ad7e2288c public interface RetrofitInterface { @GET("weather") Call<WeatherPojo> getWeatherByName(@Query("q") String cityName, @Query("units") String unit, @Query("APPID") String APPID); @GET("weather") Call<WeatherPojo> getWeatherById(@Query("id") int id, @Query("units") String unit, @Query("APPID") String APPID); @GET("forecast") Call<ForecastFiveDays> getForecastByName(@Query("q") String cityName, @Query("units") String unit, @Query("APPID") String APPID); @GET("forecast") Call<ForecastFiveDays> getForecastById(@Query("id") int id, @Query("units") String unit, @Query("APPID") String APPID); }