text
stringlengths
10
2.72M
/* * Copyright (C) 2015 Adrien Guille <adrien.guille@univ-lyon2.fr> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package main.java.fr.ericlab.sondy.core.structures; import edu.stanford.nlp.ling.CoreAnnotations; import edu.stanford.nlp.ling.CoreAnnotations.LemmaAnnotation; import edu.stanford.nlp.ling.CoreAnnotations.SentencesAnnotation; import edu.stanford.nlp.ling.CoreAnnotations.TokensAnnotation; import edu.stanford.nlp.ling.CoreLabel; import edu.stanford.nlp.pipeline.Annotation; import edu.stanford.nlp.pipeline.StanfordCoreNLP; import edu.stanford.nlp.util.CoreMap; import java.io.BufferedReader; import java.io.BufferedWriter; import main.java.fr.ericlab.sondy.core.app.Configuration; import main.java.fr.ericlab.sondy.core.text.index.GlobalIndexer; import main.java.fr.ericlab.sondy.core.text.nlp.ArabicStemming; import main.java.fr.ericlab.sondy.core.text.nlp.PersianStemming; import main.java.fr.ericlab.sondy.core.utils.PropertiesFileUtils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.ObjectInputStream; import java.nio.file.Path; import java.nio.file.Paths; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import main.java.fr.ericlab.sondy.core.text.index.Tokenizer; import main.java.fr.ericlab.sondy.core.text.nlp.EnglishStemming; import main.java.fr.ericlab.sondy.core.text.nlp.FrenchStemming; import main.java.fr.ericlab.sondy.core.utils.ArrayUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.io.LineIterator; import org.apache.commons.lang3.StringUtils; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; /** * * @author Adrien GUILLE, Laboratoire ERIC, Université Lumière Lyon 2 * @author Farrokh GHAMSARY */ public class Corpus { // Properties public int messageCount; public int authorCount; public Date start; public Date end; public Path path; // Preprocessed corpus public String preprocessing = ""; public int timeSliceLength; public int[] messageDistribution; public short[][] termFrequencies; public ArrayList<String> vocabulary; public short[][] termMentionFrequencies; public ArrayList<String> mentionVocabulary; public String[] splitString(String str) { return str.split("\t"); } public void loadProperties(Path p) { try { path = p; String propertiesFilePath = Paths.get(path+File.separator+"messages.properties").toString(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); messageCount = Integer.parseInt(PropertiesFileUtils.readProperty(propertiesFilePath, "messageCount")); authorCount = Integer.parseInt(PropertiesFileUtils.readProperty(propertiesFilePath, "authorCount")); start = dateFormat.parse(PropertiesFileUtils.readProperty(propertiesFilePath, "start")); end = dateFormat.parse(PropertiesFileUtils.readProperty(propertiesFilePath, "end")); preprocessing = ""; messageDistribution = null; termFrequencies = null; vocabulary = null; } catch (ParseException ex) { Logger.getLogger(Corpus.class.getName()).log(Level.SEVERE, null, ex); } } public String create(String id, String csvFilePath) { File dir = Paths.get(Configuration.datasets.toString() + File.separator + id).toFile(); int skippedLineCount = 0; try { Properties properties = new Properties(); HashSet<String> authors = new HashSet<>(); Date minDate = null, maxDate = null; BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(csvFilePath))); messageCount = 0; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String line; String firstLine = bufferedReader.readLine(); String[] components = splitString(firstLine); while (components.length != 3 && (firstLine = bufferedReader.readLine()) != null) { components = splitString(firstLine); skippedLineCount++; } if (components.length == 3) { authors.add(components[0]); Date parsedDate = dateFormat.parse(components[1]); minDate = maxDate = parsedDate; File messages = new File(dir.getAbsolutePath() + File.separator + "messages.csv"); FileUtils.write(messages, ""); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(messages)); bufferedWriter.write(firstLine); bufferedWriter.newLine(); while ((line = bufferedReader.readLine()) != null) { components = splitString(line); if (components.length == 3) { authors.add(components[0]); parsedDate = dateFormat.parse(components[1]); if (parsedDate.before(minDate)) { minDate = parsedDate; } else { if (parsedDate.after(maxDate)) { maxDate = parsedDate; } } messageCount++; bufferedWriter.write(line); bufferedWriter.newLine(); } else { skippedLineCount++; } } bufferedWriter.close(); } bufferedReader.close(); properties.setProperty("messageCount", messageCount+""); properties.setProperty("authorCount", authors.size()+""); properties.setProperty("start", dateFormat.format(minDate)); properties.setProperty("end", dateFormat.format(maxDate)); PropertiesFileUtils.saveProperties(Paths.get(Configuration.datasets + File.separator + id + File.separator + "messages.properties").toString(),properties); } catch (IOException | ParseException ex) { Logger.getLogger(Corpus.class.getName()).log(Level.SEVERE, null, ex); } return "Messages: done (imported "+messageCount+" messages, skipped "+skippedLineCount+" misformatted lines)."; } public void lemmatize(Path path) { try { LineIterator lineIterator = FileUtils.lineIterator(new File(path.toString()+File.separator+"messages.csv")); Properties props = new Properties(); props.put("annotators", "tokenize,ssplit,parse,lemma"); StanfordCoreNLP pipeline = new StanfordCoreNLP(props); Annotation annotation; File lemmatizedFile = new File(path.toString()+File.separator+"lemmatized_messages.csv"); BufferedWriter bwLemmatizedFile = new BufferedWriter(new FileWriter(lemmatizedFile, true)); while(lineIterator.hasNext()){ String[] components = splitString(lineIterator.nextLine()); String text = components[2]; annotation = new Annotation(text); String lemmatizedText = ""; pipeline.annotate(annotation); List<CoreMap> lem = annotation.get(CoreAnnotations.SentencesAnnotation.class); for(CoreMap l: lem) { for (CoreLabel token: l.get(CoreAnnotations.TokensAnnotation.class)) { lemmatizedText += token.get(CoreAnnotations.LemmaAnnotation.class)+" "; } } if(text.contains("@")){ lemmatizedText += " @"; } bwLemmatizedFile.write(components[0]+"\t"+components[1]+"\t"+lemmatizedText+"\n"); } bwLemmatizedFile.close(); } catch (IOException ex) { Logger.getLogger(Corpus.class.getName()).log(Level.SEVERE, null, ex); } } public String preprocess(Path path,String stemming, String lemmatization, int ngram, int timeSliceLength){ Path preprocessPath = Paths.get(path+File.separator+stemming+"-"+lemmatization+"-"+ngram+"-"+timeSliceLength); preprocessPath.normalize(); File dir = preprocessPath.toFile(); File sourceFile = new File(path.toString()+File.separator+"messages.csv"); if(lemmatization.equals("English")){ File lemmatizedFile = new File(path.toString()+File.separator+"lemmatized_messages.csv"); if(!lemmatizedFile.exists()){ lemmatize(path); } sourceFile = lemmatizedFile; } if(!dir.exists()){ try { dir.mkdir(); BufferedReader bufferedReader = new BufferedReader(new FileReader(sourceFile)); BufferedWriter bwText = null, bwTime = null, bwAuthor = null; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); long startTime = start.getTime(); NumberFormat formatter = new DecimalFormat("00000000"); Analyzer analyzer = new StandardAnalyzer(); String line; int timeSlice = -1; while ((line = bufferedReader.readLine()) != null) { String[] components = splitString(line); Date parsedDate = dateFormat.parse(components[1]); double diff = (parsedDate.getTime() - startTime) / (60 * 1000); if (timeSlice != (int) (diff / timeSliceLength)) { timeSlice = (int) (diff / timeSliceLength); if (bwText != null) { bwText.close(); } File fileText = new File(preprocessPath + File.separator + formatter.format(timeSlice) + ".text"); if (!fileText.exists()) { FileUtils.write(fileText, ""); } bwText = new BufferedWriter(new FileWriter(fileText, true)); if (bwTime != null) { bwTime.close(); } File fileTime = new File(preprocessPath + File.separator + formatter.format(timeSlice) + ".time"); if (!fileTime.exists()) { FileUtils.write(fileText, ""); } bwTime = new BufferedWriter(new FileWriter(fileTime, true)); if (bwAuthor != null) { bwAuthor.close(); } File fileAuthor = new File(preprocessPath + File.separator + formatter.format(timeSlice) + ".author"); if (!fileAuthor.exists()) { FileUtils.write(fileAuthor, ""); } bwAuthor = new BufferedWriter(new FileWriter(fileAuthor, true)); } String text = components[2]; if (!stemming.equals("disabled")) { String newText = ""; List<String> tokenList = Tokenizer.tokenizeString(analyzer, text); switch (stemming) { case "French": FrenchStemming frenchStemming = new FrenchStemming(); for (String token : tokenList) newText += frenchStemming.stem(token) + " "; break; case "Arabic": ArabicStemming arabicStemming = new ArabicStemming(); for (String token : tokenList) newText += arabicStemming.stem(token) + " "; break; case "Persian": PersianStemming persianStemming = new PersianStemming(); for (String token : tokenList) newText += persianStemming.stem(token) + " "; break; case "English": EnglishStemming englishStemming = new EnglishStemming(); for (String token : tokenList) newText += englishStemming.stem(token) + " "; default: break; } text = newText; } if (ngram > 1) { String newText = ""; List<String> tokenList = Tokenizer.tokenizeString(analyzer, text); for (int token = 0; token < tokenList.size() - 1 - ngram; token++) { for (int n = 0; n < ngram; n++) { newText += tokenList.get(token + n); if (n == ngram - 1) { newText += " "; } else { newText += "_"; } } } text = newText; } bwText.write(text); bwText.newLine(); bwTime.write(components[1]); bwTime.newLine(); bwAuthor.write(components[0]); bwAuthor.newLine(); } bwText.close(); bwTime.close(); bwAuthor.close(); bufferedReader.close(); GlobalIndexer indexer = new GlobalIndexer(Configuration.numberOfCores, false); indexer.index(preprocessPath.toString()); indexer = new GlobalIndexer(Configuration.numberOfCores, true); indexer.index(preprocessPath.toString()); return "Done."; } catch (IOException | ParseException | InterruptedException ex) { Logger.getLogger(Corpus.class.getName()).log(Level.SEVERE, null, ex); } } return "Error:"; } public void loadFrequencies(String preprocessedCorpus){ preprocessing = preprocessedCorpus; FileInputStream fisMatrix = null; try { setTimeSliceLength(); fisMatrix = new FileInputStream(path+File.separator+preprocessing+File.separator+"indexes/frequencyMatrix.dat"); ObjectInputStream oisMatrix = new ObjectInputStream(fisMatrix); termFrequencies = (short[][]) oisMatrix.readObject(); FileInputStream fisVocabulary = new FileInputStream(path+File.separator+preprocessing+File.separator+"indexes/vocabulary.dat"); ObjectInputStream oisVocabulary = new ObjectInputStream(fisVocabulary); vocabulary = (ArrayList<String>) oisVocabulary.readObject(); FileInputStream fisDistribution = new FileInputStream(path+File.separator+preprocessing+File.separator+"indexes/messageCountDistribution.dat"); ObjectInputStream oisDistribution = new ObjectInputStream(fisDistribution); messageDistribution = (int[]) oisDistribution.readObject(); } catch (FileNotFoundException ex) { Logger.getLogger(Corpus.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException | ClassNotFoundException ex) { Logger.getLogger(Corpus.class.getName()).log(Level.SEVERE, null, ex); } finally { try { fisMatrix.close(); } catch (IOException ex) { Logger.getLogger(Corpus.class.getName()).log(Level.SEVERE, null, ex); } } } public void loadMentionFrequencies(){ FileInputStream fisMatrix = null; try { setTimeSliceLength(); fisMatrix = new FileInputStream(path+File.separator+preprocessing+File.separator+"indexes/mentionFrequencyMatrix.dat"); ObjectInputStream oisMatrix = new ObjectInputStream(fisMatrix); termMentionFrequencies = (short[][]) oisMatrix.readObject(); FileInputStream fisVocabulary = new FileInputStream(path+File.separator+preprocessing+File.separator+"indexes/mentionVocabulary.dat"); ObjectInputStream oisVocabulary = new ObjectInputStream(fisVocabulary); mentionVocabulary = (ArrayList<String>) oisVocabulary.readObject(); } catch (FileNotFoundException ex) { Logger.getLogger(Corpus.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException | ClassNotFoundException ex) { Logger.getLogger(Corpus.class.getName()).log(Level.SEVERE, null, ex); } finally { try { fisMatrix.close(); } catch (IOException ex) { Logger.getLogger(Corpus.class.getName()).log(Level.SEVERE, null, ex); } } } public short[] getTermFrequency(String term){ int i = vocabulary.indexOf(term); return termFrequencies[i]; } public short[] getTermMentionFrequency(String term){ int i = mentionVocabulary.indexOf(term); return termMentionFrequencies[i]; } public String getMessages(String term, int timeSliceA, int timeSliceB){ String messages = ""; NumberFormat formatter = new DecimalFormat("00000000"); for(int i = timeSliceA; i <= timeSliceB; i++){ try { File textFile = new File(path+File.separator+preprocessing+File.separator+formatter.format(i)+".text"); List<String> lines = FileUtils.readLines(textFile); for(String line : lines){ if(StringUtils.containsIgnoreCase(line,term)){ messages += line+"\n"; } } } catch (IOException ex) { Logger.getLogger(Corpus.class.getName()).log(Level.SEVERE, null, ex); } } return messages; } public ObservableList<Message> getMessages(Event event){ ObservableList<Message> messages = FXCollections.observableArrayList(); String[] interval = event.getTemporalDescription().split(","); int timeSliceA = convertDayToTimeSlice(Double.parseDouble(interval[0])); int timeSliceB = convertDayToTimeSlice(Double.parseDouble(interval[1])); String term = event.getTextualDescription().split(" ")[0]; NumberFormat formatter = new DecimalFormat("00000000"); for(int i = timeSliceA; i <= timeSliceB; i++){ try { File textFile = new File(path+File.separator+preprocessing+File.separator+formatter.format(i)+".text"); File timeFile = new File(path+File.separator+preprocessing+File.separator+formatter.format(i)+".time"); File authorFile = new File(path+File.separator+preprocessing+File.separator+formatter.format(i)+".author"); LineIterator textIter = FileUtils.lineIterator(textFile); LineIterator timeIter = FileUtils.lineIterator(timeFile); LineIterator authorIter = FileUtils.lineIterator(authorFile); while(textIter.hasNext()){ String text = textIter.nextLine(); String author = authorIter.nextLine(); String time = timeIter.nextLine(); if(StringUtils.containsIgnoreCase(text,term)){ messages.add(new Message(author,time,text)); } } } catch (IOException ex) { Logger.getLogger(Corpus.class.getName()).log(Level.SEVERE, null, ex); } } return messages; } public ObservableList<Message> getFilteredMessages(Event event, String[] words, int operator){ ObservableList<Message> messages = FXCollections.observableArrayList(); String[] interval = event.getTemporalDescription().split(","); int timeSliceA = convertDayToTimeSlice(Double.parseDouble(interval[0])); int timeSliceB = convertDayToTimeSlice(Double.parseDouble(interval[1])); String term = event.getTextualDescription().split(" ")[0]; NumberFormat formatter = new DecimalFormat("00000000"); for(int i = timeSliceA; i <= timeSliceB; i++){ try { File textFile = new File(path+File.separator+preprocessing+File.separator+formatter.format(i)+".text"); File timeFile = new File(path+File.separator+preprocessing+File.separator+formatter.format(i)+".time"); File authorFile = new File(path+File.separator+preprocessing+File.separator+formatter.format(i)+".author"); LineIterator textIter = FileUtils.lineIterator(textFile); LineIterator timeIter = FileUtils.lineIterator(timeFile); LineIterator authorIter = FileUtils.lineIterator(authorFile); while(textIter.hasNext()){ String text = textIter.nextLine(); short[] test = new short[words.length]; for(int j = 0; j < words.length; j++){ if(StringUtils.containsIgnoreCase(text,words[j])){ test[j] = 1; }else{ test[j] = 0; } } if(StringUtils.containsIgnoreCase(text,term)){ int testSum = ArrayUtils.sum(test, 0, test.length-1); String author = authorIter.nextLine(); String time = timeIter.nextLine(); if(operator==0 && testSum == test.length){ messages.add(new Message(author,time,text)); } if(operator==1 && testSum > 0){ messages.add(new Message(author,time,text)); } } } } catch (IOException ex) { Logger.getLogger(Corpus.class.getName()).log(Level.SEVERE, null, ex); } } return messages; } public ObservableList<Message> getMessages(String user){ ObservableList<Message> messages = FXCollections.observableArrayList(); try { File messagesFile = new File(path.toString() + File.separator + "messages.csv"); LineIterator lineIterator = FileUtils.lineIterator(messagesFile); while (lineIterator.hasNext()) { String line = lineIterator.nextLine(); String[] components = splitString(line); if(components[0].equals(user)){ messages.add(new Message(components[0],components[1],components[2])); } } return messages; } catch (IOException ex) { Logger.getLogger(Corpus.class.getName()).log(Level.SEVERE, null, ex); } return messages; } public HashSet<String> getAuthors(Event event){ HashSet<String> authors = new HashSet<>(); String[] interval = event.getTemporalDescription().split(","); int timeSliceA = convertDayToTimeSlice(Double.parseDouble(interval[0])); int timeSliceB = convertDayToTimeSlice(Double.parseDouble(interval[1])); String term = event.getTextualDescription().split(" ")[0]; NumberFormat formatter = new DecimalFormat("00000000"); for(int i = timeSliceA; i <= timeSliceB; i++){ try { File textFile = new File(path+File.separator+preprocessing+File.separator+formatter.format(i)+".text"); File authorFile = new File(path+File.separator+preprocessing+File.separator+formatter.format(i)+".author"); LineIterator textIter = FileUtils.lineIterator(textFile); LineIterator authorIter = FileUtils.lineIterator(authorFile); while(textIter.hasNext()){ String text = textIter.nextLine(); String author = authorIter.nextLine(); if(text.contains(term)){ authors.add(author); } } } catch (IOException ex) { Logger.getLogger(Corpus.class.getName()).log(Level.SEVERE, null, ex); } } return authors; } public int getNumberOfTermsInTimeSlice(int timeSlice){ int count = 0; try { NumberFormat formatter = new DecimalFormat("00000000"); List<String> lines = FileUtils.readLines(new File(path+File.separator+preprocessing+File.separator+formatter.format(timeSlice)+".text")); for(String line : lines){ for(int i = 0; i < line.length(); i++) if(Character.isWhitespace(line.charAt(i))) count++; count++; } } catch (IOException ex) { Logger.getLogger(Corpus.class.getName()).log(Level.SEVERE, null, ex); } return count; } public void setTimeSliceLength(){ String[] components = preprocessing.split("-"); timeSliceLength = Integer.parseInt(components[3]); } public double convertTimeSliceToDay(int timeSlice){ double norm = (((double)timeSliceLength)/60.0)/24.0; return ((double)timeSlice) * norm; } public int convertDayToTimeSlice(double day){ double norm = 24*60/(double)timeSliceLength; int timeSlice = (int) Math.round(day * norm); return timeSlice; } public double getLength(){ return (end.getTime() - start.getTime())/(1000*60*60*24L)+1; } }
package com.tdr.registrationv3.bean; /** * 按钮跳转对象 * */ public class ItemModel { private String rolePower;//权限编号 private String itemName;//该Item的名字 private int itemBitResc;//本地图片资源 private int size;//指令条数 public String getRolePower() { return rolePower; } public void setRolePower(String rolePower) { this.rolePower = rolePower; } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public int getItemBitResc() { return itemBitResc; } public void setItemBitResc(int itemBitResc) { this.itemBitResc = itemBitResc; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } }
package com.example.dolly0920.item5; public interface Car { public void start(); public void accelerate(); public void slowdown(); public void stop(); }
public class name { public static void main(String[] args ){ String text = "Hello World!"; System.out.println(text); double doubleNum = 7000000000.; float floautNum = 213020f; boolean boolOne = true; boolean boolTwo = false; int apple = 1; if (apple == 1){ System.out.println("I have one apple"); } } }
package myGame; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.JLayeredPane; import javax.swing.JPanel; public class DeathScreen extends JPanel{ /** * */ private static final long serialVersionUID = 1L; private WriteScors WS = new WriteScors(); private JLayeredPane screenDead; private String path; private boolean deathSound=true; private BufferedImage deathS = null; private long savedTime = System.currentTimeMillis(); private boolean startTimer=true; public void paint(Graphics g) { if(Main.SreenSize==1){path = "small";} else if(Main.SreenSize==2){path = "big";} screenDead = new JLayeredPane(); if(deathSound && !Window.MUTE){Sound.DEAD.play();deathSound=false;} if(startTimer){savedTime = System.currentTimeMillis();startTimer=false;} try { if(Window.dead){ if(System.currentTimeMillis() > savedTime+850) deathS = ImageIO.read(new File("image/"+path+"/deathSreen/1.png")); else if(System.currentTimeMillis() > savedTime+800) deathS = ImageIO.read(new File("image/"+path+"/deathSreen/2.png")); else if(System.currentTimeMillis() > savedTime+750) deathS = ImageIO.read(new File("image/"+path+"/deathSreen/3.png")); else if(System.currentTimeMillis() > savedTime+700) deathS = ImageIO.read(new File("image/"+path+"/deathSreen/4.png")); else if(System.currentTimeMillis() > savedTime+250) deathS = ImageIO.read(new File("image/"+path+"/deathSreen/5.png")); else if(System.currentTimeMillis() > savedTime+200) deathS = ImageIO.read(new File("image/"+path+"/deathSreen/4.png")); else if(System.currentTimeMillis() > savedTime+150) deathS = ImageIO.read(new File("image/"+path+"/deathSreen/3.png")); else if(System.currentTimeMillis() > savedTime+100) deathS = ImageIO.read(new File("image/"+path+"/deathSreen/2.png")); else if(System.currentTimeMillis() > savedTime+50) deathS = ImageIO.read(new File("image/"+path+"/deathSreen/1.png")); if(System.currentTimeMillis() > savedTime+900){startTimer=true;Window.dead=false;deathSound=true;deathS=null;WS.AddScore(0,0,1);} } } catch (IOException e) { } if(Window.dead){ if(deathS!=null)deathS.getGraphics(); if(deathS!=null)g.drawImage(deathS,0, 0, screenDead); } } }
package com.anderson.pontointeligente.api.entities; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.SequenceGenerator; import javax.persistence.Table; @Entity @Table(name = "empresa") @SequenceGenerator(name = "sq_empresa", sequenceName = "sq_empresa", allocationSize = 1) public class Empresa { private Long id; private String razaoSocial; private String cnpj; private Date dataCriacao; private Date dataAtualização; private List<Funcionario> funcionarios = new ArrayList<Funcionario>(); public Empresa() { } public Empresa(String cnpj, String razaoSocial) { this.cnpj = cnpj; this.razaoSocial = razaoSocial; } @Id @GeneratedValue(strategy = GenerationType.AUTO, generator = "sq_empresa") public Long getId() { return id; } @Column(name = "razao_social", nullable = false) public String getRazaoSocial() { return razaoSocial; } @Column(nullable = false, unique = true) public String getCnpj() { return cnpj; } @Column(name = "data_criacao", nullable = false) public Date getDataCriacao() { return dataCriacao; } @Column(name = "data_atualizacao") public Date getDataAtualização() { return dataAtualização; } @OneToMany(mappedBy = "empresa", fetch = FetchType.LAZY, cascade = CascadeType.ALL) public List<Funcionario> getFuncionarios() { return funcionarios; } public void setId(Long id) { this.id = id; } public void setRazaoSocial(String razaoSocial) { this.razaoSocial = razaoSocial; } public void setCnpj(String cnpj) { this.cnpj = cnpj; } public void setDataCriacao(Date dataCriacao) { this.dataCriacao = dataCriacao; } public void setDataAtualização(Date dataAtualização) { this.dataAtualização = dataAtualização; } public void setFuncionarios(List<Funcionario> funcionarios) { this.funcionarios = funcionarios; } @PreUpdate public void preUpdate() { dataAtualização = new Date(); } @PrePersist public void prePersist() { dataCriacao = new Date(); } @Override public String toString() { return "Empresa [id=" + id + ", razaoSocial=" + razaoSocial + ", cnpj=" + cnpj + ", dataCriacao=" + dataCriacao + ", dataAtualização=" + dataAtualização + "]"; } }
package com.test; import java.util.ArrayDeque; import java.util.HashMap; import java.util.HashSet; import com.test.base.Solution; /** * 构建一个图,超时 * * @author YLine * * 2019年10月15日 下午9:11:53 */ public class SolutionA implements Solution { @Override public int numBusesToDestination(int[][] routes, int S, int T) { if (S == T) { return 0; } // 构造点时间的图,距离为1的为相互关联 Graph graph = new Graph(); for (int i = 0; i < routes.length; i++) { graph.buildByRoutes(routes[i]); } // bfs直接遍历 ArrayDeque<Integer> queue = new ArrayDeque<>(); queue.add(S); // 缓存,key - value的距离 HashMap<Integer, Integer> cacheMap = new HashMap<>(); cacheMap.put(S, 0); while (!queue.isEmpty()) { Integer stop = queue.pollFirst(); int step = cacheMap.get(stop); HashSet<Integer> nextStopSet = graph.get(stop); // 空校验 if (null == nextStopSet || nextStopSet.isEmpty()) { continue; } // 已经找到 if (nextStopSet.contains(T)) { return step + 1; } // 加入下一个循环 for (Integer nextStop : nextStopSet) { // 已经添加过,则不重复添加 if (cacheMap.containsKey(nextStop)) { continue; } cacheMap.put(nextStop, step + 1); queue.add(nextStop); } } return -1; } public static class Graph { // 建立点 到 其他点的映射(自带防重) private HashMap<Integer, HashSet<Integer>> map; public Graph() { map = new HashMap<>(); } public HashSet<Integer> get(int key) { return map.get(key); } public void buildByRoutes(int[] array) { if (null == array || array.length < 2) { return; } for (int i = 0; i < array.length; i++) { for (int j = i + 1; j < array.length; j++) { add(array[i], array[j]); } } } private void add(int stopA, int stopB) { HashSet<Integer> aSet = map.get(stopA); if (null == aSet) { HashSet<Integer> newSet = new HashSet<>(); newSet.add(stopB); map.put(stopA, newSet); } else { aSet.add(stopB); } HashSet<Integer> bSet = map.get(stopB); if (null == bSet) { HashSet<Integer> newSet = new HashSet<>(); newSet.add(stopA); map.put(stopB, newSet); } else { bSet.add(stopA); } } } }
package br.com.branquinho.jpa.venda.web.controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import br.com.branquinho.jpa.venda.casosDeUso.VendaProduto; import br.com.branquinho.jpa.venda.casosDeUso.dto.NovaVendaForm; @RestController @RequestMapping("/api/venda") public class VendaController { private final VendaProduto vendaProduto; public VendaController(VendaProduto vendaProduto) { this.vendaProduto = vendaProduto; } @PostMapping public void criarVenda(@RequestBody NovaVendaForm form) { vendaProduto.criarVenda(form); } }
package com.example.gpssample; import java.util.LinkedList; import java.util.List; import android.app.Activity; import android.content.Context; import android.location.GpsSatellite; import android.location.GpsStatus; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.util.Log; import android.widget.TextView; public class MainActivity extends Activity { public static final String TAG = MainActivity.class.getName(); private static final long DURATION_TO_FIX_LOST_MS = 10000; private static final long MINIMUM_UPDATE_TIME = 0; private static final float MINIMUM_UPDATE_DISTANCE = 0.0f; private LocationManager locationManager; private MyGpsListener gpsListener; private TextView latitudeText; private TextView longitudeText; private TextView qualityText; private TextView satsTotal; private TextView satsUsed; private boolean gpsEnabled; private boolean gpsFix; private double latitude; private double longitude; private int satellitesTotal; private int satellitesUsed; private float accuracy; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); latitudeText = (TextView) findViewById(R.id.latitudeText); longitudeText = (TextView) findViewById(R.id.longitudeText); qualityText = (TextView) findViewById(R.id.qualityText); satsTotal = (TextView) findViewById(R.id.satsTotalText); satsUsed = (TextView) findViewById(R.id.satsUsedText); } @Override protected void onResume() { super.onResume(); // ask Android for the GPS service locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // make a delegate to receive callbacks gpsListener = new MyGpsListener(); // ask for updates on the GPS status locationManager.addGpsStatusListener(gpsListener); // ask for updates on the GPS location locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MINIMUM_UPDATE_TIME, MINIMUM_UPDATE_DISTANCE, gpsListener); } @Override protected void onPause() { super.onPause(); if (locationManager != null) { // remove the delegates to stop the GPS locationManager.removeGpsStatusListener(gpsListener); locationManager.removeUpdates(gpsListener); locationManager = null; } } private void updateView() { // update all data in the UI latitudeText.setText(Double.toString(latitude)); longitudeText.setText(Double.toString(longitude)); qualityText.setText(getGrade()); satsTotal.setText(Integer.toString(satellitesTotal)); satsUsed.setText(Integer.toString(satellitesUsed)); } private String getGrade() { if (!gpsEnabled) { return "Disabled"; } if (!gpsFix) { return "Waiting for Fix"; } if (accuracy <= 10) { return "Good"; } if (accuracy <= 30) { return "Fair"; } if (accuracy <= 100) { return "Bad"; } return "Unusable"; } protected class MyGpsListener implements GpsStatus.Listener, LocationListener { // the last location time is needed to determine if a fix has been lost private long locationTime = 0; private List<Float> rollingAverageData = new LinkedList<Float>(); @Override public void onGpsStatusChanged(int changeType) { if (locationManager != null) { // status changed so ask what the change was GpsStatus status = locationManager.getGpsStatus(null); switch(changeType) { case GpsStatus.GPS_EVENT_FIRST_FIX: gpsEnabled = true; gpsFix = true; break; case GpsStatus.GPS_EVENT_SATELLITE_STATUS: gpsEnabled = true; // if it has been more then 10 seconds since the last update, consider the fix lost gpsFix = System.currentTimeMillis() - locationTime < DURATION_TO_FIX_LOST_MS; break; case GpsStatus.GPS_EVENT_STARTED: // GPS turned on gpsEnabled = true; gpsFix = false; break; case GpsStatus.GPS_EVENT_STOPPED: // GPS turned off gpsEnabled = false; gpsFix = false; break; default: Log.w(TAG, "unknown GpsStatus event type. "+changeType); return; } // number of satellites, not useful, but cool int newSatTotal = 0; int newSatUsed = 0; for(GpsSatellite sat : status.getSatellites()) { newSatTotal++; if (sat.usedInFix()) { newSatUsed++; } } satellitesTotal = newSatTotal; satellitesUsed = newSatUsed; updateView(); } } @Override public void onLocationChanged(Location location) { locationTime = location.getTime(); latitude = location.getLatitude(); longitude = location.getLongitude(); if (location.hasAccuracy()) { // rolling average of accuracy so "Signal Quality" is not erratic updateRollingAverage(location.getAccuracy()); } updateView(); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { /* dont need this info */ } @Override public void onProviderEnabled(String provider) { /* dont need this info */ } @Override public void onProviderDisabled(String provider) { /* dont need this info */ } private void updateRollingAverage(float value) { // does a simple rolling average rollingAverageData.add(value); if (rollingAverageData.size() > 10) { rollingAverageData.remove(0); } float average = 0.0f; for(Float number : rollingAverageData) { average += number; } average = average / rollingAverageData.size(); accuracy = average; } } }
package GUIVentti; import javax.swing.JFrame; import javax.swing.JOptionPane; public class Pelaaja { private Korttipakka pelaajanKasi; private String pelaajanNimi; private int pelaajanPisteet; private boolean onTalo, onVentti; public Pelaaja(String nimi, boolean onkoTalo) { this.pelaajanKasi = new Korttipakka(); this.pelaajanNimi=nimi; this.pelaajanPisteet = 0; this.onTalo = onkoTalo; this.onVentti = false; } private int assaKysely() { Object[] arvot = {1, 14}; JFrame frame = new JFrame(); int s = (Integer) JOptionPane.showInputDialog(frame, "Valitse ässän arvo", "Ässän arvo", JOptionPane.QUESTION_MESSAGE, null, arvot, arvot[0]); return s; } public void otaKortti(Korttipakka pakka) { int korttiIndeksi = (int) (Math.random()*pakka.getSize()); this.pelaajanKasi.addKortti(pakka.getKortti(korttiIndeksi)); if (pakka.getKortti(korttiIndeksi).getMaa().contains("ässä")) { // jos ässä, kysy onko ässä arvoltaan 1 vai 14 if (!this.onTalo) { this.pelaajanPisteet += assaKysely(); // pelaaja päättää ässän arvon } else { this.pelaajanPisteet++; // talolle ässä on 1 } } else { this.pelaajanPisteet += pakka.getKortti(korttiIndeksi).getArvo(); } pakka.poistaKortti(korttiIndeksi); } public String tulostaKasi() { String kasi = ""; if (this.pelaajanKasi.getSize() == 0) { kasi += "Käsi on tyhjä"; } else { for (int i = 0; i < this.pelaajanKasi.getSize(); i++) { kasi += this.pelaajanKasi.getKortti(i).getMaa()+" "; } } return kasi; } public int getPisteet() { return this.pelaajanPisteet; } public String getNimi() { return this.pelaajanNimi; } public boolean onTalo() { return this.onTalo; } public void nollaa() { this.pelaajanPisteet=0; this.onVentti=false; this.pelaajanKasi.nollaa(); } public int kadenKoko() { return this.pelaajanKasi.getSize(); } public void saaVentin() { this.onVentti=true; } public boolean Ventti() { return this.onVentti; } }
package com.zeal.common.utils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * Created by zeal on 2017/4/7. */ public class DateUtils { public static String getWeek(long date) { SimpleDateFormat sdf = new SimpleDateFormat("u"); String s = sdf.format(new Date(date)); return s; } public static String getDay(long date) { SimpleDateFormat sdf = new SimpleDateFormat("d"); String s = sdf.format(new Date(date)); return (Integer.parseInt(s) ) + ""; } //2017-02-01 21:00 public static String getDay(String date) { try { SimpleDateFormat sdf = new SimpleDateFormat("d"); Date parse = sdf.parse(date); String s = sdf.format(parse); return (Integer.parseInt(s) + 1) + ""; } catch (Exception e) { e.printStackTrace(); return ""; } } public static String getMonthAndDay(long date) { try { SimpleDateFormat sdf = new SimpleDateFormat("M月d日"); return sdf.format(new Date(date)); } catch (Exception e) { e.printStackTrace(); return ""; } } public static String getYearMonthAndDay(long date) { try { SimpleDateFormat sdf = new SimpleDateFormat("Y年M月d日"); return sdf.format(new Date(date)); } catch (Exception e) { e.printStackTrace(); return ""; } } public static String getYearMonthAndDayAndHourMiniteSecond(long date) { try { SimpleDateFormat sdf = new SimpleDateFormat("Y年M月d日 H:m:s"); return sdf.format(new Date(date)); } catch (Exception e) { e.printStackTrace(); return ""; } } public static String getMonth(long date) { SimpleDateFormat sdf = new SimpleDateFormat("M"); String s = sdf.format(new Date(date)); return s; } public static String getHourAndMinute(long date) { SimpleDateFormat sdf = new SimpleDateFormat("H:m"); String s = sdf.format(new Date(date)); return s; } public static String getTodoListDateTemplate(long date) { SimpleDateFormat sdf = new SimpleDateFormat("H:m\nM/d"); String s = sdf.format(new Date(date)); return s; } public static String getTodoListDateTemplate(String date) { SimpleDateFormat sdf = new SimpleDateFormat("H:m"); Date parse = null; try { parse = sdf.parse(date); } catch (ParseException e) { e.printStackTrace(); } String s = sdf.format(parse); return s; } public static long getDateMillis(int year, int month, int date) { Calendar calendar = Calendar.getInstance(); calendar.set(year, month, date); long millis = calendar.getTimeInMillis(); return millis; } public static long getDateMillis(int year, int month, int date, int hourOfDay, int minute, int second) { Calendar calendar = Calendar.getInstance(); calendar.set(year, month, date, hourOfDay, minute, second); long millis = calendar.getTimeInMillis(); return millis; } public static String getYearMonth(long date) { try { SimpleDateFormat sdf = new SimpleDateFormat("Y.M"); return sdf.format(new Date(date)); } catch (Exception e) { e.printStackTrace(); return ""; } } }
package com.utils; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @作者 张剑 * @版本 1.1 * @日期 2014年8月16日 * @时间 下午2:15:59 */ public final class ZJ_ValiCodeUtils { // 产生多少字符 private static final int SIZE = 4; // 干扰线数量 private static final int LINES = 12; // 图片宽 private static final int WIDTH = 120; // 图片高 private static final int HEIGHT = 40; // 字体大小 private static final int FONT_SIZE = 30; private static String getRandomStr() { String randomString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String str2 = randomString.toLowerCase(); randomString += str2; StringBuffer sb = new StringBuffer(); Random ran = new Random(); // 画随机字符 for (int i = 1; i <= SIZE; i++) { int r = ran.nextInt(randomString.length()); sb.append(randomString.charAt(r)); } return sb.toString(); } private static float getRandomFloat(float min, float max) { return (float) (min + (max - min) * Math.random()); } private static Color getRandomColor(float min, float max) { Random ran = new Random(); float a = getRandomFloat(min, max); Color color = new Color(ran.nextFloat(), ran.nextFloat(), ran.nextFloat(), a); return color; } /** * 干扰字符 * * @param graphic */ private static void setZifu(Graphics graphic) { Random ran = new Random(); for (int i = 1; i <= LINES; i++) { graphic.setColor(getRandomColor(0.1f, 0.2f)); graphic.setFont(new Font("Consolas", Font.BOLD + Font.ROMAN_BASELINE, 40)); int x1 = ran.nextInt(WIDTH); int y1 = ran.nextInt(WIDTH); graphic.drawString(getRandomStr(), x1, y1); } } /** * 干扰线 * * @param graphic */ @SuppressWarnings("unused") private static void setLine(Graphics graphic) { Random ran = new Random(); for (int i = 1; i <= LINES; i++) { graphic.setColor(getRandomColor(0.1f, 0.2f)); graphic.setFont(new Font("Consolas", Font.BOLD + Font.ROMAN_BASELINE, 40)); int x1 = ran.nextInt(WIDTH); int y1 = ran.nextInt(WIDTH); int x2 = x1 + ran.nextInt(20) - 20; int y2 = y1 + ran.nextInt(20) - 20; graphic.drawLine(x1, y1, x2, y2); } } public static void createImage(HttpServletRequest request, HttpServletResponse response) { BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics graphic = image.getGraphics(); graphic.setColor(Color.WHITE); graphic.setFont(new Font("Consolas", Font.ITALIC, FONT_SIZE)); graphic.fillRect(0, 0, WIDTH, HEIGHT); String randomStr = getRandomStr(); // 画干扰线 setZifu(graphic); // 画随机字符 for (int i = 1; i <= SIZE; i++) { graphic.setColor(getRandomColor(0.6f, 1.0f)); graphic.setFont(new Font("Consolas", Font.BOLD + Font.ROMAN_BASELINE, FONT_SIZE)); graphic.drawString(randomStr.charAt(i - 1) + "", (i - 1) * WIDTH / SIZE, FONT_SIZE); } try { response.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片 response.setHeader("Pragma", "No-cache");// 设置响应头信息,告诉浏览器不要缓存此内容 response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expire", 0); ImageIO.write(image, "JPEG", response.getOutputStream()); request.getSession().setAttribute("valicode", randomStr); } catch (Exception e) { } } }
package Arrays; public class Merge2SortedArr { public static void main(String[] args) { ArrayOperation ao = ArrayOperation.getInstance(); int[] a=ao.readElement(); System.out.println("Entered first sorted array elements are: "); ao.dispArr(a); int[] b=ao.readElement(); System.out.println("Entered second sorted array elements are: "); ao.dispArr(b); int[] c = ao.merge2SotredArr(a, b); System.out.println("Array after merging 2 sorted array"); ao.dispArr(c); } }
package test; import java.util.HashMap; import br.ufrgs.MASBench.Entity; import br.ufrgs.MASBench.NodeID; import br.ufrgs.MASBench.TickDampedCommunicationAdapter; import br.ufrgs.MASBench.BinaryMaxSum.Factor.SelectorFactor; import br.ufrgs.MASBench.BinaryMaxSum.Factor.WeightingFactor; import br.ufrgs.MASBench.Solver.Operator.Minimize; public class testAlgo { public static void main(String[] args) { TickDampedCommunicationAdapter instance = new TickDampedCommunicationAdapter(); instance.tick(); SelectorFactor<NodeID> s1 = new SelectorFactor<NodeID>(); NodeID me = new NodeID(new Entity(1),null,null); NodeID task1 = new NodeID(null, new Entity(10), null); NodeID task2 = new NodeID(null, new Entity(2), null); NodeID task3 = new NodeID(null, new Entity(3), null); WeightingFactor<NodeID> potential = new WeightingFactor<NodeID>(s1); potential.addNeighbor(task1); potential.setPotential(task1, 10.0); potential.addNeighbor(task2); potential.setPotential(task2, 12.0); potential.addNeighbor(task3); potential.setPotential(task3, 10.8); potential.setCommunicationAdapter(instance); potential.setIdentity(me); potential.setMaxOperator(new Minimize()); s1.run(); System.out.println(s1.select().toString()); HashMap<NodeID, Boolean> m = new HashMap<>(); m.put(task1, false); m.put(task2, true); m.put(task3, false); System.out.println(potential.evaluate(m)); } }
package com.capstone.kidinvest.models; import javax.persistence.*; import java.sql.Timestamp; import java.util.List; @Entity @Table(name = "stocks") public class Stock { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(nullable = false) private String name; @Column(nullable = false) private String ticker; @Column(name = "market_price", nullable = false) private double marketPrice; @Column(name = "open_price", nullable = false) private double openPrice; @Column(name = "low_price", nullable = false) private double lowPrice; @Column(name = "high_price", nullable = false) private double highPrice; @Column(name = "year_low_price", nullable = false) private double yearLowPrice; @Column(name = "year_high_price", nullable = false) private double yearHighPrice; @Column(name = "percentage_change", nullable = false) private double change; @Column(nullable = false) private Timestamp time; @OneToMany(cascade = CascadeType.ALL, mappedBy = "stock") private List<StockTransaction> transactionList; @OneToMany(cascade = CascadeType.ALL, mappedBy = "stock") private List<UserStock> userStockList; // Defualt Constructor public Stock() { } //Constructor public Stock(long id, String name, String ticker, double marketPrice, double openPrice, double lowPrice, double highPrice, double yearLowPrice, double yearHighPrice, Timestamp time) { this.id = id; this.name = name; this.ticker = ticker; this.marketPrice = marketPrice; this.openPrice = openPrice; this.lowPrice = lowPrice; this.highPrice = highPrice; this.yearLowPrice = yearLowPrice; this.yearHighPrice = yearHighPrice; this.time = time; } public Stock(double marketPrice, double openPrice, double lowPrice, double highPrice, double yearLowPrice, double yearHighPrice) { this.marketPrice = marketPrice; this.openPrice = openPrice; this.lowPrice = lowPrice; this.highPrice = highPrice; this.yearLowPrice = yearLowPrice; this.yearHighPrice = yearHighPrice; } public Stock(double marketPrice, double openPrice, double lowPrice, double highPrice) { this.marketPrice = marketPrice; this.openPrice = openPrice; this.lowPrice = lowPrice; this.highPrice = highPrice; } // Getters public long getId() { return this.id; } public String getName() { return this.name; } public String getTicker(){ return this.ticker; } public double getMarketPrice() { return this.marketPrice; } public double getOpenPrice() { return this.openPrice; } public double getLowPrice() { return this.lowPrice; } public double getHighPrice() { return this.highPrice; } public double getYearLowPrice() { return this.yearLowPrice; } public double getYearHighPrice() { return this.yearHighPrice; } public Timestamp getTime() { return this.time; } // Setters public void setId(long id) { this.id = id; } public void setName(String name) { this.name = name; } public void setTicker(String ticker) { this.ticker = ticker; } public void setMarketPrice(double marketPrice) { this.marketPrice = marketPrice; } public void setOpenPrice(double openPrice) { this.openPrice = openPrice; } public void setLowPrice(double lowPrice) { this.lowPrice = lowPrice; } public void setHighPrice(double highPrice) { this.highPrice = highPrice; } public void setYearLowPrice(double yearLowPrice) { this.yearLowPrice = yearLowPrice; } public void setYearHighPrice(double yearHighPrice) { this.yearHighPrice = yearHighPrice; } public void setTime(Timestamp time) { this.time = time; } public double getChange() { return change; } public void setChange(double change) { this.change = change; } public List<StockTransaction> getTransactionList() { return transactionList; } public void setTransactionList(List<StockTransaction> transactionList) { this.transactionList = transactionList; } public List<UserStock> getUserStockList() { return userStockList; } public void setUserStockList(List<UserStock> userStockList) { this.userStockList = userStockList; } }
package com.example.chordnote.di.module; import android.content.Context; import androidx.appcompat.app.AppCompatActivity; import com.example.chordnote.data.DataManager; import com.example.chordnote.di.ActivityContext; import com.example.chordnote.ui.booklist.BookListPresenter; import com.example.chordnote.ui.booklist.BookListPresenterImpl; import com.example.chordnote.ui.booklist.BookListView; import com.example.chordnote.ui.collectcomments.CollectCommentPresenter; import com.example.chordnote.ui.collectcomments.CollectCommentPresenterImpl; import com.example.chordnote.ui.collectcomments.CollectCommentView; import com.example.chordnote.ui.collectdynamics.CollectDynamicPresenter; import com.example.chordnote.ui.collectdynamics.CollectDynamicPresenterImpl; import com.example.chordnote.ui.collectdynamics.CollectDynamicView; import com.example.chordnote.ui.login.LoginPresenter; import com.example.chordnote.ui.login.LoginPresenterImpl; import com.example.chordnote.ui.login.LoginView; import com.example.chordnote.ui.main.discover.DiscoverPresenter; import com.example.chordnote.ui.main.discover.DiscoverPresenterImpl; import com.example.chordnote.ui.main.discover.DiscoverView; import com.example.chordnote.ui.main.me.MePresenter; import com.example.chordnote.ui.main.me.MePresenterImpl; import com.example.chordnote.ui.main.me.MeView; import com.example.chordnote.ui.main.study.StudyPresenter; import com.example.chordnote.ui.main.study.StudyPresenterImpl; import com.example.chordnote.ui.main.study.StudyView; import com.example.chordnote.ui.mydynamics.MyDynamicPresenter; import com.example.chordnote.ui.mydynamics.MyDynamicPresenterImpl; import com.example.chordnote.ui.mydynamics.MyDynamicView; import com.example.chordnote.ui.period.PeriodPresenter; import com.example.chordnote.ui.period.PeriodPresenterImpl; import com.example.chordnote.ui.period.PeriodView; import com.example.chordnote.ui.period.comment.CommentPresenter; import com.example.chordnote.ui.period.comment.CommentPresenterImpl; import com.example.chordnote.ui.period.comment.CommentView; import com.example.chordnote.ui.period.periodcontent.PeriodContentPresenter; import com.example.chordnote.ui.period.periodcontent.PeriodContentPresenterImpl; import com.example.chordnote.ui.period.periodcontent.PeriodContentView; import com.example.chordnote.ui.period.question.QuestionPresenter; import com.example.chordnote.ui.period.question.QuestionPresenterImpl; import com.example.chordnote.ui.period.question.QuestionView; import com.example.chordnote.ui.register.RegisterPresenter; import com.example.chordnote.ui.register.RegisterPresenterImpl; import com.example.chordnote.ui.register.RegisterView; import com.example.chordnote.ui.splash.SplashPresenter; import com.example.chordnote.ui.splash.SplashPresenterImpl; import com.example.chordnote.ui.splash.SplashView; import com.example.chordnote.ui.userinfo.UserInfoPresenter; import com.example.chordnote.ui.userinfo.UserInfoPresenterImpl; import com.example.chordnote.ui.userinfo.UserInfoView; import dagger.Module; import dagger.Provides; @Module public class ActivityModule { private AppCompatActivity mActivity; public ActivityModule(AppCompatActivity activity) { mActivity = activity; } @Provides SplashPresenter<SplashView> provideSplashPresenter(DataManager manager) { return new SplashPresenterImpl<>(manager); } @Provides RegisterPresenter<RegisterView> provideRegisterPresenter(DataManager manager) { return new RegisterPresenterImpl<>(manager); } @Provides LoginPresenter<LoginView> provideLoginPresenter(DataManager manager) { return new LoginPresenterImpl<>(manager); } @Provides MePresenter<MeView> provideMePresenter(DataManager manager) { return new MePresenterImpl<>(manager); } @Provides StudyPresenter<StudyView> provideStudyPresenter(DataManager manager) { return new StudyPresenterImpl<>(manager); } @Provides UserInfoPresenter<UserInfoView> provideUserInfoPresenter(@ActivityContext Context context, DataManager manager) { return new UserInfoPresenterImpl<>(context, manager); } @Provides DiscoverPresenter<DiscoverView> provideDiscoverPresenter(DataManager manager){ return new DiscoverPresenterImpl<>(manager); } @Provides PeriodPresenter<PeriodView> providePeriodPresenter(DataManager manager){ return new PeriodPresenterImpl<>(manager); } @Provides CollectDynamicPresenter<CollectDynamicView> provideCollectDynamicPresenter(DataManager manager){ return new CollectDynamicPresenterImpl<>(manager); } @Provides MyDynamicPresenter<MyDynamicView> provideMyDynamicPresenter(DataManager manager){ return new MyDynamicPresenterImpl<>(manager); } @Provides BookListPresenter<BookListView> provideBookListPresenter(DataManager manager){ return new BookListPresenterImpl<>(manager); } @Provides PeriodContentPresenter<PeriodContentView> providePeriodContentPresenter(DataManager manager){ return new PeriodContentPresenterImpl<>(manager); } @Provides CommentPresenter<CommentView> provideCommentPresenter(DataManager manager){ return new CommentPresenterImpl<>(manager); } @Provides QuestionPresenter<QuestionView> provideQuestionPresenter(DataManager manager){ return new QuestionPresenterImpl<>(manager); } @Provides CollectCommentPresenter<CollectCommentView> provideCollectCommentPresenter(DataManager manager){ return new CollectCommentPresenterImpl<>(manager); } @Provides @ActivityContext Context provideActivityContext() { return mActivity; } }
/******************************************************************************* * Copyright 2014 See AUTHORS file. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 dk.sidereal.lumm.architecture; import java.util.ArrayList; import java.util.List; import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.Game; import com.badlogic.gdx.Input; import com.badlogic.gdx.utils.ObjectMap; import dk.sidereal.lumm.architecture.core.Assets; import dk.sidereal.lumm.architecture.core.Debug; import dk.sidereal.lumm.architecture.core.Net; import dk.sidereal.lumm.architecture.core.Debug.Log; import dk.sidereal.lumm.util.LummException; /** * The main settings of the Game made with Lumm. Has to be passed to * {@link Lumm} in the {@link Lumm#Lumm(LummScene, LummConfiguration)} * constructor. If the {@link LummConfiguration} passed is null, the constructor * will create a new instance of {@link LummConfiguration}, holding the default * values to variables. * <p> * Adding additional variables in future versions will by default make the * framework behave as before they were added, thus this class will be safe to * update from the git server. * * @author Claudiu Bele */ public class LummConfiguration { // region fields /** * List of modules to add to {@link Lumm} when an instance of * {@link LummConfiguration} is passed to the constructor. Elements should * be added using {@link #addModule(LummModule)}. */ final List<Class<? extends LummModule>> modules; /** List of parameters that modules can use in order to be customized. */ private final ObjectMap<String, Object> parameters; /** * Whether debugging can be toggled on or off in the application. In * {@link Lumm#create()} the value will be applied to {@link Lumm#debug}. */ public boolean debugEnabled; /** The root path to all data related to the app. */ public String rootDataPath; /** * Whether the application is an executable or not (false by default). * Affects the root path for loading assets, so people responsible with * graphics can change them and start the app to see changes instead of * assets being loaded from the jar file * <p> * If value is set to true, files will be taken using * {@link FileType#Classpath} ( from the executable ), otherwise * {@link FileType#Internal} will be used, files being handled at a location * relative to the executable. * <p> * * @see Assets#getFileType() returns the FileType used in importing tied to * the application * @see Assets#getResolver() */ public boolean isExecutable; /** * Whether to prioritise external storage when saving data or not, if the * device allows. */ public boolean prioritiseExternalStorage; /** Initial scene to be displayed after the game is loaded */ public LummScene initialScene; /** Names of input processors to use in {@link Input} */ public String[] inputProcessorNames; /** * Whether to run the app in background if possible ( depends on platform ). * Internally, it will affect whether {@link Game#pause()} * {@link Game#resume()} are called when the app goes into background */ public boolean runInBackground; /** * The app key to be used for LNet authentication. L-Net can save logs, * crashes and facilitate server-client TCP socket communication */ public String applicationLNetKey; /** If set to true, the LNet session will be started as soon as possible. Otherwise {@link Net#startLNet()} has to be explicitly called * */ public boolean startLNetSessionOnStartup; /** * App version. Will be used in LNet. If the version is not set L-Net * functionality will not work. */ public String applicationVersion; /** * Whether to call {@link Debug#startLog(String)} as soon as * {@link Lumm#debug} is initialized. Is set to false by default. If set to * true, a log will be started with logtype {@link Log#LOG_ALL }. */ public boolean startDebugLogOnStartup; /** Whether to use the LNet when ending a log, the data being sent to the server afterwards * */ public boolean useLNetOnFinishLogListener; // endregion fields // region constructors public LummConfiguration() { inputProcessorNames = new String[]{"Default"}; debugEnabled = true; prioritiseExternalStorage = false; isExecutable = false; rootDataPath = "Lumm app"; parameters = new ObjectMap<String, Object>(); modules = new ArrayList<Class<? extends LummModule>>(); runInBackground = false; startDebugLogOnStartup = false; } /** * Adds a module to the list of modules available in the game. Modules can * also be added at runtime using {@link Lumm#addModule(Object)}. * <p> * The module will be accessible from game scenes, batches, objects and * behaviors through {@link Lumm#getModule(Class)}. * * @param module * @return */ public LummConfiguration addModule(Class<? extends LummModule> module) { if (module == null) throw new NullPointerException("LummConfiguration.addModule parameter 'module' of type Module is null"); if (modules.contains(module)) throw new LummException("LummConfiguration.addModule parameter type " + module.getClass() + " is already in the list of modules"); modules.add(module); return this; } public <T extends Object> LummConfiguration addModuleParameter(String key, T value) { if (key == null) throw new LummException("Attempted to add module parameter while key was null"); parameters.put(key, value); return this; } public Object getModuleParameter(String key) { return parameters.get(key); } // endregion }
package br.com.webscraping.b3; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class WebscrappingB3ApiApplication { public static void main(String[] args) { SpringApplication.run(WebscrappingB3ApiApplication.class, args); } @Bean public WebDriver webDriver() { System.setProperty("webdriver.gecko.driver","C:\\Users\\vinic\\Documents\\workspace-spring-tool-suite-4-4.2.1.RELEASE\\webscrapping-b3-api\\src\\test\\resources\\geckodriver.exe"); return new FirefoxDriver(); } }
package com.example.customer.entity; public enum RoleName { ROLE_ADMINISTRATOR, ROLE_USER }
package Graph.Utilities; import Graph.Structure.Node; /** * Created by Jok3r on 13.01.2017. */ public class Constants { public static final int SIZE_MULTIPLIKATOR = 7; public static final int FRAME_SIZE_X = 155 * SIZE_MULTIPLIKATOR; public static final int FRAME_SIZE_Y = 100 * SIZE_MULTIPLIKATOR; public static final int PANEL_LEFT_MENU_SIZE_X = 45 * SIZE_MULTIPLIKATOR; public static final int PANEL_LEFT_MENU_SIZE_Y = FRAME_SIZE_Y; public static final int PANEL_GRAPH_SIZE_X = FRAME_SIZE_X - PANEL_LEFT_MENU_SIZE_X; public static final int PANEL_GRAPH_SIZE_Y = FRAME_SIZE_Y; public static final int PANEL_STATUS_BAR_SIZE_X = FRAME_SIZE_X; public static final int PANEL_STATUS_BAR_SIZE_Y = 4 * SIZE_MULTIPLIKATOR; public static final int NODE_WIDTH = 25; public static final int NODE_HEIGHT = NODE_WIDTH; public static final int [] EDGE_FOUND_COLOR = { 25, 193, 14 }; public static final int [] EDGE_DEFAULT_COLOR = { 0, 0, 0 }; public static final int [] NODE_BRIDGE_COLOR = { 115, 225, 0 }; public static final int [] NODE_START_COLOR = { 255, 165, 0 }; public static final int [] NODE_NORMAL_COLOR = { 107, 107, 106 }; public enum NODE_TYPE { NODE_START, NODE_BRIDGE, NODE_NORMAL } public static final String ALGORITHM_DIJKSTRA = "Dijkstra"; public static final String ALGORITHM_MCST = "MCST"; public static final String ALGORITHM_DFS = "DFS"; public static final String [] ALGORITHMS = {ALGORITHM_MCST,ALGORITHM_DIJKSTRA,ALGORITHM_DFS}; public static final Node DEFAULT_NODE = new Node("-1",1337,1337); public static final double INFINITY = 999999; }
package com.energytrade.app.dto; import java.util.Date; import java.util.List; import com.energytrade.app.model.EventSetEventDto; public class AllEventSetDto extends AbstractBaseDto { private int eventSetId; private String eventSetName; private String eventSetStatus; private int userId; private String userName; private List<AllEventDto> allEvents; private String dateOfOccurence; private String plannedPower; private String actualPower; private String totalPrice; private String committedPower; public String getCommittedPower() { return committedPower; } public void setCommittedPower(String committedPower) { this.committedPower = committedPower; } public String getTotalPrice() { return totalPrice; } public void setTotalPrice(String totalPrice) { this.totalPrice = totalPrice; } private String publishedEvents; private String completedEvents; private String cancelledEvents; public Date createdTs; public List<EventSetEventDto> events; public Date getCreatedTs() { return createdTs; } public void setCreatedTs(Date createdTs) { this.createdTs = createdTs; } public List<AllEventDto> getAllEvents() { return allEvents; } public void setAllEvents(List<AllEventDto> allEvents) { this.allEvents = allEvents; } public int getEventSetId() { return eventSetId; } public String getDateOfOccurence() { return dateOfOccurence; } public void setDateOfOccurence(String dateOfOccurence) { this.dateOfOccurence = dateOfOccurence; } public String getPlannedPower() { return plannedPower; } public void setPlannedPower(String plannedPower) { this.plannedPower = plannedPower; } public String getActualPower() { return actualPower; } public void setActualPower(String actualPower) { this.actualPower = actualPower; } public String getPublishedEvents() { return publishedEvents; } public void setPublishedEvents(String publishedEvents) { this.publishedEvents = publishedEvents; } public String getCompletedEvents() { return completedEvents; } public void setCompletedEvents(String completedEvents) { this.completedEvents = completedEvents; } public String getCancelledEvents() { return cancelledEvents; } public void setCancelledEvents(String cancelledEvents) { this.cancelledEvents = cancelledEvents; } public void setEventSetId(int eventSetId) { this.eventSetId = eventSetId; } public String getEventSetName() { return eventSetName; } public void setEventSetName(String eventSetName) { this.eventSetName = eventSetName; } public String getEventSetStatus() { return eventSetStatus; } public void setEventSetStatus(String eventSetStatus) { this.eventSetStatus = eventSetStatus; } public List<EventSetEventDto> getEvents() { return events; } public void setEvents(List<EventSetEventDto> events) { this.events = events; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } }
package com.ledongtech.test.druid; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; import com.alibaba.druid.pool.DruidDataSource; public class MySQLPool { private static MySQLPool instance; //???????? private static String jdbcUrl; //mysql???? private static String username; //mysql????? private static String password; //mysql???? private static String driverClassName; //mysql???? private static int initialSize; private static int maxActive; private static int minIdle; private static int maxWait; private static boolean poolPreparedStatements; private static int maxOpenPreparedStatements; private static boolean testWhileIdle; private static boolean defaultAutoCommit; // private DruidDataSource dataSource; public DruidDataSource dataSource; static { Properties prop = new Properties(); try { prop.load(MySQLPool.class.getClassLoader().getResourceAsStream("jdbc.properties")); jdbcUrl = prop.getProperty("druid.jdbcUrl"); username = prop.getProperty("druid.username"); password = prop.getProperty("druid.password"); driverClassName = prop.getProperty("druid.driverClassName"); initialSize = Integer.parseInt(prop.getProperty("druid.initialSize")); maxActive = Integer.parseInt(prop.getProperty("druid.maxActive")); minIdle = Integer.parseInt(prop.getProperty("druid.minIdle")); maxWait = Integer.parseInt(prop.getProperty("druid.maxWait")); poolPreparedStatements = Boolean.parseBoolean(prop.getProperty("druid.poolPreparedStatements")); maxOpenPreparedStatements = Integer.parseInt(prop.getProperty("druid.maxOpenPreparedStatements")); testWhileIdle = Boolean.parseBoolean(prop.getProperty("druid.testWhileIdle")); defaultAutoCommit = Boolean.parseBoolean(prop.getProperty("druid.defaultAutoCommit")); } catch (IOException e) { e.printStackTrace(); } } //?????JDBC???? MySQLPool() { //System.out.print("MySQLPool!\n"); dataSource = new DruidDataSource(); dataSource.setUrl(jdbcUrl); dataSource.setUsername(username); dataSource.setPassword(password); dataSource.setDriverClassName(driverClassName); dataSource.setInitialSize(initialSize); dataSource.setMaxActive(maxActive); dataSource.setMinIdle(minIdle); dataSource.setMaxWait(maxWait); dataSource.setPoolPreparedStatements(poolPreparedStatements); dataSource.setMaxOpenPreparedStatements(maxOpenPreparedStatements); dataSource.setTestWhileIdle(testWhileIdle); dataSource.setDefaultAutoCommit(defaultAutoCommit); } //?????? public static MySQLPool getInstance() { //System.out.print("getInstance!\n"); if (instance == null) { synchronized (MySQLPool.class) { if(instance == null) { instance = new MySQLPool(); } } } return instance; } //??????? public synchronized Connection getConnection() { //System.out.print("getConnection!\n"); try { return dataSource.getConnection(); } catch (SQLException e) { e.printStackTrace(); } return null; } //??????? public void releaseConnection(Connection conn) { //System.out.print("releaseConnection!\n"); try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
/* Copyright 2006 thor.jini.org Project 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. */ /* * thor : org.jini.projects.org.jini.projects.thor.service.constrainable * * * ThorServiceProxy.java * Created on 22-Dec-2003 * * ThorServiceProxy * */ package org.jini.projects.thor.service.constrainable; import java.io.Serializable; import java.rmi.RemoteException; import net.jini.core.constraint.MethodConstraints; import net.jini.core.constraint.RemoteMethodControl; import net.jini.id.Uuid; import org.jini.projects.thor.handlers.Branch; import org.jini.projects.thor.service.ThorSession; /** * @author calum */ public class ThorSessionProxy implements ThorSession, Serializable { public static final long serialVersionUID=15686868123423L; /** * */ final ThorSession backend; final Uuid ID; public static final ThorSession create(ThorSession server, Uuid id) { if (server instanceof RemoteMethodControl) { return new ThorSessionProxy.ConstrainableProxy(server, id, null); } else return new ThorSessionProxy(server, id); } private ThorSessionProxy(ThorSession backend, Uuid ID) { super(); this.backend = backend; this.ID = ID; // URGENT Complete constructor stub for ThorServiceProxy } final static class ConstrainableProxy extends ThorSessionProxy implements RemoteMethodControl{ private static final long serialVersionUID = 4L; private ConstrainableProxy(ThorSession server, Uuid id, MethodConstraints methodConstraints) { super(constrainServer(server,methodConstraints), id); //l.fine("Creating a secure proxy"); } public RemoteMethodControl setConstraints(MethodConstraints constraints) { return new ThorSessionProxy.ConstrainableProxy(backend, ID, constraints); } /** {@inheritDoc} */ public MethodConstraints getConstraints() { return ((RemoteMethodControl) backend).getConstraints(); } private static ThorSession constrainServer(ThorSession server, MethodConstraints methodConstraints) { return (ThorSession) ((RemoteMethodControl)server).setConstraints(methodConstraints); } } /* @see org.jini.projects.thor.service.ThorSession#getRoot() */ public Branch getRoot() throws RemoteException { // TODO Complete method stub for getRoot return backend.getRoot(); } }
package ru.job4j.utils; import org.bouncycastle.crypto.generators.OpenBSDBCrypt; import org.springframework.security.crypto.password.PasswordEncoder; /** * Реализует кодировщик паролей с использованием алгоритма BCrypt. * @version 2019-08-01 * @since 2019-07-30 */ public class CustomBCryptPasswordEncoder implements PasswordEncoder { /** * Cost factor - логарифм итераций алгоритма. * Целое число в диапазоне > 3 && < 32. */ private final int costFactor; /** * Соль. Любой массив из 8 байтов. */ private final byte[] salt; /** * Конструктор. * @param salt соль (любой набор из 8 байтов). * @param costFactor логарифм итераций алгоритма. */ public CustomBCryptPasswordEncoder(byte[] salt, int costFactor) { this.costFactor = costFactor; this.salt = salt; } /** * Кодирует пароль. * @param rawPassword последовательность символов пароля. * @return хэш пароля. */ @Override public String encode(CharSequence rawPassword) { return OpenBSDBCrypt.generate(rawPassword.toString().toCharArray(), this.salt, this.costFactor); } /** * Проверяет соответствие хэшей целевого пароля и пороля из хранилица. * @param rawPassword целевой пароль для проверки. * @param encodedPassword хэш пароля из хранилища. * @return true если хэши паролей одинаковые. Иначе false. */ @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { return OpenBSDBCrypt.checkPassword(encodedPassword, rawPassword.toString().toCharArray()); } }
package kr.co.lifesolution.repository.mapper; import java.util.List; import kr.co.lifesolution.repository.domain.Staff; public interface StaffMapper { List<Staff> selectStaff(); }
/* * (C) Copyright 2011 Marvell International Ltd. * All Rights Reserved * * MARVELL CONFIDENTIAL * Copyright 2011 ~ 2014 Marvell International Ltd All Rights Reserved. * The source code contained or described herein and all documents related to * the source code ("Material") are owned by Marvell International Ltd or its * suppliers or licensors. Title to the Material remains with Marvell International Ltd * or its suppliers and licensors. The Material contains trade secrets and * proprietary and confidential information of Marvell or its suppliers and * licensors. The Material is protected by worldwide copyright and trade secret * laws and treaty provisions. No part of the Material may be used, copied, * reproduced, modified, published, uploaded, posted, transmitted, distributed, * or disclosed in any way without Marvell's prior express written permission. * * No license under any patent, copyright, trade secret or other intellectual * property right is granted to or conferred upon you by disclosure or delivery * of the Materials, either expressly, by implication, inducement, estoppel or * otherwise. Any license under such intellectual property rights must be * express and approved by Marvell in writing. * */ package com.marvell.networkinfo; import java.lang.String; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.Context; import android.content.Intent; import android.app.Service; import android.os.Binder; import android.os.IBinder; import android.util.Log; public class NetworkInfoService extends Service { public static final String TAG = "NetworkInfoService"; private static final String INFORM_UPDATE_BROADCAST="com.marvell.action.INFORM_UPDATE_BROADCAST"; public static native void start_ee_mode(); public native int query_ee_data(); public static native void stop_ee_mode(); public native int[] get_neighboring_cell(int type); public static native boolean lock_cell(int mode, int arfcn, int cellId); public native int[] get_reject_history(); public static boolean lock_result; //item 2g sub0 data public int item_2g_sub0_arfcn; public int item_2g_sub0_rl_timeout_v; public int item_2g_sub0_rxlev; public int item_2g_sub0_c1; public int item_2g_sub0_c2; public int item_gsm_edge_support; public int item_gsm_ci; public int item_gsm_bsic; public int item_2g_t3212; public static int item_reject_history[]; //10*2 //item 2g sub1 data public static int item_2g_sub1[]; //4*8 //item 2g sub2 data public static int item_2g_sub2[]; //5*8 //item 2g sub3 data public int item_2g_sub3_rxlevel_full; public int item_2g_sub3_rxlevel_sub; public int item_2g_sub3_rxqual_full; public int item_2g_sub3_rxqual_sub; public int item_2g_sub3_tx_power_level; //item 2g sub4 data public int item_2g_sub4_amr_ch; public int item_2g_sub4_channel_mode; //item 3g sub0 data public int item_3g_sub0_rcc_state; public int item_3g_sub0_s_freq; public int item_3g_sub0_s_psc; public int item_3g_sub0_s_ecio; public int item_3g_sub0_s_rscp; //item 3g sub1 data public static int item_3g_sub1[]; //4*32 //item 3g sub2 data public static int item_3g_sub2[]; //item nw sub0 data //public int item_nw_sub0_plmn; public int item_nw_sub0_mnc; public int item_nw_sub0_mcc; public int item_nw_sub0_lac; public int item_nw_sub0_rac; public int item_nw_sub0_hplmn; public int item_td_pid; public int item_3g_t3212; public int item_3g_tmsi; //item nw sub1 data public int item_nw_sub1_mm_state; public int item_nw_sub1_mm_reject; public int item_nw_sub1_gmm_state; public int item_nw_sub1_attach_reject; public int item_nw_sub1_rau_reject; //item nw sub2 data public int item_nw_sub2_ciphering; public int item_nw_sub2_UEA1; public int item_nw_sub2_GEA1; public int item_nw_sub2_GEA2; public int item_nw_sub2_A5_1; public int item_nw_sub2_A5_2; public int item_nw_sub2_A5_3; //flag public static final String ITEM_2G_SUB0_ARFCN = "ITEM_2G_SUB0_ARFCN"; public static final String ITEM_2G_SUB0_RL_Timeout_v = "ITEM_2G_SUB0_RL_Timeout_v"; public static final String ITEM_2G_SUB0_RXLEV = "TEM_2G_SUB0_RXLEV"; public static final String ITEM_2G_SUB0_C1 = "TEM_2G_SUB0_C1"; public static final String ITEM_2G_SUB0_C2 = "TEM_2G_SUB0_C2"; public static final String ITEM_GSM_EDGE_SUPPORT = "ITEM_GSM_EDGE_SUPPORT"; public static final String ITEM_GSM_CI = "ITEM_GSM_CI"; public static final String ITEM_GSM_BSIC = "ITEM_GSM_BSIC"; public static final String ITEM_2G_T3212 = "ITEM_2G_T3212"; // public static final String ITEM_2G_SUB3_RXLevel_Full = "TEM_2G_SUB2_RXLevel_Full"; public static final String ITEM_2G_SUB3_RXLevel_Sub = "ITEM_2G_SUB2_RXLevel_Sub"; public static final String ITEM_2G_SUB3_RXQual_Full = "ITEM_2G_SUB2_RXQual_Full"; public static final String ITEM_2G_SUB3_RXQual_Sub = "ITEM_2G_SUB2_RXQual_Sub"; public static final String ITEM_2G_SUB3_Tx_Power_Level = "ITEM_2G_SUB3_Tx_Power_Level"; public static final String ITEM_2G_SUB4_AMR_Ch = "ITEM_2G_SUB4_AMR_Ch"; public static final String ITEM_2G_SUB4_Channel_Mode = "ITEM_2G_SUB2_Channel_Mode"; public static final String ITEM_3G_SUB0_RRC_state = "ITEM_3G_SUB0_RRC_state"; public static final String ITEM_3G_SUB0_S_FREQ = "ITEM_3G_SUB0_S_FREQ"; public static final String ITEM_3G_SUB0_S_PSC = "ITEM_3G_SUB0_S_PSC"; public static final String ITEM_3G_SUB0_S_ECIO = "ITEM_3G_SUB0_S_ECIO"; public static final String ITEM_3G_SUB0_S_RSCP = "ITEM_3G_SUB0_S_RSCP"; // public static final String ITEM_NW_SUB0_PLMN = "ITEM_NW_SUB0_PLMN"; public static final String ITEM_NW_SUB0_LAC = "ITEM_NW_SUB0_LAC"; public static final String ITEM_NW_SUB0_RAC = "ITEM_NW_SUB0_RAC"; public static final String ITEM_NW_SUB0_HPLMN = "ITEM_NW_SUB0_HPLMN"; public static final String ITEM_NW_SUB0_MNC = "ITEM_NW_SUB0_MNC"; public static final String ITEM_NW_SUB0_MCC = "ITEM_NW_SUB0_MCC"; public static final String ITEM_TD_PID = "ITEM_TD_PID"; public static final String ITEM_3G_T3212 = "ITEM_3G_T3212"; public static final String ITEM_3G_TMSI = "ITEM_3G_TMSI"; //nw sub1 public static final String ITEM_NW_SUB1_MM_State = "ITEM_NW_SUB1_MM_Stat"; public static final String ITEM_NW_SUB1_MM_Reject = "ITEM_NW_SUB1_MM_Reject"; public static final String ITEM_NW_SUB1_GMM_State = "ITEM_NW_SUB1_GMM_State"; public static final String ITEM_NW_SUB1_Attach_Reject = "ITEM_NW_SUB1_Attach_Reject"; public static final String ITEM_NW_SUB1_RAU_Reject = "ITEM_NW_SUB1_RAU_Reject"; //nw sub2 public static final String ITEM_NW_SUB2_CIPHERING = "ITEM_NW_SUB2_CIPHERING"; public static final String ITEM_NW_SUB2_UEA1 = "ITEM_NW_SUB2_UEA1"; public static final String ITEM_NW_SUB2_GEA1 = "ITEM_NW_SUB2_GEA1"; public static final String ITEM_NW_SUB2_GEA2 = "ITEM_NW_SUB2_GEA2"; public static final String ITEM_NW_SUB2_A5_1 = "ITEM_NW_SUB2_A5_1"; public static final String ITEM_NW_SUB2_A5_2 = "ITEM_NW_SUB2_A5_2"; public static final String ITEM_NW_SUB2_A5_3 = "ITEM_NW_SUB2_A5_3"; static { System.loadLibrary("NetworkInfo"); } public void onCreate(){ Log.i(TAG, "onCreate called"); super.onCreate(); } public void onStart(Intent intent, int startId) { Log.d(TAG, "onStart called"); super.onStart(intent, startId); } public void onDestroy() { Log.d(TAG, "onDestroy called"); super.onDestroy(); } @Override public IBinder onBind(Intent intent) { Log.i(TAG, "onBind ~~~~~~~~~~~~"); return mBinder; } @Override public boolean onUnbind(Intent intent) { Log.d(TAG, "onUnbind ~~~~~~~~~~~"); return super.onUnbind(intent); } /** ** Class for clients to access. Because we know this service always ** runs in the same process as its clients, we don't need to deal with ** IPC. **/ public class NetworkInfoBinder extends Binder { NetworkInfoService getService() { return NetworkInfoService.this; } } private final IBinder mBinder = new NetworkInfoBinder(); private void update_ee_data_callback(){ Log.d(TAG, "update_ee_data_callback called"); //TODO: send intent broadcast to inform GUI update Intent informUpdate = new Intent(INFORM_UPDATE_BROADCAST); sendBroadcast(informUpdate); } public int query(){ int result = 0; item_2g_sub1 = get_neighboring_cell(0); //Log.d(TAG, "item_2g_sub1 length: " + item_2g_sub1.length ); item_2g_sub2 = get_neighboring_cell(1); //Log.d(TAG, "item_2g_sub2 length: " + item_2g_sub2.length ); item_3g_sub1 = get_neighboring_cell(2); //Log.d(TAG, "item_3g_sub1 length: " + item_3g_sub1.length ); item_3g_sub2 = get_neighboring_cell(3); //Log.d(TAG, "item_3g_sub2 length: " + item_3g_sub2.length ); item_reject_history = get_reject_history(); //Log.d(TAG, "item_reject_history length: " + item_reject_history.length); result = query_ee_data(); if(result == 0) { //write to shared preference for easy access SharedPreferences prefs = getSharedPreferences("NetworkInfo", Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE); Editor editor = prefs.edit(); editor.putInt(ITEM_2G_SUB0_ARFCN, item_2g_sub0_arfcn); editor.putInt(ITEM_2G_SUB0_C1, item_2g_sub0_c1); editor.putInt(ITEM_2G_SUB0_C2, item_2g_sub0_c2); editor.putInt(ITEM_2G_SUB0_RL_Timeout_v, item_2g_sub0_rl_timeout_v); editor.putInt(ITEM_2G_SUB0_RXLEV, item_2g_sub0_rxlev); editor.putInt(ITEM_GSM_EDGE_SUPPORT, item_gsm_edge_support); editor.putInt(ITEM_GSM_CI, item_gsm_ci); editor.putInt(ITEM_GSM_BSIC, item_gsm_bsic); editor.putInt(ITEM_2G_T3212, item_2g_t3212); // editor.putInt(ITEM_2G_SUB3_RXLevel_Full, item_2g_sub3_rxlevel_full); editor.putInt(ITEM_2G_SUB3_RXLevel_Sub, item_2g_sub3_rxlevel_sub); editor.putInt(ITEM_2G_SUB3_RXQual_Full, item_2g_sub3_rxqual_full); editor.putInt(ITEM_2G_SUB3_RXQual_Sub, item_2g_sub3_rxqual_sub); editor.putInt(ITEM_2G_SUB3_Tx_Power_Level, item_2g_sub3_tx_power_level); // editor.putInt(ITEM_2G_SUB4_AMR_Ch, item_2g_sub4_amr_ch); editor.putInt(ITEM_2G_SUB4_Channel_Mode, item_2g_sub4_channel_mode); // editor.putInt(ITEM_3G_SUB0_RRC_state, item_3g_sub0_rcc_state); editor.putInt(ITEM_3G_SUB0_S_ECIO, item_3g_sub0_s_ecio); editor.putInt(ITEM_3G_SUB0_S_FREQ, item_3g_sub0_s_freq); editor.putInt(ITEM_3G_SUB0_S_PSC, item_3g_sub0_s_psc); editor.putInt(ITEM_3G_SUB0_S_RSCP, item_3g_sub0_s_rscp); //nw sub0 editor.putInt(ITEM_NW_SUB0_HPLMN, item_nw_sub0_hplmn); editor.putInt(ITEM_NW_SUB0_LAC, item_nw_sub0_lac); //editor.putInt(ITEM_NW_SUB0_PLMN, item_nw_sub0_plmn); editor.putInt(ITEM_NW_SUB0_MNC, item_nw_sub0_mnc); editor.putInt(ITEM_NW_SUB0_MCC, item_nw_sub0_mcc); editor.putInt(ITEM_NW_SUB0_RAC, item_nw_sub0_rac); editor.putInt(ITEM_TD_PID, item_td_pid); editor.putInt(ITEM_3G_T3212, item_3g_t3212); editor.putInt(ITEM_3G_TMSI, item_3g_tmsi); // editor.putInt(ITEM_NW_SUB1_Attach_Reject, item_nw_sub1_attach_reject); editor.putInt(ITEM_NW_SUB1_GMM_State, item_nw_sub1_gmm_state); editor.putInt(ITEM_NW_SUB1_MM_Reject, item_nw_sub1_mm_reject); editor.putInt(ITEM_NW_SUB1_MM_State, item_nw_sub1_mm_state); editor.putInt(ITEM_NW_SUB1_RAU_Reject, item_nw_sub1_rau_reject); // editor.putInt(ITEM_NW_SUB2_A5_1, item_nw_sub2_A5_1); editor.putInt(ITEM_NW_SUB2_A5_2, item_nw_sub2_A5_2); editor.putInt(ITEM_NW_SUB2_A5_3, item_nw_sub2_A5_3); editor.putInt(ITEM_NW_SUB2_CIPHERING, item_nw_sub2_ciphering); editor.putInt(ITEM_NW_SUB2_GEA1, item_nw_sub2_GEA1); editor.putInt(ITEM_NW_SUB2_GEA2, item_nw_sub2_GEA2); editor.putInt(ITEM_NW_SUB2_UEA1, item_nw_sub2_UEA1); editor.commit(); } else { //use last time values } return result; } }
/* * (C) Copyright IBM Corp. 2020. * * 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.ibm.cloud.cloudant.v1.model; import com.ibm.cloud.sdk.core.service.model.GenericModel; /** * The putReplicationDocument options. */ public class PutReplicationDocumentOptions extends GenericModel { /** * Query parameter to specify whether to store in batch mode. The server will respond with a HTTP 202 Accepted * response code immediately. */ public interface Batch { /** ok. */ String OK = "ok"; } protected String docId; protected ReplicationDocument replicationDocument; protected String ifMatch; protected String batch; protected Boolean newEdits; protected String rev; /** * Builder. */ public static class Builder { private String docId; private ReplicationDocument replicationDocument; private String ifMatch; private String batch; private Boolean newEdits; private String rev; private Builder(PutReplicationDocumentOptions putReplicationDocumentOptions) { this.docId = putReplicationDocumentOptions.docId; this.replicationDocument = putReplicationDocumentOptions.replicationDocument; this.ifMatch = putReplicationDocumentOptions.ifMatch; this.batch = putReplicationDocumentOptions.batch; this.newEdits = putReplicationDocumentOptions.newEdits; this.rev = putReplicationDocumentOptions.rev; } /** * Instantiates a new builder. */ public Builder() { } /** * Instantiates a new builder with required properties. * * @param docId the docId * @param replicationDocument the replicationDocument */ public Builder(String docId, ReplicationDocument replicationDocument) { this.docId = docId; this.replicationDocument = replicationDocument; } /** * Builds a PutReplicationDocumentOptions. * * @return the new PutReplicationDocumentOptions instance */ public PutReplicationDocumentOptions build() { return new PutReplicationDocumentOptions(this); } /** * Set the docId. * * @param docId the docId * @return the PutReplicationDocumentOptions builder */ public Builder docId(String docId) { this.docId = docId; return this; } /** * Set the replicationDocument. * * @param replicationDocument the replicationDocument * @return the PutReplicationDocumentOptions builder */ public Builder replicationDocument(ReplicationDocument replicationDocument) { this.replicationDocument = replicationDocument; return this; } /** * Set the ifMatch. * * @param ifMatch the ifMatch * @return the PutReplicationDocumentOptions builder */ public Builder ifMatch(String ifMatch) { this.ifMatch = ifMatch; return this; } /** * Set the batch. * * @param batch the batch * @return the PutReplicationDocumentOptions builder */ public Builder batch(String batch) { this.batch = batch; return this; } /** * Set the newEdits. * * @param newEdits the newEdits * @return the PutReplicationDocumentOptions builder */ public Builder newEdits(Boolean newEdits) { this.newEdits = newEdits; return this; } /** * Set the rev. * * @param rev the rev * @return the PutReplicationDocumentOptions builder */ public Builder rev(String rev) { this.rev = rev; return this; } } protected PutReplicationDocumentOptions(Builder builder) { com.ibm.cloud.sdk.core.util.Validator.notEmpty(builder.docId, "docId cannot be empty"); com.ibm.cloud.sdk.core.util.Validator.notNull(builder.replicationDocument, "replicationDocument cannot be null"); docId = builder.docId; replicationDocument = builder.replicationDocument; ifMatch = builder.ifMatch; batch = builder.batch; newEdits = builder.newEdits; rev = builder.rev; } /** * New builder. * * @return a PutReplicationDocumentOptions builder */ public Builder newBuilder() { return new Builder(this); } /** * Gets the docId. * * Path parameter to specify the document ID. * * @return the docId */ public String docId() { return docId; } /** * Gets the replicationDocument. * * HTTP request body for replication operations. * * @return the replicationDocument */ public ReplicationDocument replicationDocument() { return replicationDocument; } /** * Gets the ifMatch. * * Header parameter to specify the document revision. Alternative to rev query parameter. * * @return the ifMatch */ public String ifMatch() { return ifMatch; } /** * Gets the batch. * * Query parameter to specify whether to store in batch mode. The server will respond with a HTTP 202 Accepted * response code immediately. * * @return the batch */ public String batch() { return batch; } /** * Gets the newEdits. * * Query parameter to specify whether to prevent insertion of conflicting document revisions. If false, a well-formed * _rev must be included in the document. False is used by the replicator to insert documents into the target database * even if that leads to the creation of conflicts. * * @return the newEdits */ public Boolean newEdits() { return newEdits; } /** * Gets the rev. * * Query parameter to specify a document revision. * * @return the rev */ public String rev() { return rev; } }
package pl.edu.uj.fais.amsi.bio; import pl.edu.uj.fais.amsi.main.Game; /** * * @author Michał Szura */ public class Bacteria extends MapObject { //Very Empty Class public Bacteria(int objectPosition) { super(Game.rules.getBacteriaStartingWeight(), objectPosition); } }
import com.sun.xml.internal.fastinfoset.util.ValueArray; /** * Created with IntelliJ IDEA. * User: dexctor * Date: 12-12-21 * Time: 上午10:44 * To change this template use File | Settings | File Templates. */ public class MyLinkedSeparateChainingHashST<Key, Value> { private int M; private int N; private class Node<Key, Value> { Key key; Value value; int n; Node next; public Node(Key key, Value value, Node next, int n) { this.key = key; this.value = value; this.next = next; this.n = n; } } private Node<Key,Value>[] st; public MyLinkedSeparateChainingHashST(int M) { this.M = M; st = (Node<Key, Value>[]) new Node[M]; } private int hash(Key key) { return (key.hashCode() & 0x7ffffff) % M; } public Value get(Key key) { int h = hash(key); return get(st[h], key); } private Value get(Node<Key,Value> x, Key key) { while (x != null) { if(x.key.equals(key)) return x.value; x = x.next; } return null; } public int size() { return N; } public void put(Key key, Value value) { int h = hash(key); st[h] = put(st[h], key, value); } private Node put(Node x, Key key, Value value) { Node first = x; while (x != null) { if(x.key.equals(key)) { x.value = value; x.n = size(); return first; } x = x.next; } Node oldfirst = first; first = new Node(key, value, oldfirst, size()); N++; return first; } public void delete(Key key) { int h = hash(key); st[h] = delete(st[h], key); } private Node delete(Node x, Key key) { if(x == null) return null; if(key.equals(x.key)) { N--; return x.next; } else x.next = delete(x.next, key); return x; } public void deleteLarge(int k) { for(int i = 0; i < M; i ++) { st[i] = deleteLarge(st[i], k); } } private Node deleteLarge(Node x, int k) { if(x == null) return null; if(x.n > k) { N--; return deleteLarge(x.next, k); } else { x.next = deleteLarge(x.next, k); return x; } } public static void main(String[] args) { int N = StdIn.readInt(); Integer[] a = new Integer[N]; for(int i = 0; i < N; ++i) { a[i] = i; } StdRandom.shuffle(a); MyLinkedSeparateChainingHashST<Integer, Integer> st = new MyLinkedSeparateChainingHashST<Integer, Integer>(N / 2); for(int i = 0; i < N; ++i) { st.put(a[i], a[i]); } for(int i = 0; i < N; ++i) { StdOut.print(a[i] + ":" + st.get(a[i]) + " "); } StdOut.println(); StdOut.println(st.get(100)); st.delete(10); for(int i = 0; i < N; ++i) { StdOut.print(a[i] + ":" + st.get(a[i]) + " "); } StdOut.println(); st.deleteLarge(15); for(int i = 0; i < N; ++i) { StdOut.print(a[i] + ":" + st.get(a[i]) + " "); } StdOut.println(); } }
package com.esum.comp.ebms.outbound; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import org.apache.commons.io.IOUtils; import org.apache.cxf.common.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.esum.comp.ebms.EbMSCode; import com.esum.comp.ebms.EbMSConfig; import com.esum.comp.ebms.EbMSException; import com.esum.comp.ebms.adapter.EbMSInterfaceAdapter; import com.esum.comp.ebms.table.EbMSInfoRecord; import com.esum.comp.ebms.table.EbMSInfoTable; import com.esum.comp.ebms.util.MessageIDMapper; import com.esum.ebms.v2.packages.container.Payload; import com.esum.ebms.v2.packages.util.MessageUtil; import com.esum.ebms.v2.service.ApplicationMessage; import com.esum.ebms.v2.service.MessageService; import com.esum.ebms.v2.service.Routing; import com.esum.ebms.v2.service.Routing.PartyInfo; import com.esum.ebms.v2.storage.RoutingInfoRecord; import com.esum.ebms.v2.storage.RoutingPathRecord; import com.esum.ebms.v2.storage.RoutingSearch; import com.esum.ebms.v2.storage.StorageException; import com.esum.ebms.v2.service.ServiceException; import com.esum.framework.common.util.FileUtil; import com.esum.framework.common.util.StringUtil; import com.esum.framework.common.util.ZipUtil; import com.esum.framework.core.component.ComponentException; import com.esum.framework.core.component.PostRoutingException; import com.esum.framework.core.component.config.ComponentConfigFactory; import com.esum.framework.core.component.table.InfoTableManager; import com.esum.framework.core.event.RoutingStatus; import com.esum.framework.core.event.log.ErrorInfo; import com.esum.framework.core.event.log.LoggingEvent; import com.esum.framework.core.event.message.Attachment; import com.esum.framework.core.event.message.ContentInfo; import com.esum.framework.core.event.message.EventHeader; import com.esum.framework.core.event.message.MessageEvent; import com.esum.framework.core.event.util.LoggingEventUtil; import com.esum.framework.core.exception.SystemException; import com.esum.framework.net.http.HTTPException; import com.esum.framework.security.auth.HTTPAuthInfo; import com.esum.framework.security.auth.HTTPAuthManager; import com.esum.framework.security.auth.HTTPBasicAuthentication; import com.esum.framework.security.pki.manager.PKIException; import com.esum.router.RouterUtil; import com.esum.router.handler.OutboundHandlerAdapter; import com.esum.router.route.MessageSentAutoAcknowledgeHandler; import com.esum.router.table.document.DocInfoRecord; import com.esum.router.table.partner.PartnerInfoRecord; public class EbMSOutboundHandler extends OutboundHandlerAdapter { private static final long serialVersionUID = 1L; private Logger log = LoggerFactory.getLogger(EbMSOutboundHandler.class); public EbMSOutboundHandler(String compponentId) { super(compponentId); setLog(log); } public void onProcess(MessageEvent messageEvent) { this.traceId = "[" + messageEvent.getMessageControlId() + "] "; try { log.info(traceId + "Received MessageEvent...."); List<OutputStream> payloadList = EbMSInterfaceAdapter.getInstance().getPayloadList(messageEvent); ApplicationMessage appMessage = createApplicationMessage(traceId, messageEvent, payloadList); EbMSConfig ebMSConfig = (EbMSConfig)ComponentConfigFactory.getInstance(getComponentId()); String outputStatus = EbMSConfig.OUTPUT_STATUS; if(messageEvent.getEventHeader().getType()==EventHeader.TYPE_ACKNOWLEDGE) { log.debug(traceId+"acknowledge event. sending status is DONE."); outputStatus = RoutingStatus.DONE_STATUS; } else { // RoutingInfoRecord routingInfo = null; // try { // routingInfo = RoutingSearch.getRoutingInfo( // MessageService.EBXML_MESSAGE , appMessage.getRouting()); // if(routingInfo!=null) { // RoutingPathRecord routingPath = routingInfo.getRoutingPath(); // if(routingPath==null) // throw new StorageException(StorageException.ERROR_NOT_FOUND_ROUTING_INFO, "onProcess()", // "Could not found Routing Path. routing path : "+routingInfo.getRoutingPathId()); // if(routingPath.isAckRequested()) // outputStatus = RoutingStatus.SNDG_STATUS; // } // } catch (StorageException e) { // throw new EbMSException(e.getErrorCode(), e.getErrorLocation(), e.getErrorMessage(), e); // } } processSucess(messageEvent, new Object[] {appMessage}, outputStatus, ebMSConfig.getSyncOutputStatus(), false); /** MSH의 처리 속도가 빨라서 status가 역전될 수 있 수 있기 때문에 나중에 처리한다. */ sendToMSH(traceId, appMessage, messageEvent); } catch (EbMSException e) { log.error(traceId + "process() ", e); processError(messageEvent, e); } catch (ComponentException e) { log.error(traceId + "process() ", e); processError(messageEvent, e); } catch (Exception e) { log.error(traceId + "process() ", e); EbMSException ee = new EbMSException(EbMSCode.ERROR_UNDEFINED, "process()", e); processError(messageEvent, ee); } } @Override protected LoggingEvent onPostProcess(MessageEvent messageEvent, Object[] params, String status) throws SystemException { // ebXML Message내의 ID와 Payload중 첫 번째 Payload의 크기를 OutMessageId, OutMessageSize에 설정한다. ApplicationMessage appMessage = (ApplicationMessage)params[0]; LoggingEvent logEvent = LoggingEventUtil.makeLoggingEvent(messageEvent.getEventHeader().getType(), messageEvent.getMessageControlId(), getComponentId(), messageEvent, status); if (appMessage != null) { logEvent.getLoggingInfo().getMessageLog().setOutMessageId(appMessage.getMessageId()); logEvent.getLoggingInfo().getMessageLog().setOutMessageSize(appMessage.getPayload(0).getData().length); } return logEvent; } protected void onProcessPostRoutingJob(MessageEvent messageEvent, ErrorInfo errorInfo) throws PostRoutingException { boolean isHold = false; try { isHold = isHoldMessage(messageEvent); } catch (SystemException e) { return; } if(EbMSConfig.USE_ACK_SEND && !isHold) { log.debug(traceId + "Use Auto ACK sending is true."); MessageSentAutoAcknowledgeHandler ackHandler = new MessageSentAutoAcknowledgeHandler(); try { ackHandler.sendAcknowledge(messageEvent, messageEvent.getMessageControlId(), EbMSConfig.ACK_CLASS); } catch (SystemException e) { log.error(traceId+"Auto Acknowledge sending error", e); } ackHandler = null; } } /** * 메시지를 MSH로 전송한다. */ private ApplicationMessage createApplicationMessage(String traceId, MessageEvent messageEvent, List<OutputStream> payloadList) throws EbMSException, ComponentException, SystemException { if(log.isDebugEnabled()) log.debug(traceId + "Sending Message to MSH..."); String fromSvcId = messageEvent.getMessage().getHeader().getFromParty().getUserId(); String toSvcId = messageEvent.getMessage().getHeader().getToParty().getUserId(); String msgName = messageEvent.getMessage().getHeader().getMessageName(); if(log.isDebugEnabled()) log.debug(traceId + "FromSvcId("+fromSvcId+"), ToSvcId("+toSvcId+"), MessageName(" + msgName+")"); String targetIfId = messageEvent.getRoutingInfo().getTargetInterfaceId(); if (targetIfId == null) targetIfId = RouterUtil.getTargetInterfaceId(fromSvcId, toSvcId, msgName); if(log.isDebugEnabled()) log.debug(traceId + "Target Interface Id : " + targetIfId); setInterfaceId(targetIfId); EbMSInfoTable ebMSInfoTable = (EbMSInfoTable)InfoTableManager.getInstance().getInfoTable(EbMSConfig.EBMS_INFO_TABLE_ID); EbMSInfoRecord ebMSInfoRecord = ebMSInfoTable.getInfoRecord(getInterfaceId(), EbMSInfoRecord.class); if (ebMSInfoRecord == null) { throw new EbMSException(EbMSCode.ERROR_NOT_FOUND_EBMS_INFO, "sendMessageToMSH()", "Not found the EBMS information for " + getInterfaceId() + " interface ID."); } // if (StringUtils.isEmpty(ebMSInfoRecord.getParsingRule())) { // throw new EbMSException(EbMSCode.ERROR_NOT_FOUND_RULE_ID, // "sendMessageToMSH()", "Not found the parsing rule for ebMS MSH. Interface ID: " + getInterfaceId()); // } /** Building ebxml routing */ Routing routing = new Routing(); try { Hashtable<String,String> params = new Hashtable<String,String>(); // set the sender and receiver party information. PartnerInfoRecord senderInfo = RouterUtil.getPartnerInfo(messageEvent.getMessage().getPayload().getDataInfo().getSender()); PartnerInfoRecord receiverInfo = RouterUtil.getPartnerInfo(messageEvent.getMessage().getPayload().getDataInfo().getReceiver()); String docName = messageEvent.getMessage().getPayload().getDataInfo().getDocumentName(); String secondDocName = docName; if (RouterUtil.isExistDocInfoRecord(docName, senderInfo.getTpId(), receiverInfo.getTpId())) { DocInfoRecord docInfo = RouterUtil.getDocInfoRecord(docName, senderInfo.getTpId(), receiverInfo.getTpId()); secondDocName = docInfo.getBizSvcName(); } params.put("sender.vendor.code", senderInfo.getUserId()); params.put("recver.vendor.code", receiverInfo.getUserId()); params.put("doc.name", docName); params.put("biz.svc.name", secondDocName); String cpaId = StringUtil.replacePropertyToValue(ebMSInfoRecord.getOutboundCpaId(), params); String fromPartyId = StringUtil.replacePropertyToValue(ebMSInfoRecord.getOutboundFromPartyId(), params); String fromPartyType = StringUtil.replacePropertyToValue(ebMSInfoRecord.getOutboundFromPartyType(), params); String toPartyId = StringUtil.replacePropertyToValue(ebMSInfoRecord.getOutboundToPartyId(), params); String toPartyType = StringUtil.replacePropertyToValue(ebMSInfoRecord.getOutboundToPartyType(), params); String fromRole = StringUtil.replacePropertyToValue(ebMSInfoRecord.getOutboundFromRole(), params); String toRole = StringUtil.replacePropertyToValue(ebMSInfoRecord.getOutboundToRole(), params); String service = StringUtil.replacePropertyToValue(ebMSInfoRecord.getOutboundService(), params); String serviceType = StringUtil.replacePropertyToValue(ebMSInfoRecord.getOutboundServiceType(), params); String action = StringUtil.replacePropertyToValue(ebMSInfoRecord.getOutboundAction(), params); String description = StringUtil.replacePropertyToValue(ebMSInfoRecord.getOutboundDescription(), params); // Set Party Info routing.addFromParty(fromPartyId, fromPartyType); routing.addToParty(toPartyId, toPartyType); routing.setFromPartyRole(fromRole); routing.setToPartyRole(toRole); // Set CPA ID routing.setCpaId(cpaId); // Set Service routing.service = service; routing.serviceType = serviceType; // Set Action routing.action = action; // Set Description routing.description = description; } catch (Exception e) { log.error(traceId + "Error occured in Building Ebxml Routing Info. (InterfaceID: " + getInterfaceId() +") ", e); throw new EbMSException(EbMSCode.ERROR_BUILD_EBXML_ROUTING, "sendMessageToMSH()", "Error occured in Building Ebxml Routing Info. (InterfaceID: " + getInterfaceId() +") "+e.getMessage()); } if(routing.getFromPartyList().size() < 1){ throw new EbMSException(EbMSCode.ERROR_NOT_FOUND_SAINFO, "sendMessageToMSH()", "getFromPartyList() is 0."); } if(log.isDebugEnabled()) { log.debug(traceId + "From Party ID: " + ((PartyInfo)routing.getFromPartyList().get(0)).id + " Type: " + ((PartyInfo)routing.getFromPartyList().get(0)).type); log.debug(traceId + "To Party ID: " + ((PartyInfo)routing.getToPartyList().get(0)).id + " Type: " + ((PartyInfo)routing.getToPartyList().get(0)).type); log.debug(traceId + "CPA ID: " + routing.getCpaId()); log.debug(traceId + "Service: " + routing.service); log.debug(traceId + "Action: " + routing.action); log.debug(traceId + "Description: " + routing.description); } int count = 0; ApplicationMessage appMessage = null; appMessage = new ApplicationMessage(EbMSConfig.CONTEXT_ID, routing); appMessage.setTxId(messageEvent.getMessageControlId()); String fromPartyId = ((PartyInfo)routing.getFromPartyList().get(0)).id; // appMessage.setMessageId(MessageUtil.generateMessageId(routing.getCpaId())); appMessage.setMessageId(messageEvent.getMessageControlId()+"@"+routing.getCpaId()); String conversationId = messageEvent.getMessage().getPayload().getDataInfo().getConversationId(); if (conversationId == null || conversationId.trim().equals("")) { conversationId = appMessage.getMessageId(); } appMessage.setConversationId(conversationId); appMessage.setDescription(routing.description); if(log.isDebugEnabled()) { log.debug(traceId + "ebXML Tx ID: " + appMessage.getTxId()); log.debug(traceId + "ebXML Message ID: " + appMessage.getMessageId()); log.debug(traceId + "ebXML Conversation ID: " + appMessage.getConversationId()); } // HTTP 인증을 사용하는 경우 설정: HTTP Basic 인증과 식별번호를 이용한 본인확인(관세청)시에 사용된다. if (ebMSInfoRecord.getOutboundAuthInfo() != null && !ebMSInfoRecord.getOutboundAuthInfo().equals("")) { HTTPAuthInfo httpAuthInfo = HTTPAuthManager.getInstance().getHTTPAuthInfo(ebMSInfoRecord.getOutboundAuthInfo()); try { appMessage.setHTTPBasicAuth(HTTPBasicAuthentication.getInstance().generateValue(httpAuthInfo)); } catch (HTTPException e) { throw new EbMSException(EbMSCode.ERROR_GENERATE_HTTP_AUTH, "sendMessageToMSH()", e.getMessage(), e); } catch (PKIException e) { throw new EbMSException(EbMSCode.ERROR_GENERATE_HTTP_AUTH, "sendMessageToMSH()", e.getMessage(), e); } } Iterator<OutputStream> i = payloadList.iterator(); while (i.hasNext()) { count++; ByteArrayOutputStream out = (ByteArrayOutputStream)i.next(); byte[] payloadData = null; try { payloadData = out.toByteArray(); } finally { IOUtils.closeQuietly(out); } try { appMessage.addPayload(payloadData); } catch (ServiceException e) { throw new EbMSException(EbMSCode.ERROR_PAYLOAD_NULL, "sendMessageToMSH()", e.getMessage(), e); } } int attachedCnt = messageEvent.getMessage().getAttachmentCount(); if(attachedCnt!=0) { processAttachement(messageEvent, appMessage); } if(log.isDebugEnabled()) log.debug(traceId + "Payload Count: " + count); return appMessage; } private void sendToMSH(String traceId, ApplicationMessage appMessage, MessageEvent messageEvent) throws EbMSException { // ebXML Message의 Message ID와 MessageEvent를 매핑한다. MessageIDMapper.getInstance().map(appMessage.getMessageId(), messageEvent, getInterfaceId()); try { EbMSInterfaceAdapter.getInstance().request(appMessage); } catch (Exception e) { MessageIDMapper.getInstance().removeRoutingInfo(appMessage.getMessageId()); throw new EbMSException(EbMSCode.ERROR_SEND_MESSAGE_TO_MSH, "sendMessageToMSH()", e.getMessage(), e); } log.debug(traceId + "Sent Message to MSH."); } private void processAttachement(MessageEvent messageEvent, ApplicationMessage appMessage) throws EbMSException, ServiceException { List<File> attachedFiles = new ArrayList<File>(); for (int idx = 0; idx < messageEvent.getMessage().getAttachmentCount(); idx++) { Attachment attachment = messageEvent.getMessage().getAttachment(idx); try { ContentInfo attachmentCInfo = attachment.getContentInfo(); String contentType = attachmentCInfo.getContentType()!=null?attachmentCInfo.getContentType():Payload.MIME_TYPE_APPLICATION_OCTET_STREAM; String contentCharSet = attachmentCInfo.getContentEncoding(); String contentName = attachmentCInfo.getContentName(); String contentDescription = attachmentCInfo.getContentDescription(); byte[] attachData = null; if(contentType.equals(Payload.MIME_TYPE_APPLICATION_FILE)) { String filePath = new String(attachment.getData()); File attachFile = new File(filePath); if(attachFile.exists() && !attachedFiles.contains(attachFile)) { attachedFiles.add(attachFile); } } else { attachData = attachment.getData(); appMessage.addPayload(attachData, contentType, contentCharSet, contentName, contentDescription); } } catch (ServiceException e) { throw new EbMSException(EbMSCode.ERROR_PAYLOAD_NULL, "sendMessageToMSH()", e.getMessage(), e); } } /** * 대법원 연계시 사용함. * Attachment에 File경로가 들어가 있고, File을 읽어서 압축한 후 Payload에 적재한다. */ if(attachedFiles.size()!=0){ byte[] attachedData = null; try { if(EbMSConfig.OUTBOUND_ATTACH_FILE_COMPRESS) { attachedData = ZipUtil.zip(attachedFiles); appMessage.addPayload(attachedData, Payload.MIME_TYPE_APPLICATION_ZIP); } else { for(File f:attachedFiles) { appMessage.addPayload(FileUtil.readToByte(f), Payload.MIME_TYPE_APPLICATION_FILE); } } log.debug(traceId + "zip attachment("+attachedFiles.size()+" data) attached."); } catch (IOException e) { log.error(traceId+"Could not add payload.", e); throw new EbMSException(EbMSCode.ERROR_PAYLOAD_NULL, "sendMessageToMSH()", e.getMessage(), e); } if(EbMSConfig.OUTBOUND_DELETE_ATTACHED_FILE) { for(File f : attachedFiles) { log.debug(traceId+"Deleting Attached File. name : "+f.getAbsolutePath()); f.delete(); } } } } }
package chapter_two.linked_lists; /** * Date 06/06/20. * * Implement an algorithm to find the kt to last element of a singly linked list. * A more optimal, but less straightforward, solution is to implement this iteratively. * We can use two pointers, p1 and p2. We place them k nodes apart in the linked list by putting * p1 at the beggining and moving p2 k nodes into the list. Then, when we move them at the same pace, * p2 will hit the end of the linked list after LENGTH - K nodes into the list, or K nodes from the end. */ public class LinkedListKthElementIterativeBookSolution { public static void main(String[] args) { head = new Node(4); head.next = new Node(10); head.next.next = new Node(15); head.next.next.next = new Node(7); head.next.next.next.next = new Node(11); head.next.next.next.next.next = new Node(13); Node node = nThToLast(head, 2); System.out.println(node.data); } public static Node head; public static class Node { int data; Node next; public Node(int data) { this.data = data; } } public static Node nThToLast(Node head, int k) { if (k == 0) { return null; } Node p1 = head; Node p2 = head; //Move p2 forward k nodes into the list. for (int i = 0; i < k-1; i++) { if (p2 == null) { return null; } p2 = p2.next; } if (p2 == null) { return null; } // Now, move p1 and p2 at the same speed. When p2 hits the end, p1 will be at the right element. while (p2 != null) { p1 = p1.next; p2 = p2.next; } return p1; } }
import javax.swing.*; public class MyButton extends JButton { int x; int y; MyButton(int x, int y){ super(); this.x=x; this.y=y; } }
package com.egreat.adlauncher.util; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.params.CookiePolicy; import org.apache.http.client.params.HttpClientParams; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.text.TextUtils; import android.util.Log; /** * 閫氳繃瀵瑰簲鐨勮姹傝幏寰桱son鏁版嵁 * @author wangguoqing */ public class HttpUtils { private static final int REQUEST_TIMEOUT = 10*1000;//璁剧疆璇锋眰瓒呮椂10绉掗挓 private static final int SO_TIMEOUT = 10*1000; //璁剧疆绛夊緟鏁版嵁瓒呮椂鏃堕棿10绉掗挓 public static HttpParams httpParams; /** * @param url 鍙戦�璇锋眰鐨刄RL * @return 鏈嶅姟鍣ㄥ搷搴斿瓧绗︿覆 * @throws Exception */ public static String getRequest(final String url,Context ctx) throws IOException { if (TextUtils.isEmpty(url)) { return null; } HttpResponse httpResponse = null; StringBuffer sb = new StringBuffer(); HttpClient httpClient = null; try{ //鍒涘缓HttpGet瀵硅薄銆� HttpGet get = new HttpGet(url); httpParams = new BasicHttpParams(); //璁剧疆杩炴帴瓒呮椂鍜�Socket 瓒呮椂锛屼互鍙�Socket 缂撳瓨澶у皬 HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT); HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT); HttpConnectionParams.setSocketBufferSize(httpParams, 8192); //璁剧疆閲嶅畾鍚戯紝缂虹渷涓�true HttpClientParams.setRedirecting(httpParams, true); //璁剧疆 user agent String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6"; HttpProtocolParams.setUserAgent(httpParams, userAgent); //鍒涘缓涓�釜 HttpClient瀹炰緥 //娉ㄦ剰 HttpClient httpClient = new HttpClient(); 鏄疌ommons HttpClient //涓殑鐢ㄦ硶锛屽湪 Android 1.5 涓垜浠渶瑕佷娇鐢�Apache 鐨勭己鐪佸疄鐜�DefaultHttpClient httpClient = new DefaultHttpClient(httpParams); HttpClientParams.setCookiePolicy(httpClient.getParams(), CookiePolicy.BROWSER_COMPATIBILITY); //鍙戦�GET璇锋眰 httpResponse = httpClient.execute(get); //濡傛灉鏈嶅姟鍣ㄦ垚鍔熷湴杩斿洖鍝嶅簲 if (httpResponse.getStatusLine().getStatusCode() == 200) { //鑾峰彇鏈嶅姟鍣ㄥ搷搴斿瓧绗︿覆 sb.append(EntityUtils.toString(httpResponse.getEntity())); return sb.toString(); } }catch (ClientProtocolException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } finally{ if(null != httpClient && null != httpClient.getConnectionManager()) { httpClient.getConnectionManager().shutdown(); } } return null; } /** * @param url 鍙戦�璇锋眰鐨刄RL * @param params 璇锋眰鍙傛暟 * @return 鏈嶅姟鍣ㄥ搷搴斿瓧绗︿覆 * @throws Exception */ public static String postRequest(String url, Map<String ,String> rawParams,Context ctx) throws Exception { HttpClient httpClient = null; try{ //鍒涘缓HttpPost瀵硅薄銆� HttpPost post = new HttpPost(url); //濡傛灉浼犻�鍙傛暟涓暟姣旇緝澶氱殑璇濆彲浠ュ浼犻�鐨勫弬鏁拌繘琛屽皝瑁� List<NameValuePair> params = new ArrayList<NameValuePair>(); for(String key : rawParams.keySet()) { //灏佽璇锋眰鍙傛暟 params.add(new BasicNameValuePair(key , rawParams.get(key))); } //璁剧疆璇锋眰鍙傛暟 post.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8)); httpParams = new BasicHttpParams(); //璁剧疆杩炴帴瓒呮椂鍜�Socket 瓒呮椂锛屼互鍙�Socket 缂撳瓨澶у皬 HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT); HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT); HttpConnectionParams.setSocketBufferSize(httpParams, 8192); //璁剧疆閲嶅畾鍚戯紝缂虹渷涓�true HttpClientParams.setRedirecting(httpParams, true); //璁剧疆 user agent String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6"; HttpProtocolParams.setUserAgent(httpParams, userAgent); //鍒涘缓涓�釜 HttpClient 瀹炰緥 //娉ㄦ剰 HttpClient httpClient = new HttpClient();鏄疌ommons HttpClient //涓殑鐢ㄦ硶锛屽湪 Android 1.5 涓垜浠渶瑕佷娇鐢�Apache 鐨勭己鐪佸疄鐜�DefaultHttpClient httpClient = new DefaultHttpClient(httpParams); //鍙戦�POST璇锋眰 HttpResponse httpResponse = httpClient.execute(post); //濡傛灉鏈嶅姟鍣ㄦ垚鍔熷湴杩斿洖鍝嶅簲 if (httpResponse.getStatusLine().getStatusCode() == 200) { //鑾峰彇鏈嶅姟鍣ㄥ搷搴斿瓧绗︿覆 String result = EntityUtils.toString(httpResponse.getEntity()); return result; } }catch(Exception e){ e.printStackTrace(); }finally{ if(null != httpClient && null != httpClient.getConnectionManager()) httpClient.getConnectionManager().shutdown(); } return null; } /** * 鑾峰彇鏈嶅姟鍣ㄥ浘鐗� * @param image * @return */ public static Bitmap getImage(String path) { // 瀹氫箟涓�釜URL瀵硅薄 URL url; Bitmap bitmap = null; try { System.out.println("image_url---"+(path)); url = new URL(path); //鑾峰緱杩炴帴 HttpURLConnection conn=(HttpURLConnection)url.openConnection(); //璁剧疆瓒呮椂鏃堕棿涓�0000姣锛宑onn.setConnectionTiem(0);琛ㄧず娌℃湁鏃堕棿闄愬埗 conn.setConnectTimeout(10000); //璁剧疆浠庝富鏈鸿鍙栨暟鎹秴鏃讹紙鍗曚綅锛氭绉掞級 conn.setReadTimeout(10000); //杩炴帴璁剧疆鑾峰緱鏁版嵁娴� conn.setDoInput(true); //璁剧疆璇锋眰鏂瑰紡涓篜OST conn.setRequestMethod("POST"); //涓嶄娇鐢ㄧ紦瀛� conn.setUseCaches(false); // 鎵撳紑璇RL瀵瑰簲鐨勮祫婧愮殑杈撳叆娴� InputStream is = conn.getInputStream(); // 浠嶪nputStream涓В鏋愬嚭鍥剧墖 bitmap = BitmapFactory.decodeStream(is); //浣跨敤ImageView鏄剧ず璇ュ浘鐗� is.close(); } catch (IOException e) { e.printStackTrace(); } return bitmap; } public static void deleteFilesByDirectory(File directory) { if (directory != null && directory.exists() && directory.isDirectory()) { for (File item : directory.listFiles()) { item.delete(); } } } /** * 鍒ゆ柇缃戠粶鏄惁杩為� * @param context * @return */ public static boolean isNetworkConnected(Context context) { @SuppressWarnings("static-access") ConnectivityManager cm = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getActiveNetworkInfo(); return info != null && info.isConnected(); } public static String getContent(String url, Header[] headers, NameValuePair[] pairs ) { String content = null; HttpResult result = null; result = HttpClientHelper.get(url, headers, pairs); if (result != null && result.getStatuCode() == HttpStatus.SC_OK) { try { content = result.getHtml(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } return content; } public static String getFileNameForUrl(String url) { String fileName = ""; if (url != null && !TextUtils.isEmpty(url)) { int lastIndexOf = url.trim().lastIndexOf("/"); if (lastIndexOf > -1) { fileName = url.substring(lastIndexOf+1, url.length()); } } return fileName; } }
package com.hp.app; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @RequestMapping("/hello") public String hi() { return "My First SpringBoot App"; } }
package tn.esprit.spring.service; import java.util.List; import tn.esprit.spring.entity.Mission; public interface IMissionService { long ajouterMission(Mission mission); void deleteMission(int id); List<Mission> getMissions(); long getMissionNumber(); Mission MissionUpadate(Mission Miss); }
package de.mneifercons.webdriver; /* * Copyright (c) 2020 Markus Neifer * Licensed under the MIT License. * See file LICENSE in parent directory of project root. */ public class App { public static void main(String[] args) { System.out.println("Hello World!"); } }
package com.gaoshin.fbobuilder.client.editor; public class CircleEditor extends ShapeEditor { }
/* * 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 copyingfile; import java.io.*; /** * * @author Rami Dannah */ public class Ex extends Reader{ @Override public int read(char[] cbuf, int off, int len) throws IOException { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void close() throws IOException { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
package com.array; import java.util.Stack; public class Test { @org.junit.Test public void test1() { MyArray<Integer> arr = new MyArray<>(); for(int i=0;i<10;i++) { arr.addLast(i); } System.out.println(arr); arr.add(5, 100); //arr.removeElement(5); System.out.println(arr); /*arr.addFirst(-1); arr.remove(4); System.out.println(arr);*/ } @org.junit.Test public void test2() { ArrayStack<Integer> s = new ArrayStack<>(); for(int i=0;i<5;i++) { s.push(i); } System.out.println(s); System.out.println(s.pop()); } @org.junit.Test public void test3() { System.out.println(isValid("12(2(3){s()s}[]")); System.out.println(isValid("({[]})")); } @org.junit.Test public void test4() { ArrayQueue<Integer> queue = new ArrayQueue<>(); queue.enqueue(3); queue.enqueue(2); queue.enqueue(6); System.out.println(queue.getFront()); System.out.println(queue.dequeue()); System.out.println(queue.getFront()); System.out.println(queue); } public boolean isValid(String s) { Stack<Character> st = new Stack<>(); for(int i=0;i<s.length();i++) { char c=s.charAt(i); if( c== '(' || c == '{' || c == '[') { st.push(s.charAt(i)); } else { if(c == ')' || c == '}' || c == ']') { if(st.isEmpty()) { return false; } char co= st.pop(); if(co == ')' && c!=')') { return false; }if(co == '}' && c!='}') { return false; }if(co == ']' && c!=']') { return false; } } } } return st.isEmpty(); } }
package com.company; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; public class Main { public static String getdate() { Date dnow = new Date(); SimpleDateFormat ft = new SimpleDateFormat("E"); return ft.format(dnow); } public static void main(String[] args) throws IOException { String[][] tablica = new String[9][7]; Connection connect = Jsoup.connect("http://www.zsb.iq.pl/plan/plany/o1.html"); Document document = connect.get(); //Nagłówek int i = 0; Elements allth = document.select("th"); for(Element elem: allth) { tablica[0][i] = elem.text(); i++; // System.out.println(elem.text()); } // zajecia int j = 2; i = 1; Elements alltd = document.select("td.l"); for(Element elem: alltd) { if(j==7){ j=2; i++; } tablica[i][j] = elem.text(); j++; //System.out.println(elem.text()); } //numer i=1; Elements allnr = document.select(".nr"); for(Element elem: allnr) { tablica[i][0] = elem.text(); i++; //System.out.println(elem.text()); } //godziny i=1; Elements allgod = document.select(".g"); for(Element elem: allgod) { tablica[i][1] = elem.text(); i++; //System.out.println(elem.text()); } String day = getdate(); switch (day) { case "Pn": i = 2; break; case "Wt": i = 3; break; case "Sr": i = 4; break; case "Cw": i = 5; break; case "Pt": i = 6; break; default:System.out.println( "Invalid day"); break; } for(int k = 0; k < 9; k++){ System.out.println(tablica[k][i]); } } }
package comp5134.model; public class FlavorDecorator extends IceCreamDecorator{ public FlavorDecorator(IceCream iceCream, int price) { super(iceCream); // TODO Auto-generated constructor stub myPrice = price; totalPrice = iceCream.totalPrice; for (int i=0;i<iceCream.getObserverList().size();i++){ this.registerObserver(iceCream.getObserverList().get(i)); } } @Override public int getTotalPrice() { // TODO Auto-generated method stub return totalPrice; } @Override public boolean isHasFlavor() { // TODO Auto-generated method stub return true; } @Override public void addTotal() { // TODO Auto-generated method stub totalPrice += myPrice; setChanged(); notifyObservers(OBSERVABLE_EVENT_ADD_TOTAL); } @Override public void setFlavor() { // TODO Auto-generated method stub hasFlavor = false; setChanged(); notifyObservers(OBSERVABLE_EVENT_SET_FLAVOR); } }
/* * (C) Mississippi State University 2009 * * The WebTOP employs two licenses for its source code, based on the intended use. The core license for WebTOP applications is * a Creative Commons GNU General Public License as described in http://*creativecommons.org/licenses/GPL/2.0/. WebTOP libraries * and wapplets are licensed under the Creative Commons GNU Lesser General Public License as described in * http://creativecommons.org/licenses/*LGPL/2.1/. Additionally, WebTOP uses the same licenses as the licenses used by Xj3D in * all of its implementations of Xj3D. Those terms are available at http://www.xj3d.org/licenses/license.html. */ //Complex.java //Defines the class Complex, for representing complex numbers. //Davis Herring //Created August 6 2002 //Updated August 17 2002 //Version 1.21 (CSDL v3.32) package org.sdl.math; public class Complex { public double R,I; public Complex() {} public Complex(double a,double b) {R=a;I=b;} public Complex(Complex c) {R=c.R;I=c.I;} public static Complex fromPolar(double r,double t) {return new Complex(r*Math.cos(t),r*Math.sin(t));} public double mag() {return Math.pow(R*R+I*I,.5);} public double arg() {return Math.atan2(I,R);} public Complex log() {return new Complex(Math.log(R*R+I*I)/2,arg());} public Complex exp() {return fromPolar(Math.exp(R),I);} public Complex conjugate() {return new Complex(R,-I);} public void setRect(double a,double b) {R=a;I=b;} public void setPolar(double m,double t) {R=m*Math.cos(t);I=m*Math.sin(t);} public void add(Complex c) {R+=c.R;I+=c.I;} public void add(double d) {R+=d;} public void subtract(Complex c) {R-=c.R;I-=c.I;} public void subtract(double d) {R-=d;} public void multiply(Complex c) {setRect(R*c.R-I*c.I,R*c.I+I*c.R);} public void multiply(double d) {R*=d;I*=d;} public void divide(Complex c) {double m=c.R*c.R+c.I*c.I;setRect((R*c.R+I*c.I)/m,(c.R*I-c.I*R)/m);} public void divide(double d) {R/=d;I/=d;} public static Complex add(Complex c1,Complex c2) {return new Complex(c1.R+c2.R,c1.I+c2.I);} public static Complex add(Complex c,double d) {return new Complex(c.R+d,c.I);} public static Complex subtract(Complex c1,Complex c2) {return new Complex(c1.R-c2.R,c1.I-c2.I);} public static Complex subtract(Complex c,double d) {return new Complex(c.R-d,c.I);} public static Complex multiply(Complex c1,Complex c2) {return new Complex(c1.R*c2.R-c1.I*c2.I,c1.R*c2.I+c1.I*c2.R);} public static Complex multiply(Complex c,double d) {return new Complex(c.R*d,c.I*d);} public static Complex divide(Complex c1,Complex c2) {double m=c2.R*c2.R+c2.I*c2.I;return new Complex((c1.R*c2.R+c1.I*c2.I)/m,(c2.R*c1.I-c2.I*c1.R)/m);} public static Complex divide(Complex c,double d) {return new Complex(c.R/d,c.I/d);} public static Complex divide(double d,Complex c) {double m=c.R*c.R+c.I*c.I;return new Complex(c.R*d/m,-c.I*d/m);} public static Complex pow(Complex base,Complex power) {Complex l=base.log(); l.multiply(power); return l.exp();} public static Complex pow(Complex base,double power) {Complex l=base.log(); l.multiply(power); return l.exp();} public Complex sin() {return new Complex(Hyperbolic.cos(I)*Math.sin(R),Math.cos(R)*Hyperbolic.sin(I));} public Complex cos() {return new Complex(Hyperbolic.cos(I)*Math.cos(R),-Math.sin(R)*Hyperbolic.sin(I));} public Complex tan() {return new Complex(Math.sin(2*R)/(Math.cos(2*R) + Hyperbolic.cos(2*I)),Hyperbolic.sin(2*I)/(Math.cos(2*R) + Hyperbolic.cos(2*I)));} public Complex sinh() {Complex e=exp(); e.subtract(Complex.multiply(this,-1).exp()); e.divide(2); return e;} public Complex cosh() {Complex e=exp(); e.add(Complex.multiply(this,-1).exp()); e.divide(2); return e;} public Complex tanh() {Complex e=exp(),e2=new Complex(e),i=Complex.multiply(this,-1).exp(); e.subtract(i); e2.add(i); e.divide(e2); return e;} public Complex asinh() {Complex s=multiply(this,this); s.add(1); s=pow(s,.5); s.add(this); return s.log();} public Complex acosh() {Complex s=multiply(this,this); s.subtract(1); s=pow(s,.5); s.add(this); return s.log();} //The next three functions may not be reliable. Check them at some point! public Complex atanh() {Complex p1=add(this,1); p1.divide(subtract(this,1)); p1=p1.log(); p1.divide(2); return p1;} public Complex asech() {Complex i=divide(1,this),i2=multiply(i,i); i2.subtract(1); i.add(i2.log()); return i.log();} public Complex acsch() {Complex i=divide(1,this),i2=multiply(i,i); i2.add(1); i.add(i2.log()); return i.log();} public Complex acoth() {Complex p=add(this,1),m=subtract(this,1); p.divide(m); p=p.log(); p.divide(2); return p;} public static Complex i() {return new Complex(0,1);} public String rectString() { StringBuffer sb=new StringBuffer(35); if(R!=0) { sb.append(R); if(I>0) sb.append('+'); } if(I!=0) { sb.append(I); sb.append('i'); } return sb.toString(); } public String polarString() { StringBuffer sb=new StringBuffer(40); double t=mag(); if(t!=1) sb.append(t); t=arg(); if(t!=0) { sb.append("e^("); if(t!=1) sb.append(t); sb.append("i)"); } return sb.toString(); } public String toString() {return getClass().getName()+'['+R+','+I+']';} }
/* * (C) Mississippi State University 2009 * * The WebTOP employs two licenses for its source code, based on the intended use. The core license for WebTOP applications is * a Creative Commons GNU General Public License as described in http://*creativecommons.org/licenses/GPL/2.0/. WebTOP libraries * and wapplets are licensed under the Creative Commons GNU Lesser General Public License as described in * http://creativecommons.org/licenses/*LGPL/2.1/. Additionally, WebTOP uses the same licenses as the licenses used by Xj3D in * all of its implementations of Xj3D. Those terms are available at http://www.xj3d.org/licenses/license.html. */ //Mutex.java //Defines the class Mutex, for flexible thread control. //Davis Herring //Created October 9 2002 //Updated March 25 2004 //Version 1.1 package org.sdl.util; /*/ import java.awt.*; import java.awt.event.*; //*/ /** * Provides long-term object locking akin to the behavior of 'synchronized'. */ public class Mutex extends ThreadLock { /** * Object used for internal synchronization. */ private final Object _lock=new Object(); /** * A reference to the Thread object for the thread that owns this Mutex, * or null if none does. */ private Thread owner; /** * A flag indicating that this Mutex has been made private and will not * reveal references to its owner. */ private boolean priv; /** * Any AbandonedException waiting to be thrown in threads waiting on this * Mutex. */ private AbandonedException ae; /** * Constructs a Mutex. */ public Mutex() {} /** * Constructs a named Mutex. */ public Mutex(String name) {super(name);} /** * Locks this Mutex, blocking until the lock is acquired. Does nothing and * returns silently if this thread has already locked this object. * * @exception InterruptedException the current thread was interrupted while * waiting to acquire the ThreadLock. */ public void lock() throws InterruptedException { synchronized(_lock) { if(mine()) return; while(isLocked()) _lock.wait(); owner=Thread.currentThread(); if(ae!=null) throw ae; } } /** * Attempts to lock this Mutex. If this Mutex is already locked by another * thread, returns false immediately. * * @return true if the lock was acquired; false if it was already locked */ public boolean tryLock() {synchronized(_lock) {return tryLock0();}} /** * Unlocks this Mutex, which must have been most recently locked by this * thread. However, if the mutex is unlocked, does nothing and returns * silently. * * @exception IllegalStateException if this Mutex is locked but not by the * current thread. */ public void unlock() { synchronized(_lock) { if(!isLocked()) return; if(!mine()) throw new IllegalStateException("This thread doesn't own this Mutex."); ae=null; //This thread didn't abandon it unlock0(); } } /** * Removes the lock, waking up any waiting threads. */ private void unlock0() { synchronized(_lock) { owner=null; _lock.notify(); } } /** * Checks whether this Mutex is locked. * * @return true if this Mutex has been locked by a thread and not yet * unlocked; false otherwise. */ public boolean isLocked() { synchronized(_lock) { if(owner==null) return false; if(owner.isAlive()) return true; unlock0(); //Oops, we've been abandoned. Make exception to be thrown (somewhere). //This can need to know the return value of this very function, so we //make this after unlocking (recursive calls will just return false). //There is no race condition because we've held the _lock since before //the notify(), and don't release it until ae has been assigned. ae=new AbandonedException(this,priv?null:owner); return false; } } /** * Checks whether this Mutex is ownable. <code>Mutex</code>es are ownable. * * @return true */ public boolean isOwnable() {return true;} /** * Returns the thread owning this Mutex. * * @see #makePrivate * @return a reference to the Thread that owns this Mutex, or null if it is * unlocked. Also null if makePrivate() has been called. */ public Thread getOwner() { synchronized(_lock) { if(!isLocked()) return null; return priv?null:owner; } } /** * Checks whether the current thread owns this Mutex. * * @return true if the current thread has locked this Mutex most recently; * false otherwise. */ public boolean mine() {return owner==Thread.currentThread();} /** * Causes this Mutex to be private, preventing it from revealing its owner. * This operation cannot be reversed. * * @see #isPrivate */ public void makePrivate() {priv=true;} /** * Checks whether this Mutex is private. * * @see #makePrivate * @return true if this Mutex will not reveal owners; false otherwise. */ public boolean isPrivate() {return priv;} /*/ public static void main(String[] args) { Label n=new Label("0"); final Frame f=new Frame("MutexTest"); f.setBounds(100,100,400,400); f.add(n); f.show(); class PokeableThread extends Thread implements MouseListener { private final Mutex mutex; private final Label label; private final int delta; private volatile boolean seppuku,letgo; public PokeableThread(Mutex m,Label l,int dx) {mutex=m;label=l;delta=dx;} public void mouseClicked(MouseEvent e) { letgo=true; interrupt(); } public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void run() { while(!seppuku) { try { System.out.println(this+": locking..."); mutex.lock(); // It's possible to miss an interrupt() here; a thread that is // both notify()ed and interrupt()ed will (at least sometimes) // wake up in the manner of the notify, and lose the interrupted // status which would cause the Thread.sleep() call below to // throw. This is probably just an indication that calls to // Mutex::lock() should, like those to Object.wait(), be put, with // their catch(InterruptedException e) blocks, in // condition-checking while loops. But this is fine for here. if(seppuku) break; System.out.println(this+": locked! Printing/sleeping..."); label.setText(""+(Integer.parseInt(label.getText())+delta)); Thread.sleep(2500); System.out.println(this+": done sleeping"); } catch(InterruptedException e) { System.out.println(this+": <interrupted...>"); //This effectively randomizes the order of interruption try { Thread.sleep((long)(Math.random()*50)); } catch(InterruptedException ie) {} // again?! System.out.println(this+": <interrupted>"); if(letgo) { System.out.println(this+": letting go"); letgo=false; if(mutex.mine()) mutex.unlock(); Thread.yield(); } } } if(mutex.mine()) mutex.unlock(); //don't be a deadbeat System.out.println(this+": done."); } public void kill() { System.out.print(this+"::kill()... "); seppuku=true; interrupt(); System.out.println("interrupt sent (to "+this+')'); } } final Mutex mtx=new Mutex(); final PokeableThread t1=new PokeableThread(mtx,n,1), t2=new PokeableThread(mtx,n,-1); t1.start(); t2.start(); n.addMouseListener(t1); n.addMouseListener(t2); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { t1.kill(); t2.kill(); f.setVisible(false); while(true) try { System.out.println("Joins: 0"); t1.join(); System.out.println("Joins: 1"); t2.join(); System.out.println("Joins: 2"); break; } catch(InterruptedException ie) { System.out.println("Joins: <interrupted>"); } System.exit(0); } }); System.out.println("main(): done"); }//*/ }
/* * 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.dao; import com.innovaciones.reporte.model.DetalleEgresoInventario; import java.util.List; /** * * @author fyaulema */ public interface DetalleEgresoInventarioDAO { public DetalleEgresoInventario addDetalleEgresoInventario(DetalleEgresoInventario detalleEgresoInventario); public List<DetalleEgresoInventario> getDetalleEgresoInventarios(); public DetalleEgresoInventario getDetalleEgresoInventarioById(Integer id); public DetalleEgresoInventario getDetalleEgresoInventarioByCodigo(String codigo); public List<DetalleEgresoInventario> getDetalleEgresoInventariosByEstado(Integer estado); public List<DetalleEgresoInventario> getDetalleEgresoInventarioByIdCabeceraEgreso(Integer idCabeceraEgreso, Integer estado); public List<DetalleEgresoInventario> getDetalleEgresosInventarioByIdClienteSucursal(Integer idClienteSucursal); }
package com.example.yui.games; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; public class SettingTime1 extends AppCompatActivity { private RadioButton radio_time1; private RadioButton radio_time2; private RadioButton radio_time3; private RadioGroup radiogroup; private int selectTime; Button save; Intent intent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.setting_time_1); save = (Button) findViewById(R.id.buttonsave); save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { intent = new Intent(getApplication(), Game_Animal__6_picture.class); intent.putExtra("timeset",selectTime); startActivity(intent); } }) ; //radio_time1.setChecked(true); // radio_time1 = (RadioButton) findViewById(R.id.radio_time1); // radio_time1.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // // selectTime = 10; // Toast.makeText(SettingTime.this, " 10.", // Toast.LENGTH_SHORT).show(); // // // } // }); // // radio_time2 = (RadioButton) findViewById(R.id.radio_time2); // radio_time2.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // selectTime = 15; // Toast.makeText(SettingTime.this, " 15.", // Toast.LENGTH_SHORT).show(); // // // } // }); // // radio_time3 = (RadioButton) findViewById(R.id.radio_time3); // radio_time3.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // selectTime = 20; // Toast.makeText(SettingTime.this, " 20.", // Toast.LENGTH_SHORT).show(); // // } // }); } public void onRadioButtonClicked(View view) { // Is the button now checked? boolean checked = ((RadioButton) view).isChecked(); // Check which radio button was clicked switch (view.getId()) { case R.id.radio_time1: if (checked) selectTime = 10000; // intent.putExtra("timeset",selectTime); Toast.makeText(SettingTime1.this, " 10.", Toast.LENGTH_SHORT).show(); // Pirates are the best break; case R.id.radio_time2: if (checked) selectTime = 15000; // intent.putExtra("timeset",selectTime); Toast.makeText(SettingTime1.this, " 15.", Toast.LENGTH_SHORT).show(); // Ninjas rule break; case R.id.radio_time3: if (checked) selectTime = 20000; // intent.putExtra("timeset",selectTime); Toast.makeText(SettingTime1.this, " 20.", Toast.LENGTH_SHORT).show(); // Ninjas rule break; default: selectTime = 10000 ; break; } } }
package com.trump.auction.cust.api.impl; import com.cf.common.utils.ServiceResult; import com.trump.auction.cust.CustApplication; import com.trump.auction.cust.domain.UserShippingAddress; import com.trump.auction.cust.service.UserShippingAddressService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import static org.junit.Assert.*; /** * Author: zhanping */ @RunWith(SpringRunner.class) @SpringBootTest(classes = CustApplication.class) @Transactional @Rollback public class UserShippingAddressStuServiceImplTest { @Autowired private UserShippingAddressService userShippingAddressService; @Test public void insertUserAddressItem() throws Exception { UserShippingAddress address = new UserShippingAddress(); address.setUserId(342); address.setUserName("111112444"); address.setAddressType(0); address.setStatus(0); ServiceResult result = userShippingAddressService.insertUserAddressItem(address); Integer id = address.getId(); } }
package com.base.utils; import java.util.Map; import java.util.Set; import com.base.host.HostApplication; import com.heihei.model.msg.due.DueMessageUtils; import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; /** * SharedPreferences工具类 */ public class SharedPreferencesUtil { private SharedPreferences sp; private Editor editor; private static SharedPreferencesUtil mSharedPreferences; public static SharedPreferencesUtil getInstance() { if (mSharedPreferences == null) { synchronized (SharedPreferencesUtil.class) { if (mSharedPreferences == null) { mSharedPreferences = new SharedPreferencesUtil(HostApplication.getInstance()); } } } return mSharedPreferences; } public final static String name = "vmlives_heihei"; @SuppressWarnings("deprecation") public static int mode = Context.MODE_MULTI_PROCESS;// 进程间数据共享(代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容) @SuppressLint("CommitPrefEdits") public SharedPreferencesUtil(Context context) { this.sp = context.getSharedPreferences(name, mode); this.editor = sp.edit(); } /** * 创建一个工具类,默认打开名字为name的SharedPreferences实例 * * @param context * @param name * 唯一标识 * @param mode * 权限标识 */ @SuppressLint("CommitPrefEdits") public SharedPreferencesUtil(Context context, String name, int mode) { this.sp = context.getSharedPreferences(name, mode); this.editor = sp.edit(); } /** * 添加信息到SharedPreferences * * @param name * @param map * @throws Exception */ public void add(Map<String, String> map) { Set<String> set = map.keySet(); for (String key : set) { editor.putString(key, map.get(key)); } editor.commit(); } public void setValueStr(String key, String val) { editor.putString(key, val).commit(); } public void setValueInt(String key, Integer val) { editor.putInt(key, val).commit(); } public void setValueLong(String key, Long val) { editor.putLong(key, val).commit(); } public void setValueBoolean(String key, Boolean val) { editor.putBoolean(key, val).commit(); } /** * 删除信息 * * @throws Exception */ public void deleteAll() throws Exception { editor.clear(); editor.commit(); } /** * 删除一条信息 */ public void delete(String key) { editor.remove(key); editor.commit(); } /** * String 获取信息 * * @param key * @return * @throws Exception */ public String get(String key, String delVal) { if (sp != null) { return sp.getString(key, delVal); } return delVal; } /** * Integer 获取信息 * * @param key * @return * @throws Exception */ public Integer get(String key, Integer delVal) { if (sp != null) { return sp.getInt(key, delVal); } return delVal; } /** * Long 获取信息 * * @param key * @return * @throws Exception */ public Long get(String key, Long delVal) { if (sp != null) { return sp.getLong(key, delVal); } return delVal; } public Boolean get(String key, Boolean delVal) { if (sp != null) { return sp.getBoolean(key, delVal); } return delVal; } /** * 获取此SharedPreferences的Editor实例 * * @return */ public Editor getEditor() { return editor; } }
package telas; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JTextField; import java.awt.Font; import javax.swing.SwingConstants; import javax.swing.JTextPane; import javax.swing.JLabel; import javax.swing.JButton; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Principal implements ActionListener{ public JFrame frame; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Principal window = new Principal(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public Principal() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize(){ frame = new JFrame(); frame.getContentPane().setBackground(Color.WHITE); frame.setBounds(100, 100, 694, 459); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); JLabel lblNomeSistema = new JLabel("MMPP System"); lblNomeSistema.setBounds(109, 84, 404, 61); lblNomeSistema.setHorizontalAlignment(SwingConstants.CENTER); lblNomeSistema.setFont(new Font("Sitka Small", Font.BOLD | Font.ITALIC, 30)); frame.getContentPane().add(lblNomeSistema); JButton btnCadastrar = new JButton("Cadastrar"); btnCadastrar.setBounds(50, 218, 131, 60); btnCadastrar.setForeground(Color.WHITE); btnCadastrar.setFont(new Font("Times New Roman", Font.BOLD, 20)); btnCadastrar.setBackground(Color.DARK_GRAY); frame.getContentPane().add(btnCadastrar); btnCadastrar.addActionListener(this); JButton btnEntrada = new JButton("Entrada"); btnEntrada.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { EntradaTela entrada = new EntradaTela(); entrada.frame.setVisible(true); } }); btnEntrada.setBounds(262, 218, 131, 60); btnEntrada.setForeground(Color.WHITE); btnEntrada.setFont(new Font("Times New Roman", Font.BOLD, 20)); btnEntrada.setBackground(Color.DARK_GRAY); frame.getContentPane().add(btnEntrada); JButton btnSaída = new JButton("Sa\u00EDda"); btnSaída.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SaidaTela saida = new SaidaTela(); saida.frame.setVisible(true); } }); btnSaída.setBounds(475, 218, 131, 60); btnSaída.setForeground(Color.WHITE); btnSaída.setFont(new Font("Times New Roman", Font.BOLD, 20)); btnSaída.setBackground(Color.DARK_GRAY); frame.getContentPane().add(btnSaída); } public void actionPerformed(ActionEvent e) { //if(e.getSource() == btnCadastrar){ CadastroTela cadastro = new CadastroTela(); cadastro.frame.setVisible(true); } } //}
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.vootoo.search; import java.util.*; import org.apache.lucene.queries.function.ValueSource; import org.apache.solr.common.params.SolrParams; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.search.SyntaxError; import org.apache.solr.search.function.ValueSourceRangeFilter; import org.vootoo.search.function.filter.BitCollectorFilterablePlugin; import org.vootoo.search.function.filter.BitContainCollectorFilterablePlugin; import org.vootoo.search.function.filter.InCollectorFilterablePlugin; import org.vootoo.search.function.filter.RangeCollectorFilterablePlugin; /** * {@link CollectorFilterable} build plugin */ public abstract class CollectorFilterablePlugin { public static final Map<String,CollectorFilterablePlugin> standardPlugins = new HashMap<String,CollectorFilterablePlugin>(); static { standardPlugins.put("in", new InCollectorFilterablePlugin()); standardPlugins.put("range", new RangeCollectorFilterablePlugin()); standardPlugins.put("bit", new BitCollectorFilterablePlugin()); standardPlugins.put("cbit", new BitContainCollectorFilterablePlugin()); } /** return a {@link CollectorFilterable} */ public abstract CollectorFilterable createCollectorFilterable(String qstr, SolrParams localParams, SolrParams params, SolrQueryRequest req, ValueSource valueSource, String valueStr) throws SyntaxError; public abstract String getName(); public void verifyValueStr(String valueStr, ValueSource valueSource) throws SyntaxError { if (valueStr == null) { throw new SyntaxError("cf=" + getName() + " '" + valueSource.description() + "' value is null"); } valueStr = valueStr.trim(); if (valueStr.length() < 1) { throw new SyntaxError("cf=" + getName() + " '" + valueSource.description() + "' value is blank"); } } /** * @param valueStr * format is :<i>x or (x[<, n>...])</i> * @param splitStr * null is ',' * @param requireValue is true value is not blank * @return list value * @throws SyntaxError format error */ public static List<String> parseMultiValue(String valueStr, String splitStr, boolean requireValue) throws SyntaxError { if (splitStr == null) { splitStr = ","; } valueStr = valueStr.trim(); List<String> lvs = new ArrayList<String>(); if ('(' == valueStr.charAt(0)) { if (')' == valueStr.charAt(valueStr.length() - 1)) { String vstr = valueStr.substring(1, valueStr.length() - 1); String[] vs = vstr.split(splitStr); if (vs == null || vs.length < 1) { throw new SyntaxError("value format is 'x or (x[<, n>...])'! q=" + valueStr); } for (String s : vs) { if (s != null) { s = s.trim(); if (s.length() > 0) { lvs.add(s); } } } } else { throw new SyntaxError( "value format is 'x or (x[<, n>...])', miss ')' q=" + valueStr); } } else { // single lvs.add(valueStr); } if (requireValue && lvs.size() < 1) { throw new SyntaxError( "value format is 'x or (x[<, n>...])', not values! q=" + valueStr); } return lvs; } /** * @param rangeValue * [|(v1 TO v2)|] * * @throws SyntaxError if format error */ public static ValueSourceRangeFilter parseRange(ValueSource vs, String rangeValue) throws SyntaxError { boolean includeLower = true; boolean includeUpper = true; if(rangeValue == null) { throw new SyntaxError("range query format error, rangeValue is null"); } rangeValue = rangeValue.trim(); // "[ TO ]".length if (rangeValue.length() < 6) { throw new SyntaxError("range query format error, rangeValue=" + rangeValue); } char ch = rangeValue.charAt(0); if (ch == '(') { includeLower = false; } else { if (ch != '[') { throw new SyntaxError( "range query lower char must be '(' or '[', rangeValue=" + rangeValue); } } ch = rangeValue.charAt(rangeValue.length() - 1); if (ch == ')') { includeUpper = false; } else { if (ch != ']') { throw new SyntaxError( "range query upper char must be ')' or ']', rangeValue=" + rangeValue); } } String l = null; String u = null; String[] values = rangeValue.substring(1, rangeValue.length() - 1) .split("\\ TO\\ "); if (values == null || values.length < 2) { throw new SyntaxError("range query format error, rangeValue=" + rangeValue); } values[0] = values[0].trim(); values[1] = values[1].trim(); if (values[0].length() > 0 && !values[0].equals("*")) { l = values[0]; } if (values[1].length() > 0 && !values[1].equals("*")) { u = values[1]; } return new ValueSourceRangeFilter(vs, l, u, includeLower, includeUpper); } private static Map<String, Boolean> radix_16; static { Map<String, Boolean> map = new HashMap<>(4); // 16 radix map.put("0x", Boolean.TRUE); map.put("0X", Boolean.TRUE); // 2 radix map.put("0b", Boolean.FALSE); map.put("0B", Boolean.FALSE); radix_16 = Collections.unmodifiableMap(map); } /** * Long.parseLong and can parse 0x or 0b radix number * @throws NumberFormatException */ public static Long parseLongExt(String longStr) { try { return Long.parseLong(longStr); } catch (NumberFormatException e) { if(longStr.length() > 2) { //try parse 0x or 0b String lstr = longStr.substring(0, 2); Boolean isRadix16 = radix_16.get(lstr); if(isRadix16 == null) { throw e; } else { if(isRadix16) { return Long.parseLong(longStr.substring(2), 16); } else { return Long.parseLong(longStr.substring(2), 2); } } } else { throw e; } } } }
package org.example.codingtest.z_quiz.array_string; import com.google.common.collect.Lists; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * input 으로 txt 와 pat 문자열이 주어질 때, txt 문자열 내에 순서와 상관없이 pat 문자열이 포함되어 있는 인덱스의 위치를 리턴하라. * * EX) * txt = "BACDGABCDA" * pat = "ABCD" * * output = [0, 5, 6] **/ public class FindAllAnagrams { private static FindAllAnagrams o = new FindAllAnagrams(); public static void main(String[] args) { String txt = "BACDGABCDA"; String pat = "ABCD"; int[] solution = o.solution(txt, pat); Arrays.stream(solution).forEach(System.out::println); } /** * 1. txt 를 pat 의 크기만큼 잘라서 정렬한 뒤 * 2. pat 와 같은지 비교 * 3. 같다면 output 에 담기 **/ public int[] solution(String txt, String pat){ List<Integer> list = Lists.newArrayList(); int length = pat.length(); String patSorted = sorted(pat); for (int i = 0; i <= txt.length()-length; i++) { String substring = txt.substring(i, i + length); String sorted = sorted(substring); if (patSorted.equals(sorted)) list.add(i); } return list.stream().mapToInt(Integer::intValue).toArray(); } public String sorted(String str){ String[] strings = new String[str.length()]; for (int i = 0; i < str.length(); i++) { strings[i] = String.valueOf(str.charAt(i)); } return Arrays.stream(strings).sorted().collect(Collectors.joining("")); } }
/* * 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.neo.heladeria.entities; import com.fasterxml.jackson.annotation.JsonIgnore; import java.io.Serializable; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author laura.romerot */ @Entity @Table(name = "cashier") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Cashier.findAll", query = "SELECT c FROM Cashier c"), @NamedQuery(name = "Cashier.findByIdCashier", query = "SELECT c FROM Cashier c WHERE c.idCashier = :idCashier"), @NamedQuery(name = "Cashier.findByName", query = "SELECT c FROM Cashier c WHERE c.name = :name"), @NamedQuery(name = "Cashier.findByLastame", query = "SELECT c FROM Cashier c WHERE c.lastame = :lastame"), @NamedQuery(name = "Cashier.findByLimitCashier", query = "SELECT c FROM Cashier c WHERE c.limitCashier = :limitCashier")}) public class Cashier implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id_cashier") private Integer idCashier; @Column(name = "name") private String name; @Column(name = "lastame") private String lastame; @Column(name = "limit_cashier") private String limitCashier; @OneToMany(cascade = CascadeType.ALL, mappedBy = "cashierIdCashier") @JsonIgnore private List<ListOrder> listOrderList; public Cashier() { } public Cashier(Integer idCashier) { this.idCashier = idCashier; } public Integer getIdCashier() { return idCashier; } public void setIdCashier(Integer idCashier) { this.idCashier = idCashier; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLastame() { return lastame; } public void setLastame(String lastame) { this.lastame = lastame; } public String getLimitCashier() { return limitCashier; } public void setLimitCashier(String limitCashier) { this.limitCashier = limitCashier; } @XmlTransient public List<ListOrder> getListOrderList() { return listOrderList; } public void setListOrderList(List<ListOrder> listOrderList) { this.listOrderList = listOrderList; } @Override public int hashCode() { int hash = 0; hash += (idCashier != null ? idCashier.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Cashier)) { return false; } Cashier other = (Cashier) object; if ((this.idCashier == null && other.idCashier != null) || (this.idCashier != null && !this.idCashier.equals(other.idCashier))) { return false; } return true; } @Override public String toString() { return "com.neo.heladeria.entities.Cashier[ idCashier=" + idCashier + " ]"; } }
package io.nuls.consensus.model.dto.output; import io.nuls.consensus.model.bo.tx.txdata.Agent; import io.nuls.base.basic.AddressTool; import io.nuls.core.crypto.HexUtil; import io.nuls.core.model.BigIntegerUtils; import io.nuls.core.rpc.model.ApiModel; import io.nuls.core.rpc.model.ApiModelProperty; /** * 节点基础信息类 * Node basic information class * * @author tag * 2018/11/20 */ @ApiModel(name = "节点基础信息") public class AgentBasicDTO { @ApiModelProperty(description = "节点地址") private String agentAddress; @ApiModelProperty(description = "节点出块地址") private String packingAddress; @ApiModelProperty(description = "抵押金额") private String deposit; @ApiModelProperty(description = "是否为种子节点") private boolean isSeedNode; @ApiModelProperty(description = "公钥") private String pubKey; @ApiModelProperty(description = "节点HASH") private String agentHash; @ApiModelProperty(description = "奖励地址") private String rewardAddress; public AgentBasicDTO(Agent agent){ this.agentAddress = AddressTool.getStringAddressByBytes(agent.getAgentAddress()); this.packingAddress = AddressTool.getStringAddressByBytes(agent.getPackingAddress()); this.deposit = BigIntegerUtils.bigIntegerToString(agent.getDeposit()); this.isSeedNode = false; if(agent.getPubKey() != null){ this.pubKey = HexUtil.encode(agent.getPubKey()); } this.agentHash = agent.getTxHash().toHex(); this.rewardAddress = AddressTool.getStringAddressByBytes(agent.getRewardAddress()); } public AgentBasicDTO(String packingAddress,String pubKey){ this.packingAddress = packingAddress; this.isSeedNode = true; this.pubKey = pubKey; } public String getAgentAddress() { return agentAddress; } public void setAgentAddress(String agentAddress) { this.agentAddress = agentAddress; } public String getPackingAddress() { return packingAddress; } public void setPackingAddress(String packingAddress) { this.packingAddress = packingAddress; } public String getDeposit() { return deposit; } public void setDeposit(String deposit) { this.deposit = deposit; } public boolean isSeedNode() { return isSeedNode; } public void setSeedNode(boolean seedNode) { isSeedNode = seedNode; } public String getPubKey() { return pubKey; } public void setPubKey(String pubKey) { this.pubKey = pubKey; } public String getAgentHash() { return agentHash; } public void setAgentHash(String agentHash) { this.agentHash = agentHash; } public String getRewardAddress() { return rewardAddress; } public void setRewardAddress(String rewardAddress) { this.rewardAddress = rewardAddress; } }
/* * MIT License * * Copyright (c) 2023 Glare * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.glaremasters.guilds.database.cooldowns.provider; import me.glaremasters.guilds.cooldowns.Cooldown; import me.glaremasters.guilds.database.cooldowns.CooldownProvider; import me.glaremasters.guilds.database.cooldowns.CooldownRowMapper; import org.jdbi.v3.sqlobject.config.RegisterRowMapper; import org.jdbi.v3.sqlobject.customizer.Bind; import org.jdbi.v3.sqlobject.customizer.Define; import org.jdbi.v3.sqlobject.statement.SqlQuery; import org.jdbi.v3.sqlobject.statement.SqlUpdate; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.sql.Timestamp; import java.util.List; public interface CooldownMariaDBProvider extends CooldownProvider { @Override @SqlUpdate( "CREATE TABLE IF NOT EXISTS <prefix>cooldowns (\n" + " `id` VARCHAR(36) NOT NULL,\n" + " `type` VARCHAR(36) NOT NULL,\n" + " `owner` VARCHAR(36) NOT NULL,\n" + " `expiry` TIMESTAMP NOT NULL,\n" + " PRIMARY KEY (`id`),\n" + " UNIQUE (`id`));" ) void createContainer(@Define("prefix") @NotNull String prefix); @Override @SqlQuery("SELECT EXISTS(SELECT 1 FROM <prefix>cooldowns WHERE type = :type AND owner = :owner)") boolean cooldownExists(@Define("prefix") @NotNull String tablePrefix, @NotNull @Bind("type") String cooldownType, @NotNull @Bind("owner") String cooldownOwner) throws IOException; @Override @SqlQuery("SELECT * FROM <prefix>cooldowns") @RegisterRowMapper(CooldownRowMapper.class) List<Cooldown> getAllCooldowns(@Define("prefix") @NotNull String prefix); @Override @SqlUpdate("INSERT INTO <prefix>cooldowns(id, type, owner, expiry) VALUES (:id, :type, :owner, :expiry)") void createCooldown(@Define("prefix") @NotNull String prefix, @NotNull @Bind("id") String id, @NotNull @Bind("type") String type, @NotNull @Bind("owner") String owner, @NotNull @Bind("expiry") Timestamp expiry); @Override @SqlUpdate("DELETE FROM <prefix>cooldowns WHERE type = :type AND owner = :owner") void deleteCooldown(@Define("prefix") @NotNull String prefix, @NotNull @Bind("type") String type, @NotNull @Bind("owner") String owner) throws IOException; }
package com.example.snapup_android.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; @Data @AllArgsConstructor @NoArgsConstructor public class TrainSerial { private int serial; private Date date; private String run_code; }
/* Ara - capture species and specimen data * * Copyright (C) 2009 INBio ( Instituto Nacional de Biodiversidad ) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.inbio.ara.util; import java.util.StringTokenizer; public class ElementLabelXml { private String strongLabel; private String emLabel; private String labelSize; private String labelStyle; private String elementName; private String value; public ElementLabelXml(String value, String name, String em, String size, String style, String strong) { this.value = value; this.elementName = name; this.emLabel = em; this.labelSize = this.getValueOfElement(size); this.labelStyle = this.getValueOfElement(style); this.strongLabel = strong; } /** * get the element of the cadena who contains the style or size * @param cadena * @return */ public String getValueOfElement(String cadena) { String resp = null; if (cadena != null && cadena.length() > 0 ) { StringTokenizer token = new StringTokenizer(cadena, ":"); while (token.hasMoreTokens()) { resp = token.nextToken(); } } return resp; } /** * This method takes the object and transforms the object into a string with html format * @return the element in html format */ @Override public String toString() { StringBuffer sb = new StringBuffer(); if (this.getEmLabel() != null && this.getStrongLabel() != null && this.getLabelSize() != null && this.getLabelStyle() != null) { sb.append("<p style='text-align:" + this.getLabelStyle() + " ;'> <span style = 'font-size:' " + this.getLabelSize() + "> <em> <strong> " + this.getValue() + " </strong> </em> </spam> </p>"); } else if (this.getEmLabel() != null && this.getLabelSize() != null && this.getLabelStyle() != null) { sb.append("<p style='text-align:" + this.getLabelStyle() + " ;'> <span style = 'font-size:' " + this.getLabelSize() + "> <em> " + this.getValue() + " </em> </spam> </p>"); } else if (this.getStrongLabel()!= null && this.getLabelSize() != null && this.getLabelStyle() != null) { sb.append("<p style='text-align:" + this.getLabelStyle() + " ;'> <span style = 'font-size:' " + this.getLabelSize() + "> <strong> " + this.getValue() + " </strong> </spam> </p>"); } else if (this.getEmLabel() != null && this.getStrongLabel() != null && this.getLabelStyle() != null) { sb.append("<p style = 'text-align:" + this.getLabelStyle() + "'> <em> <strong> " + this.getValue() + " </strong> </em> </p>"); } else if (this.getEmLabel() != null && this.getStrongLabel() != null && this.getLabelSize() != null) { sb.append("<p> <span style = 'font-size:" + this.getLabelSize() + "'> <em> <strong> " + this.getValue() + " </strong> </em> </spam> </p>"); } else if (this.getEmLabel() != null && this.getLabelSize() != null && this.getLabelStyle() != null) { sb.append("<p style='text-align:" + this.getLabelStyle() + " ;'> <span style = 'font-size:" + this.getLabelSize() + "'> <em> " + this.getValue() + " </em> </spam> </p>"); } else if (this.getStrongLabel()!= null && this.getLabelSize() != null && this.getLabelStyle() != null) { sb.append("<p style='text-align:" + this.getLabelStyle() + " ;'> <span style = 'font-size: " + this.getLabelSize() + "'> <strong> " + this.getValue() + " </strong> </spam> </p>"); } else if (this.getEmLabel() != null && this.getLabelStyle() != null) { sb.append("<p style = 'text-align:" + this.getLabelStyle() + "'> <em> " + this.getValue() + " </em> </spam> </p>"); } else if (this.getStrongLabel() != null && this.getLabelStyle() != null) { sb.append("<p style = 'text-align: " + this.getLabelStyle() + "'> <strong> " + this.getValue() + " </strong> </p>"); } else if (this.getEmLabel() != null && this.getLabelSize() != null) { sb.append("<p> <span style = 'font-size:" + this.getLabelSize() + "'> <em> " + this.getValue() + " </em> </spam> </p>"); } else if (this.getStrongLabel() != null && this.getLabelSize() != null) { sb.append("<p> <span style = 'font-size: " + this.getLabelSize() + "'> <strong> " + this.getValue() + " </strong> </spam> </p>"); } else if (this.getEmLabel() != null && this.getStrongLabel() != null) { sb.append("<p > <em> <strong> " + this.getValue() + " </strong> </em> </p>"); } else if (this.getLabelStyle() != null) { sb.append("<p style = 'text-align:" + this.getLabelStyle() + " '>" + this.getValue() + " </p>"); } else if (this.getLabelSize() != null) { sb.append("<p> <span style = 'font-size: " + this.getLabelSize() + "'> " + this.getValue() + " </spam> </p>"); } else if (this.getEmLabel() != null) { sb.append("<p > <em> " + this.getValue() + " </em> </p>"); } else if (this.getStrongLabel() != null) { sb.append("<p > <strong> " + this.getValue() + " </strong> </p>"); } else if(this.getElementName().equals("Barcode")) { System.out.println("<p > " + this.getElementName() + " </p>"); } else { System.out.println("<p > " + this.getValue() + " </p>"); } return sb.toString(); } /** * @return the strongLabel */ public String getStrongLabel() { return strongLabel; } /** * @param strongLabel the strongLabel to set */ public void setStrongLabel(String strongLabel) { this.strongLabel = strongLabel; } /** * @return the emLabel */ public String getEmLabel() { return emLabel; } /** * @param emLabel the emLabel to set */ public void setEmLabel(String emLabel) { this.emLabel = emLabel; } /** * @return the labelSize */ public String getLabelSize() { return labelSize; } /** * @param labelSize the labelSize to set */ public void setLabelSize(String labelSize) { this.labelSize = labelSize; } /** * @return the labelStyle */ public String getLabelStyle() { return labelStyle; } /** * @param labelStyle the labelStyle to set */ public void setLabelStyle(String labelStyle) { this.labelStyle = labelStyle; } /** * @return the elementName */ public String getElementName() { return elementName; } /** * @param elementName the elementName to set */ public void setElementName(String elementName) { this.elementName = elementName; } /** * @return the value */ public String getValue() { return value; } /** * @param value the value to set */ public void setValue(String value) { this.value = value; } }
package com.zhiyou.service; import java.util.List; import com.zhiyou.model.Course; import com.zhiyou.model.Speaker; import com.zhiyou.model.Subject; import com.zhiyou.model.Video; import com.zhiyou.model.Videos; public interface SubjectService { public List<Subject> selectAll(); public Subject selectById(Integer subject_id); public List<Course> selectCourses(Integer subject_id); public List<Videos> selectVideos(Integer course_id); public List<Videos> selectVideos2(Integer speaker_id); public Course selectCourse(Integer course_id); public Video selectVideo(Integer video_id); public void updatePlay(Video video); public Speaker selectSpeaker(Integer speaker_id); }
package com.javarush.task.task26.task2601; import java.util.*; import java.util.stream.Collector; /* Почитать в инете про медиану выборки */ public class Solution { public static void main(String[] args) { /* Integer[] array = {13, 8, 15, 14, 5, 17}; System.out.println(Arrays.toString(sort(array)));*/ } public static Integer[] sort(Integer[] array) { //implement logic here if (array != null){ int mediana; Arrays.sort(array); if (array.length % 2 == 0) mediana = (array[array.length / 2 - 1] + array[ array.length / 2 ]) / 2; else mediana = array[array.length / 2]; System.out.println(mediana); Comparator<Integer> comparator = (o1, o2) -> { int result = Math.round(Math.abs(mediana - o1) - Math.abs(mediana - o2)); return (result == 0) ? (o1 - o2) : result; }; Arrays.sort(array, comparator); } return array; } }
import java.io.*; import java.util.Scanner; public class OrphanBook { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int su=0; int[]arr=new int[100]; for(int i=0;i<n;i++) { arr[i]=sc.nextInt(); su=su+arr[i]; } int re=0; if(su%n==0) { int t=su/n; for(int i=0;i<n;i++) { while(arr[i]<t) { arr[i]=arr[i]+1; re=re+1; } } System.out.print(re); } else System.out.print(-1); } }
package api.nivelensennanza; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping({"nivelensennanza"}) public class RestControladorNivelEnsennanza { @Autowired private ServicioNivelEnsennanza servicioNivelEnsennanza; /** * Este método corresponde al RF20. Adicionar Año Docente. * * @param nivelEnsennanza * @return {@link EntidadNivelEnsennanza} */ @PostMapping public EntidadNivelEnsennanza adicionarNivelEnsennanza(@RequestBody EntidadNivelEnsennanza nivelEnsennanza) { return servicioNivelEnsennanza.guardar(nivelEnsennanza); } /** * Este método corresponde al RF21. Mostrar año docente. * * @param id * @return {@link EntidadNivelEnsennanza} */ @GetMapping(path = {"{id}"}) public ResponseEntity<EntidadNivelEnsennanza> mostrarNivelEnsennanza(@PathVariable int id) { return servicioNivelEnsennanza.obtenerPorId(id) .map(record -> ResponseEntity.ok(record)) .orElse(ResponseEntity.notFound().build()); } /** * Este método corresponde al RF22. Editar año docente * * @param * @param nivelEnsennanza * @return {@link EntidadNivelEnsennanza} */ @PutMapping(path = "{id}") public ResponseEntity<EntidadNivelEnsennanza> editarNivelEnsennanza(@PathVariable int id, @RequestBody EntidadNivelEnsennanza nivelEnsennanza) { return servicioNivelEnsennanza.actualizar(id, nivelEnsennanza) .map(record -> ResponseEntity.ok(record)) .orElse(ResponseEntity.notFound().build()); } /** * Este método corresponde al RF23. Eliminar año docente * * @param id * @return {@link EntidadNivelEnsennanza} */ @DeleteMapping(path = "{id}") public ResponseEntity<EntidadNivelEnsennanza> eliminarNivelEnsennanza(@PathVariable int id) { return servicioNivelEnsennanza.eliminar(id) .map(record -> ResponseEntity.ok(record)) .orElse(ResponseEntity.notFound().build()); } /** * Este método corresponde al RF24. Mostrar listado de años docentes * * @return */ @GetMapping public List<EntidadNivelEnsennanza> mostrarListadoNivelEnsennanza() { return servicioNivelEnsennanza.listarTodos(); } }
package classes; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Iterator; import org.apache.log4j.Logger; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class WriteInExcel { Logger logger = Logger.getLogger(getClass()); int sheetNo; FileInputStream file = null; XSSFWorkbook workbook; XSSFSheet sheet; int resultCellNumber; public WriteInExcel(int sheetNo) { this.sheetNo=sheetNo; } public int fetchResultCellNumber() { Iterator<Cell> cellIterator = sheet.getRow(0).cellIterator(); while (cellIterator.hasNext()) { Cell cell = (Cell) cellIterator.next(); if (cell.getStringCellValue().equals("Result")) { return cell.getColumnIndex(); } } return -1; } public void updateResult(int rowCounter, boolean status) { try { file = new FileInputStream(new File("./ExcelFiles/DataInput.xlsx")); workbook = new XSSFWorkbook(file); sheet = workbook.getSheetAt(sheetNo); resultCellNumber = fetchResultCellNumber(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { // System.out.println("################################## rowCounter X ResultCellNumber="+rowCounter +" , "+resultCellNumber); Cell cell = sheet.getRow(rowCounter).getCell(resultCellNumber); logger.info("=========================================== Writing Result In DataInput File. ====================================================="); logger.info("Current DataInput Result = " +cell); if (status) { cell.setCellValue("Passed"); } else { cell.setCellValue("Failed"); } logger.info("DataInput Result = " +status); FileOutputStream outFile = new FileOutputStream(new File("./ExcelFiles/DataInput.xlsx")); workbook.write(outFile); outFile.flush(); outFile.close(); logger.info("=========================================== Result DataInput File Completed. ======================================================"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }catch (Exception e) { e.printStackTrace(); } finally { try { workbook.close(); file.close(); } catch (IOException e) { e.printStackTrace(); } } } public void close() { } }
package com.firedata.qtacker.service; import com.firedata.qtacker.service.dto.CompanyExternDTO; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.Optional; /** * Service Interface for managing {@link com.firedata.qtacker.domain.CompanyExtern}. */ public interface CompanyExternService { /** * Save a companyExtern. * * @param companyExternDTO the entity to save. * @return the persisted entity. */ CompanyExternDTO save(CompanyExternDTO companyExternDTO); /** * Get all the companyExterns. * * @param pageable the pagination information. * @return the list of entities. */ Page<CompanyExternDTO> findAll(Pageable pageable); /** * Get the "id" companyExtern. * * @param id the id of the entity. * @return the entity. */ Optional<CompanyExternDTO> findOne(Long id); /** * Delete the "id" companyExtern. * * @param id the id of the entity. */ void delete(Long id); /** * Search for the companyExtern corresponding to the query. * * @param query the query of the search. * * @param pageable the pagination information. * @return the list of entities. */ Page<CompanyExternDTO> search(String query, Pageable pageable); }
class A { public char x = 'A'; public void getX() { System.out.println("getX() from A. Value of x = " + x); } } class B extends A { //public char x = 'B'; public void getX() { System.out.println("getX() from B. Value of x = " + x); } } public class C extends B { public char x = 'C'; public void getX() { System.out.println("getX() from C. Value of x = " + x); } public static void main(String[] args) { A a = new A(); System.out.println("Value of a.x = " + a.x); //prints: Value of a.x = A a.getX(); //prints: getX() from A. Value of x = A B b = new B(); System.out.println("Value of b.x = " + b.x); //prints: Value of b.x = A b.getX(); //prints: getX() from B. Value of x = A C c = new C(); System.out.println("Value of c.x = " + c.x); //prints: Value of c.x = C c.getX(); //prints: getX() from C. Value of x = C System.out.println("-----------------------------"); A ac = new C(); System.out.println("Value of ac.x = " + ac.x); //prints: Value of ac.x = A ac.getX(); //prints: getX() from C. Value of x = C B bc = new C(); System.out.println("Value of bc.x = " + bc.x); //prints: Value of bc.x = A bc.getX(); //prints: getX() from C. Value of x = C C cc = new C(); System.out.println("Value of cc.x = " + cc.x); //prints: Value of cc.x = C cc.getX(); //prints: getX() from C. Value of x = C System.out.println("-----------------------------"); A aac = new C(); B bbc = new C(); C ccc = new C(); aac = bbc; System.out.println("Value of aac.x = " + aac.x); //prints: Value of aac.x = A aac.getX(); //prints: getX() from C. Value of x = C aac = ccc; System.out.println("Value of aac.x = " + aac.x); //prints: Value of aac.x = A aac.getX(); //prints: getX() from C. Value of x = C bbc = ccc; System.out.println("Value of bbc.x = " + bbc.x); //prints: Value of bbc.x = A bbc.getX(); //prints: getX() from C. Value of x = C System.out.println("-----------------------------"); A aaac = new C(); B bbbc = new C(); C cccc = new C(); bbbc = (B)aaac; System.out.println("Value of bbbc.x = " + bbbc.x); //prints: Value of bbbc.x = A bbbc.getX(); //prints: getX() from C. Value of x = C cccc = (C)aaac; System.out.println("Value of cccc.x = " + cccc.x); //prints: Value of cccc.x = C cccc.getX(); //prints: getX() from C. Value of x = C cccc = (C)bbbc; System.out.println("Value of cccc.x = " + cccc.x); //prints: Value of cccc.x = C cccc.getX(); //prints: getX() from C. Value of x = C } }
import java.util.*; class Q9 { public static void main(String[] args) throws InputMismatchException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); System.out.println("1. Display odd divisors"); System.out.println("2. Display even divisors"); int ch = sc.nextInt(); System.out.println(); for(int i = 1; i < n; i++) { if(n % i == 0) { if(ch == 1) { if(i % 2 != 0) System.out.print(i + " "); } if(ch == 2) { if(i % 2 == 0) System.out.print(i + " "); } } } System.out.println(); } }
package AcademyHaru.HaruE2EProject; import java.io.IOException; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import pageObjects.LandingPage; import pageObjects.LoginPage; import resources.Base; public class HomePageTest extends Base { //Need to call methods written in Base class, we will use Inheritance @Test(dataProvider = "getData") public void basePageNavigation(String Username, String Password) throws IOException { driver = initializeDriver(); driver.get("http://www.qaclickacademy.com/"); // Creating object to that class and invoke methods of it LandingPage lp = new LandingPage(driver); lp.getLogin().click(); LoginPage loginPage = new LoginPage(driver); loginPage.getEmail().sendKeys(Username); loginPage.getPassword().sendKeys(Password); loginPage.Submit().click(); } @DataProvider public Object[][] getData() { // rows stands for how many different data types test should run // column stands for how many values per each test Object[][] data = new Object[2][2]; // 0th row data[0][0] = "haru@gmail.com"; data[0][1] = "password"; // 1st row data[1][0] = "bhupi@gmail.com"; data[1][1] = "bhupi"; return data; } }
package com.sshfortress.dao.asset.mapper; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; import com.sshfortress.common.entity.AssetDst; import com.sshfortress.common.model.DstListByAssetId; import com.sshfortress.common.model.ListByDst; public interface AssetDstMapper { int deleteByPrimaryKey(Long id); int insert(AssetDst record); int insertSelective(AssetDst record); AssetDst selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(AssetDst record); int updateByPrimaryKeyWithBLOBs(AssetDst record); int updateByPrimaryKey(AssetDst record); /**删除某个目标*/ int delDstByDstId(@Param("dstId")Long dstId); /**先删除再增加*/ int delAssetDstByAssetId(@Param("assetId")Long assetId); /**批量增加资产的目标用户名和目标密码*/ int addAssetDstNamePsdByBatch(ArrayList<AssetDst> arrayList); /**查询某个资产下的所有目标用户名和密码*/ List<DstListByAssetId> getDstNamePsdListByAssetId(@Param("assetId")Long assetId); /**目标用户下拉框*/ List<ListByDst> dstListByAssetGroupId(@Param("assetGroupId")Long assetGroupId); /**查询某个资产组下除了某个资产及某个用户名以外的用户名集合 Map: assetId assetGroupId dstName*/ Long getDstListByExceptAssetIdDstName(Map<String,Object> m); }
package com.android.wendler.wendlerandroid.main.model; import android.annotation.SuppressLint; import android.content.SharedPreferences; import com.android.wendler.wendlerandroid.utils.SharedPrefUtils; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import java.util.ArrayList; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Created by QiFeng on 7/3/17. */ public class UserTest { @Rule public MockitoRule mMockitoRule = MockitoJUnit.rule(); @Mock SharedPreferences mSharedPreferences; private User mUser; private Gson mGson; @Before public void setup() { mGson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .excludeFieldsWithoutExposeAnnotation() .create(); ArrayList<Lift> mLifts = new ArrayList<>(); mLifts.add(new Lift("bench", 10, 0, 5)); mLifts.add(new Lift("squat", 10, 0 ,10)); mLifts.add(new Lift("overhead", 10, 0, 5)); mLifts.add(new Lift("deadlift", 10, 0, 10)); mUser = new User( "123", "Wi", "Huang", "qi@te.xome", mLifts ); assertNull(mUser.getToken()); mUser.setToken("12345"); assertEquals("12345", mUser.getToken()); } @Test public void loadUser(){ when(mSharedPreferences.getString(SharedPrefUtils.KEY_USER, "{}")).thenReturn(json); when(mSharedPreferences.getString(SharedPrefUtils.KEY_TOKEN, null)).thenReturn("test"); User.loadFromSP(mSharedPreferences, mGson); verify(mSharedPreferences).getString(SharedPrefUtils.KEY_USER, "{}"); verify(mSharedPreferences).getString(SharedPrefUtils.KEY_TOKEN, null); } @SuppressLint("CommitPrefEdits") @Test public void testWrite() { SharedPreferences.Editor editor = mock(SharedPreferences.Editor.class); when(mSharedPreferences.edit()).thenReturn(editor); User.saveToSP(mSharedPreferences, mUser, mGson); verify(editor).putString(SharedPrefUtils.KEY_TOKEN, mUser.getToken()); verify(editor).putString(SharedPrefUtils.KEY_USER, mGson.toJson(mUser)); } private static final String json = "{\n" + "\"token\" : \"test\",\n" + "\"_id\": \"108034432866128207149\",\n" + "\"first_name\": \"py\",\n" + "\"last_name\": \"huang\",\n" + "\"email\": \"csc113project1@gmail.com\",\n" + "\"__v\": 0,\n" + "\"lifts\": [\n" + "{\n" + "\"week\": 2,\n" + "\"name\": \"deadlift\",\n" + "\"max\": 20,\n" + "\"_id\": \"5963dfd2df6f8b0011f2b68d\",\n" + "\"advance\": 10\n" + "},\n" + "{\n" + "\"week\": 0,\n" + "\"name\": \"bench\",\n" + "\"max\": 0,\n" + "\"_id\": \"5963dfd2df6f8b0011f2b68c\",\n" + "\"advance\": 5\n" + "},\n" + "{\n" + "\"week\": 0,\n" + "\"name\": \"squat\",\n" + "\"max\": 0,\n" + "\"_id\": \"5963dfd2df6f8b0011f2b68b\",\n" + "\"advance\": 10\n" + "},\n" + "{\n" + "\"week\": 1,\n" + "\"name\": \"overhead\",\n" + "\"max\": 0,\n" + "\"_id\": \"5963dfd2df6f8b0011f2b68a\",\n" + "\"advance\": 5\n" + "}\n" + "]\n" + "}"; @Test public void gsonTest(){ User user = mGson.fromJson(json, User.class); assertEquals(user.getId(), "108034432866128207149"); assertEquals(user.getFirstName(), "py"); assertEquals(user.getLastName(), "huang"); assertEquals(user.getEmail(), "csc113project1@gmail.com"); assertEquals(user.getToken(), "test"); assertEquals(4, user.getLifts().size()); // System.out.println(gson.toJson(user)); } }
package com.kkb.imugraph; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; public class GraphView extends View { float pX; float pY; float mX; float mYR; float mYG; float mYB; Paint mainPaint = new Paint(); Paint drawPaint = new Paint(); Path drawPathR = new Path(); Path drawPathG = new Path(); Path drawPathB = new Path(); int w; int h; float x0; float x1; float yR; float yG; float yB; float xTxt; //********************************************************************************************// // // // Class Constructors // // // //********************************************************************************************// public GraphView(Context context) { super(context); } public GraphView(Context context, AttributeSet attrs) { super(context, attrs); } //********************************************************************************************// // // // Overriden Methods // // // //********************************************************************************************// @Override protected void onDraw(Canvas canvas) { w = this.getWidth(); h = this.getHeight(); x0 = (float)(w * 0.9); x1 = (float)(x0 + w * 0.05); yR = (float)(h * 0.05); yG = (float)(h * 0.1); yB = (float)(h * 0.15); xTxt = (float)(x1 + w*0.005); mainPaint.setColor(Color.BLACK); mainPaint.setStrokeWidth(2); canvas.drawLine(0, h/2, w, h/2, mainPaint); mainPaint.setColor(Color.RED); mainPaint.setStrokeWidth(3); canvas.drawLine(x0, yR, x1, yR, mainPaint); mainPaint.setColor(Color.GREEN); canvas.drawLine(x0, yG, x1, yG, mainPaint); mainPaint.setColor(Color.BLUE); canvas.drawLine(x0, yB, x1, yB, mainPaint); mainPaint.setColor(Color.BLACK); mainPaint.setTextSize(30); // canvas.drawText(Float.toString(mX) + "&" + Float.toString(mY), 10, 30, mainPaint); canvas.drawText("X", xTxt, (float) (h * 0.06), mainPaint); canvas.drawText("Y", xTxt, (float) (h * 0.11), mainPaint); canvas.drawText("Z", xTxt, (float) (h * 0.16), mainPaint); drawPaint.setColor(Color.RED); drawPaint.setStyle(Paint.Style.STROKE); drawPaint.setStrokeWidth(3); canvas.drawPath(drawPathR, drawPaint); drawPaint.setColor(Color.GREEN); canvas.drawPath(drawPathG, drawPaint); drawPaint.setColor(Color.BLUE); canvas.drawPath(drawPathB, drawPaint); } @Override public boolean onTouchEvent(MotionEvent me) { if(me.getAction() == MotionEvent.ACTION_DOWN) { return true; } else if(me.getAction() == MotionEvent.ACTION_MOVE) { // changeValue(me.getY()); return true; } else if(me.getAction() == MotionEvent.ACTION_UP) { return true; } return false; } //********************************************************************************************// // // // User Defined Sub-routines // // // //********************************************************************************************// public void startGraph() { drawPathR.reset(); drawPathG.reset(); drawPathB.reset(); pX = 0; pY = this.getHeight() / 2; drawPathR.moveTo(pX, pY); drawPathG.moveTo(pX, pY); drawPathB.moveTo(pX, pY); } public void changeValue(float newYR, float newYG, float newYB) { mX++; mYR = newYR; mYG = newYG; mYB = newYB; drawPathR.lineTo(mX, mYR); drawPathG.lineTo(mX, mYG); drawPathB.lineTo(mX, mYB); this.invalidate(); if(mX >= this.getWidth()) { mX = 0; drawPathR.reset(); drawPathG.reset(); drawPathB.reset(); drawPathR.moveTo(pX, pY); drawPathG.moveTo(pX, pY); drawPathB.moveTo(pX, pY); } } public void resetGraph() { mX = 0; drawPathR.reset(); drawPathG.reset(); drawPathB.reset(); this.invalidate(); } }
package br.mp.mpac.atendimento.api; import br.mpac.entidade.*; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.*; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; @Path("/") @Consumes("application/json") @Produces("application/json") public class Resources { @PersistenceContext private EntityManager em; @GET @Path("/raca") public List<Raca> getRaca(){ return em.createNamedQuery("Raca.findAll",Raca.class).getResultList(); } @GET @Path("/assunto") public List<Assunto> getAssunto(){ return em.createNamedQuery("Assunto.findAll",Assunto.class).getResultList(); } @GET @Path("/escolaridade") public List<Escolaridade> getEscolaridade(){ return em.createNamedQuery("Escolaridade.findAll",Escolaridade.class).getResultList(); } @GET @Path("/estado-civil") public List<EstadoCivil> getEstadoCivil(){ return em.createNamedQuery("EstadoCivil.findAll",EstadoCivil.class).getResultList(); } @GET @Path("/tipo-atendimento") public List<TipoAtendimento> getTipoAtendimento(){ return em.createNamedQuery("TipoAtendimento.findAll",TipoAtendimento.class).getResultList(); } @GET @Path("/sexo") public List<Sexo> getSexo(){ return em.createNamedQuery("Sexo.findAll",Sexo.class).getResultList(); } @GET @Path("/deficiencia") public List<Deficiencia> getDeficiencia(){ return em.createNamedQuery("Deficiencia.findAll",Deficiencia.class).getResultList(); } @GET @Path("/renda") public List<Renda> getRenda(){ return em.createNamedQuery("Renda.findAll",Renda.class).getResultList(); } @GET @Path("/orientacao-sexual") public List<OrientacaoSexual> getOrientacaoSexual(){ return em.createNamedQuery("OrientacaoSexual.findAll",OrientacaoSexual.class).getResultList(); } @GET @Path("/local-atendimento") public List<LocalAtendimento> getLocalAtendimento(){ return em.createNamedQuery("LocalAtendimento.findAll",LocalAtendimento.class).getResultList(); } @GET @Path("/util/dropdown-options") public Map<String,List<?>> getDropdownOptions(){ return new HashMap<String,List<?>>(){{ put("raca",getRaca()); put("assunto", getAssunto()); put("estadoCivil", getEstadoCivil()); put("tipoAtendimento",getTipoAtendimento()); put("estadoCivil",getEstadoCivil()); put("sexo",getSexo()); put("deficiencia",getDeficiencia()); put("renda",getRenda()); put("escolaridade",getEscolaridade()); put("orientacaoSexual",getOrientacaoSexual()); put("localAtendimento",getLocalAtendimento()); }}; } /*@Path("/util/foto") //@Produces("image/png") protected Foto getFoto(@QueryParam("id") int id) throws Exception { return em.find(Pessoa.class, id).getFoto(); }*/ }
import java.io.*; import java.util.ArrayList; import shapes.*; /* your tasks: * create a class called ShapeException * createShape should throw a ShapeException * in main(), you should catch the ShapeException * */ public class ReadShapeFile { public static GeometricObject createShape(String shapeName) throws ShapeException{ /* if shapeName is "Circle" return Circle(); * if shapeName is "Square" return Square(); * if shapeName is "Rectangle" return Rectangle(); * if it is not any one of these, it should throw * a ShapeException */ if (shapeName.equals("Circle")) { return new Circle(); } else if (shapeName.equals("Square")) { return new Square(); } else if (shapeName.equals("Rectangle")) { return new Rectangle(); }else { throw new ShapeException(shapeName); } } public static void main(String[] args) { ArrayList<GeometricObject> shapeList = new ArrayList<GeometricObject>(); File f = new File("shapes.txt"); String inString = null; /* create a loop to read the file line-by-line */ FileReader fr = null; try { fr = new FileReader(f); BufferedReader in = new BufferedReader(fr); String linea = null; linea = in.readLine(); while (linea != null) { inString = linea; try { GeometricObject shape = createShape(inString); shapeList.add(shape); } catch (ShapeException e ) { System.err.println("Cannot create shape: " + inString); System.err.println("Caught ShapeException: " + e.getMessage()); } finally { linea = in.readLine(); } } } catch (FileNotFoundException fne) { System.out.println("File not found: "+ fne.getMessage()); } catch (IOException e) { System.out.println("IO error reading file: " + e.getMessage()); } finally { if (fr != null) { try { fr.close(); } catch (IOException e) { System.out.println("error closing file : "+ e.getMessage()); } } } System.out.println(shapeList); } }
//Created by MyEclipse Struts // XSL source (default): platform:/plugin/com.genuitec.eclipse.cross.easystruts.eclipse_3.8.2/xslt/JavaClass.xsl package com.aof.webapp.form.helpdesk; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; /** * MyEclipse Struts * Creation date: 11-17-2004 * * XDoclet definition: * @struts:form name="PartysubForm" */ public class PartysubForm extends ActionForm { // --------------------------------------------------------- Instance Variables /** desc property */ private String desc; private String name; private String type; private String choice; // --------------------------------------------------------- Methods /** * Method validate * @param mapping * @param request * @return ActionErrors */ public ActionErrors validate( ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = new ActionErrors(); // if (((desc == null) || (desc.length() < 1))&& ((relation == null) || (relation.length() < 1))&& ((address == null) || (address.length() < 1))) // errors.add("emptyvalue", new ActionError("desc,relation and address.required")); if (1==2){ errors.add("emptyvalue", new ActionError("")); } return errors; } /** * Method reset * @param mapping * @param request */ public void reset(ActionMapping mapping, HttpServletRequest request) { desc=""; name=""; choice=""; } /** * Returns the desc. * @return String */ public String getDesc() { return desc; } /** * Set the desc. * @param desc The desc to set */ public void setDesc(String desc) { this.desc = desc; } /** * @return Returns the type. */ public String getType() { return type; } /** * @param type The type to set. */ public void setType(String type) { this.type = type; } /** * @return Returns the choice. */ public String getChoice() { return choice; } /** * @param choice The choice to set. */ public void setChoice(String choice) { this.choice = choice; } /** * @return Returns the name. */ public String getName() { return name; } /** * @param name The name to set. */ public void setName(String name) { this.name = name; } }
package bouns; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class JDBCByProperties { public static void main(String[] args) { // 只需要将不同的驱动放在配置文件中,就可以实现连接不同的数据库 try { // 1.注册驱动 Class.forName(PropertiesUtil.getDriverProperties("MySQL")); // 2. 连接数据库 Connection conn = DriverManager.getConnection( PropertiesUtil.getUrlProperties("MySQL"), PropertiesUtil.getUsernameProperties("MySQL"), PropertiesUtil.getPasswordProperties("MySQL")); System.out.println("傻瓜"); System.out.println(PropertiesUtil.getUrlProperties("MySQL")); System.out.println("笨蛋"); // 3. 创建执行的sql语句, 建议使用PreparedStatement String sql = "select * from sale_todo where uniqueCode = ?"; PreparedStatement prep = null; prep = (PreparedStatement) conn.prepareStatement(sql); prep.setInt(1, 1); // 4. 查询sql 语句, 返回一个结果集 ResultSet result = prep.executeQuery(); // 5. 处理结果集, 释放资源 while (result.next()) { System.out.println(result.getInt("id")); System.out.println(result.getString("name")); System.out.println(result.getInt("age")); System.out.println(result.getString("salary")); } conn.close(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block System.out.println("驱动注册未成功"); e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
@javax.xml.bind.annotation.XmlSchema(namespace = "http://xml.apache.org/xml-soap") package org.apache.xml.xml_soap;
package it.polito.tdp.extflightdelays.model; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.jgrapht.Graphs; import org.jgrapht.event.ConnectedComponentTraversalEvent; import org.jgrapht.event.EdgeTraversalEvent; import org.jgrapht.event.TraversalListener; import org.jgrapht.event.VertexTraversalEvent; import org.jgrapht.graph.DefaultWeightedEdge; import org.jgrapht.graph.SimpleWeightedGraph; import org.jgrapht.traverse.BreadthFirstIterator; import it.polito.tdp.extflightdelays.db.ExtFlightDelaysDAO; public class Model { private SimpleWeightedGraph<Airport, DefaultWeightedEdge> grafo; private ExtFlightDelaysDAO dao; private Map<Airport,Airport> visita; private Map<Integer, Airport> idMap; public Model() { dao = new ExtFlightDelaysDAO(); idMap = new HashMap<Integer, Airport>(); dao.loadAllAirports(idMap); } public void creaGrafo(int x) { grafo = new SimpleWeightedGraph<>(DefaultWeightedEdge.class); //filtrare aereoporti e aggiungo vertici Graphs.addAllVertices(grafo, dao.getVertici(x, idMap)); //aggiungo archi for(Rotta r : dao.getRotte(idMap)) { if(this.grafo.containsVertex(r.getA1()) && this.grafo.containsVertex(r.getA2())) { // non è importante ordine per grafo non orientato DefaultWeightedEdge e = this.grafo.getEdge(r.getA1(), r.getA2()); if (e == null) { Graphs.addEdgeWithVertices(grafo, r.getA1(), r.getA2(), r.getN()); } else { double pesoVecchio = this.grafo.getEdgeWeight(e); double pesoNuovo = pesoVecchio + r.getN(); this.grafo.setEdgeWeight(e, pesoNuovo); } } } System.out.println("Grafo creato"); System.out.println("Vertici: "+ grafo.vertexSet().size()); System.out.println("Archi: "+ grafo.edgeSet().size()); } public Set<Airport> getVertici() { return this.grafo.vertexSet(); } public List<Airport> trovaPercorso(Airport a1,Airport a2){ List<Airport> percorso = new LinkedList<>(); BreadthFirstIterator<Airport, DefaultWeightedEdge> it = new BreadthFirstIterator<>(grafo,a1); visita = new HashMap<>(); visita.put(a1, null); it.addTraversalListener(new TraversalListener<Airport, DefaultWeightedEdge>(){ @Override public void connectedComponentFinished(ConnectedComponentTraversalEvent e) { } @Override public void connectedComponentStarted(ConnectedComponentTraversalEvent e) { } @Override public void edgeTraversed(EdgeTraversalEvent<DefaultWeightedEdge> e) { Airport ar1 = grafo.getEdgeSource(e.getEdge()); Airport ar2 = grafo.getEdgeTarget(e.getEdge()); if(visita.containsKey(ar1) && !visita.containsKey(ar2)) { visita.put(ar1, ar2); }else if(visita.containsKey(ar2) && !visita.containsKey(ar1)){ visita.put(ar1, ar2); } } @Override public void vertexTraversed(VertexTraversalEvent<Airport> e) { } @Override public void vertexFinished(VertexTraversalEvent<Airport> e) { } }); while(it.hasNext()) { it.next(); } percorso.add(a2); Airport step = a2; while (visita.get(step) != null) { step = visita.get(step); percorso.add(step); } return percorso; } }
package gg.bayes.challenge.service.impl; import gg.bayes.challenge.persistance.model.SpellPO; import gg.bayes.challenge.persistance.repositories.SpellRepository; import lombok.AllArgsConstructor; import lombok.Data; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @Service public class SpellServiceImpl { private Map<SpellId, SpellPO> spellCache = new ConcurrentHashMap<>(); private SpellRepository spellRepository; @Autowired public SpellServiceImpl(SpellRepository spellRepository) { this.spellRepository = spellRepository; } public SpellPO getSpellByNameAndLevel(String name, int level) { return spellCache.computeIfAbsent(new SpellId(name, level), s -> spellRepository.findByNameAndLevel(s.name, s.level) .orElseGet(() -> spellRepository.save(SpellPO .builder() .name(s.name) .level(s.level) .build()))); } @Data @AllArgsConstructor class SpellId{ private String name; private int level; } }
package org.valdi.entities.management.channel; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.logging.Level; import org.bukkit.craftbukkit.v1_12_R1.entity.CraftPlayer; import org.bukkit.entity.Player; import org.valdi.entities.iDisguise; import org.valdi.entities.management.PacketHandler; import org.valdi.entities.management.VersionHelper; import net.minecraft.server.v1_12_R1.MinecraftServer; import net.minecraft.server.v1_12_R1.Packet; import net.minecraft.server.v1_12_R1.PacketPlayInTeleportAccept; import net.minecraft.server.v1_12_R1.PacketPlayInUseEntity; import net.minecraft.server.v1_12_R1.PlayerConnection; @Deprecated public class InjectedPlayerConnection1121 extends PlayerConnection implements InjectedPlayerConnection { @Deprecated private final Player observer; @Deprecated public InjectedPlayerConnection1121(Player observer, Object originalConnection) throws Exception { super(MinecraftServer.getServer(), ((PlayerConnection)originalConnection).networkManager, ((CraftPlayer)observer).getHandle()); this.observer = observer; for(Field field : PlayerConnection.class.getDeclaredFields()) { if(!Modifier.isFinal(field.getModifiers()) && !Modifier.isStatic(field.getModifiers())) { field.setAccessible(true); field.set(this, field.get(originalConnection)); } } } @Deprecated public void resetToDefaultConnection() throws Exception { PlayerConnection defaultConnection = new PlayerConnection(MinecraftServer.getServer(), networkManager, player); for(Field field : PlayerConnection.class.getDeclaredFields()) { if(!Modifier.isFinal(field.getModifiers()) && !Modifier.isStatic(field.getModifiers())) { field.setAccessible(true); field.set(defaultConnection, field.get(this)); } } } @Deprecated public void sendPacket(Object packet) { if(packet instanceof Packet) sendPacket((Packet)packet); } @Deprecated public void sendPacketDirectly(Object packet) { if(packet instanceof Packet) super.sendPacket((Packet)packet); } @Deprecated public void a(PacketPlayInTeleportAccept packet) { try { super.a(packet); } catch(NullPointerException e) { } } @Deprecated public void a(PacketPlayInUseEntity packet) { try { packet = (PacketPlayInUseEntity)PacketHandler.handlePacketPlayInUseEntity(observer, packet); if(packet != null) { super.a(packet); } } catch(Exception e) { if(VersionHelper.debug()) { iDisguise.getInstance().getLogger().log(Level.SEVERE, "Cannot handle packet in: " + packet.getClass().getSimpleName() + " from " + observer.getName(), e); } } } @Deprecated public void sendPacket(Packet packet) { Object[] packets = PacketHandler.handlePacketOut(observer, packet); for(Object p : packets) { super.sendPacket((Packet)p); } } }
public class Woman extends Person{ @Override public void setHair(String hair) { super.setHair(hair); } @Override public void setTeeth(int teeth) { super.setTeeth(teeth); } }
package com.xwj.entity; /** * @Description TODO * @Author yuki * @Date 2018/8/6 10:01 * @Version 1.0 **/ public class ColorSet { private Color color; public Color getColor() { return color; } public void setColor(Color color) { this.color = color; } @Override public String toString() { return "ColorSet{" + "color=" + color + '}'; } }
package ch11; import java.util.*; public class TreeSetLotto { public static void main(String[] args) { Set set = new TreeSet(); // 범위 검색, 정렬, 정렬할 필요 없음 // Set set = new HashSet<>(); // 정렬 필요 for(int i=0; set.size()<6; i++) { int num = (int)(Math.random()*45)+1; set.add(num); //set.add(new Integer(num)); } System.out.println(set); } } //class Test implements Comparable{ // // @Override // public int compareTo(Object o) { // return -1; // } //비교 기준이 없음. //} // //class TestComp implements Comparator{ // // @Override // public int compare(Object arg0, Object arg1) { // return 1; // } // //}
package ru.sdevteam.videostreamer; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; public class ConnectionActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_connection); Button button = (Button) findViewById(R.id.connectButton); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { connect(); } }); } @Override protected void onResume() { super.onResume(); ProgressBar bar = (ProgressBar) findViewById(R.id.connectionProgressBar); bar.setVisibility(View.INVISIBLE); } private void connect() { EditText addressBox = (EditText) findViewById(R.id.addressTextBox); EditText portBox = (EditText) findViewById(R.id.portTextBox); TextView error = (TextView) findViewById(R.id.errorLabel); ProgressBar bar = (ProgressBar) findViewById(R.id.connectionProgressBar); bar.setVisibility(View.VISIBLE); try { String host = addressBox.getText().toString(); int port = Integer.parseInt(portBox.getText().toString()); NetThread.init(host, port); NetThread.getInstance().startHandshake(); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); e.printStackTrace(); error.setText("Error: " + e.getMessage()); bar.setVisibility(View.INVISIBLE); System.exit(0); } Intent intent = new Intent(this, CameraActivity.class); startActivity(intent); } }
package chapter_one.arrays_and_strings; /** * Date 16/05/20. * @Author Simona Oancea * * 1.4 Write a method to replace all spaces in a string with "%20". * You may assume that the string has sufficient space at the end * of the string to hold the additional characters, and that you are * given the "true" length of the string. */ public class WhitespaceInStringReplacement { public static void main(String[] args) { String s = "Mr John Smith"; String s2 = "Test test "; System.out.println(replace(s)); System.out.println(replace(s2)); } public static String replace(String s) { char[] content = s.toCharArray(); StringBuilder replacement = new StringBuilder(); StringBuilder pattern = new StringBuilder(); pattern.append("%20"); for (int i = 0; i < content.length; i++) { if (content[i] == ' ') { replacement.append(pattern); } else { replacement.append(content[i]); } } return replacement.toString(); } }
/* * 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.ut.healthelink.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; /** * * @author chadmccue */ @Entity @Table(name = "ORGANIZATIONPROGRAMS") public class organizationPrograms { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "ID", nullable = false) private int id; @Column(name = "ORGID", nullable = false) private int orgId = 0; @Column(name = "PROGRAMID", nullable = false) private int programId = 0; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getOrgId() { return orgId; } public void setOrgId(int orgId) { this.orgId = orgId; } public int getProgramId() { return programId; } public void setProgramId(int programId) { this.programId = programId; } }
package com.example.fisso.morpiontest.view; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.widget.ImageView; import com.example.fisso.morpiontest.R; public class Regles extends AppCompatActivity { ImageView pointGauche; ImageView pointMilieu; ImageView pointDroit; ViewPager mViewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.regles); pointGauche = (ImageView) findViewById(R.id.pointGauche); pointMilieu = (ImageView) findViewById(R.id.pointMilieu); pointDroit = (ImageView) findViewById(R.id.pointDroit); mViewPager = (ViewPager) findViewById(R.id.pager); pointGauche.setBackgroundResource(R.drawable.cercle_bleu); pointMilieu.setBackgroundResource(R.drawable.cercle_gris); pointDroit.setBackgroundResource(R.drawable.cercle_gris); PageListener pageListener = new PageListener(); mViewPager.setOnPageChangeListener(pageListener); mViewPager.setAdapter(new SamplePagerAdapter( getSupportFragmentManager())); } private class PageListener extends ViewPager.SimpleOnPageChangeListener { public void onPageSelected(int position) { if (position == 0) { pointGauche.setBackgroundResource(R.drawable.cercle_bleu); pointMilieu.setBackgroundResource(R.drawable.cercle_gris); pointDroit.setBackgroundResource(R.drawable.cercle_gris); } if (position == 1) { pointGauche.setBackgroundResource(R.drawable.cercle_gris); pointMilieu.setBackgroundResource(R.drawable.cercle_bleu); pointDroit.setBackgroundResource(R.drawable.cercle_gris); } if (position == 2) { pointGauche.setBackgroundResource(R.drawable.cercle_gris); pointMilieu.setBackgroundResource(R.drawable.cercle_gris); pointDroit.setBackgroundResource(R.drawable.cercle_bleu); } } } }
package edu.inheritance.newbold.griffin; import edu.jenks.dist.inheritance.*; public class Item implements Buyable{ public boolean bulk; public double weight; public double price; public double totalTax; public double totalScaleWeight; public double pricePerPound; public Item(boolean bulk){ this.bulk = bulk; } public double getWeight(){ return weight; } public boolean isBulk(){ return bulk; } public boolean initBuyable(ItemHandler itemHandler){ return false; } public void setBulk(boolean bulk){ this.bulk = bulk; } public void setWeight(double weight){ this.weight = weight; } public double getTax(double baseTaxRate){ return baseTaxRate*price; } public double getPrice(){ return price; } public void setPrice(double price){ this.price = price; } public double retrievePrice(double scaleWeight){ weight = scaleWeight; return scaleWeight * pricePerPound; } }
package com.game; /** * Interface définissant les constantes de traitement liées aux étapes du jeu. * @author pierrot */ public interface InterfaceLOTR { public final static int SERVEUR_RECEPTION_JOUEURS = 3; public final static int SERVEUR_ENVOI_JOUEURS = 2; public final static int CREATION_JOUEURS = 1; public final static int FERMER_SERVEUR = 0; }
package commands.client.game; import java.util.List; import commands.client.game.sync.SyncGameClientCommand; import core.client.ClientFrame; import core.client.GamePanelOriginal; import core.player.PlayerInfo; import net.client.ClientConnection; public class EnterOriginalGameRoomGameClientCommand implements SyncGameClientCommand { private static final long serialVersionUID = 1094417892948875381L; private final List<PlayerInfo> players; private final PlayerInfo self; public EnterOriginalGameRoomGameClientCommand(List<PlayerInfo> players, PlayerInfo self) { this.players = players; this.self = self; } @Override public void execute(ClientFrame frame, ClientConnection connection) { synchronized (frame) { frame.onNewPanelDisplayed(new GamePanelOriginal(self, players, connection)); } } }
package com.easytoolsoft.commons.lang.pair; /** * @author zhiwei.deng * @date 2017-03-25 **/ public class KeyValuePair { private String key; private String name; public KeyValuePair() { } public KeyValuePair(final String key, final String name) { this.key = key; this.name = name; } public String getKey() { return this.key; } public void setKey(final String key) { this.key = key; } public String getName() { return this.name; } public void setValue(final String name) { this.name = name; } }
package Problem_1269; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Main { static int Aidx, Bidx; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine(); int A = Integer.parseInt(str.split(" ")[0]); int B = Integer.parseInt(str.split(" ")[1]); int[] Aset = new int[A]; int[] Bset = new int[B]; StringTokenizer st = new StringTokenizer(br.readLine()); for(int i = 0; i<A; i++) Aset[i] = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); for(int i = 0; i<B; i++) Bset[i] = Integer.parseInt(st.nextToken()); Arrays.sort(Aset); Arrays.sort(Bset); int cnt = 0; while(Aidx < A && Bidx < B) { if(Aset[Aidx]==Bset[Bidx]) { cnt++; Aidx++; Bidx++; } else if(Aset[Aidx] < Bset[Bidx]) Aidx++; else Bidx++; } System.out.println(A+B-(cnt*2)); } }
package Java; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Created by User on 16-07-2017. */ public class OnlineTest1 { public static String test(String s) { Map<String, Integer> map = new HashMap<>(); Set<String> set = new HashSet<>(); //s = s.replaceAll("[^\\w]", " "); //String[] str = s.split(" "); String[] str = s.split("[\\s,;.:-]+"); for (String val : str) { val = val.replaceAll("[.,$]", ""); if (map.containsKey(val)) { System.out.println(val); return val; } else { map.put(val, 1); } } return null; } public static void main(String ar[]) { OnlineTest1.test("Hi-How;;- are. you;,myfriend"); } }
package com.windtalker.model; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.iid.FirebaseInstanceId; import com.windtalker.dto.DTOMessage; import com.windtalker.tools.ToolsFirebase; import java.io.IOException; import static android.content.ContentValues.TAG; import static android.content.Context.MODE_PRIVATE; /** * Created by jaapo on 25-10-2017. */ public class ModelApplication { private String mEmail; private String mPassword; private String mMessagingToken; private static ModelApplication sSingleton; public static synchronized ModelApplication getInstance(Context context) { if(sSingleton == null) { sSingleton = new ModelApplication(context); } return sSingleton; } private ModelApplication(Context context) { load(context); } private void load(Context context) { SharedPreferences preferences = context.getSharedPreferences("ModelApplication", MODE_PRIVATE); mMessagingToken = preferences.getString("mMessagingToken", ""); mEmail = preferences.getString("mEmail", ""); mPassword = preferences.getString("mPassword", ""); } public void save(Context context) { SharedPreferences filterSettings = context.getSharedPreferences("ModelApplication", MODE_PRIVATE); SharedPreferences.Editor edit = filterSettings.edit(); edit.clear(); edit.putString("mMessagingToken", mMessagingToken); edit.putString("mEmail", mEmail); edit.putString("mPassword", mPassword); edit.commit(); } public void sendPersonalMessage(String userKey, ModelMessage message) { Log.e(TAG, "sendMessage"); ToolsFirebase.getPersonalInbox(userKey).push().setValue(new DTOMessage(FirebaseAuth.getInstance().getCurrentUser().getUid(), message.toPayload())); } public void setToken(Context context, String messagingToken) { Log.e(TAG, "Refreshed token: " + messagingToken); mMessagingToken = messagingToken; save(context); } public void saveLogin(Context context, String email, String password) { mEmail = email; mPassword = password; save(context); } public void logout(Context context) { mMessagingToken = ""; //mEmail = ""; mPassword = ""; new Thread(() -> { try { FirebaseInstanceId.getInstance().deleteInstanceId(); FirebaseAuth.getInstance().signOut(); }catch (IOException e) { e.printStackTrace(); } }).start(); save(context); } public String getMessagingToken() { mMessagingToken = FirebaseInstanceId.getInstance().getToken(); return FirebaseInstanceId.getInstance().getToken();//return mMessagingToken; //TODO? } public String getEmail() { return mEmail; } public String getPassword() { return mPassword; } public boolean isLoggedIn() { return FirebaseAuth.getInstance().getCurrentUser() != null; } public void attemptLogin(String email, String password, FirebaseAuth.AuthStateListener listener) { try { FirebaseAuth.getInstance().addAuthStateListener(listener); FirebaseAuth.getInstance().signInWithEmailAndPassword(email,password); }catch ( Exception e) { throw new RuntimeException(e); } } public void attemptRegisterAndLogin(String email, String password , FirebaseAuth.AuthStateListener listener) { try { FirebaseAuth.getInstance().addAuthStateListener(listener); FirebaseAuth.getInstance().createUserWithEmailAndPassword(email,password); }catch ( Exception e) { throw new RuntimeException(e); } } }
package com.openfeint.game.message; public interface Message { /** * @return sender id */ String getFrom(); /** * @return recipient id. A null value means a broadcast message */ String getTo(); }
package com.myou.appback.modules.base; import java.sql.PreparedStatement; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.BatchPreparedStatementSetter; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; import com.myou.appback.modules.exception.BusinessException; //import com.myou.appback.modules.filter.MobileKeyWordFilter; import com.myou.appback.modules.foundation.oid.util.OIDGenerator; /** * Description: 业务最终父接口实现类,提供所有系统级通用的公共方法<br> * @version 1.0 */ public abstract class BusinessBO implements Business{ /** 短信最大数量 69个字是没有问题的。 */ public static final int MAXMSGCOUNT = 69; /** 日志对象 */ private final Logger logger = LoggerFactory.getLogger(getClass()); protected static SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); protected static final SimpleDateFormat SDFYou = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss-SSS"); /** * 获取JDBC模板,子类分别实现 * @return */ public abstract JdbcTemplate getJdbcTemplates(); /** * getOID 取值对象的pk * @return String */ public String getOID() { return OIDGenerator.getOID(getJdbcTemplates()); } /** * 记录业务日志 * * @param operate * @param billpk * @param billtype * @param pk_user * @param pk_org */ public void log(String businessName, String billPk, String billType, String pkUser, String pkOrg, String ip){ /* logger.info(businessName + "-" + billPk + "-" + billType + "-" + pkUser + "-" + pkOrg); StringBuffer sql = new StringBuffer(); // DELAYED 业务日志如果要求不严谨并苛求性能,可加上DELAYED关键字 sql.append(" INSERT INTO SM_BUSINESS_LOG "); sql.append(" ( "); sql.append(" BUSINESS_NAME, SOURCE_BILL, SOURCE_BILLTYPE, "); sql.append(" PK_OPERATOR, PK_ORG, TS, "); sql.append(" IP "); sql.append(" ) "); sql.append(" VALUES "); sql.append(" ( "); sql.append(" ?, ?, ?, "); sql.append(" ?, ?, ?, "); sql.append(" ? ) "); Object [] args = new Object[]{businessName, billPk, billType, pkUser, pkOrg, this.getDateTime(), ip}; getJdbcTemplates().update(sql.toString(), args);*/ } /** * 纯JDBC分页,与hibernate无关,传回map */ protected List<Map<String, Object>> findByJdbcTemplatePagination(JdbcTemplate template, String sql, final Object[] args, int first, int max) { StringBuffer sb = new StringBuffer(sql); sb.append(" limit "); sb.append(first); sb.append(" , "); sb.append(max); sql = sb.toString(); // logger.info("查询sql: " + sql + "------参数" + args); return template.queryForList(sql, args); } /** * 发送邮件 * @param toMail 邮箱地址 * @param data 填充变量 * @param type 类型,为常量表里的data,确定到邮件发送类型 */ @Transactional public void sendMail(String sendMail, String toMail, String title, Map<String, String> argsMap, String emailVm) { sendMail(sendMail, toMail, "00000000000000000001", title, argsMap, emailVm); } /** * 发送邮件 * * @param sendMail * 发送邮箱地址 * @param toMail * 目标邮箱地址 * @param pkOrg * 花店主键 * @param title * 标题 * @param argsMap * 填充变量 * @param emailVm * 模板名称 */ @Transactional public void sendMail(String sendMail, String toMail, String pkOrg, String title, Map<String, String> argsMap, String emailVm) { String match = "^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$"; StringBuffer sb = new StringBuffer(); for (Entry<String, String> entry : argsMap.entrySet()) { sb.append(entry.getKey()).append("==").append(entry.getValue()).append(";;"); } if (sb.length() > 2) { sb.delete(sb.length() - 2, sb.length()); } StringBuffer sql = new StringBuffer(); sql.append(" INSERT INTO SM_WAITING_MAIL "); sql.append(" ( "); sql.append(" TO_EMAIL, ARGS, TITLE, PK_ORG, "); sql.append(" EMAIL_VM, BILLSTATUS, TS, SEND_EMAIL "); sql.append(" ) VALUES ( "); sql.append(" ?, ?, ?, ?,"); sql.append(" ?, ?, NOW(), ? "); sql.append(" ) "); Object[] arg = new Object[] { toMail, sb.toString(), title.toString(), pkOrg, emailVm, 1, sendMail }; getJdbcTemplates().update(sql.toString(), arg); } /** * 发送给 3个 系统管理员 * @param msg * @param isQun */ /* public void sendSms(String msg){ String mobileNo = "18757113775;13735885160"; msg += "【系统】"; sendSms(mobileNo, msg, true, "00000000000000000001", true); } /** * 内部使用。 * @param mobileNo * @param msg */ /* public void sendSms(String mobileNo, String msg){ msg += "【系统】"; sendSms(mobileNo, msg, false, "00000000000000000001", true); } /** * 发送短信(无需扣除余额) * @param mobileNo * @param msg * @param isQun 是否群发 * @param pkOrg * @param isAutoSend 余额不足是否发送im消息 * return 内容和手机是否正确 */ /* public boolean sendSms(String mobileNo, final String msg, Boolean isQun, final String pkOrg , final boolean isAutoSend){ String error = ""; if(mobileNo != null){ mobileNo = mobileNo.trim(); } logger.info(mobileNo); if (StringUtils.isEmpty(mobileNo) || !mobileNo.matches("^[0-9;]+$")) { error += "号码不正确,请注意格式,多个号码以\";\"号分隔!\n"; } if(msg.length() > MAXMSGCOUNT){ error += "内容不能超过" + MAXMSGCOUNT + "个字!\n"; } List<String> list = MobileKeyWordFilter.getInstance().doFilter(msg); if(list.size() != 0){ StringBuffer sb = new StringBuffer(); sb.append("发送短信失败,您包含以下关键字:"); for (String s : list) { sb.append(s + ","); } error += sb.toString() + "\n"; } if(!error.equals("")){ if(isAutoSend){ logger.info("短息内容错误,无法发送:" + error); return false; }else{ throw new BusinessException(error); } } StringBuffer sql = new StringBuffer(); sql.append(" INSERT INTO SMS_WAITSEND( "); sql.append(" MOBILENO, MSGTEXT, billstatus, "); sql.append(" CHARTYPE, COMLIMIT, pk_org, is_unions "); sql.append(" ) VALUES( "); sql.append(" ?, ?, 1, "); sql.append(" 'U', 0 , ? , ?"); sql.append(" ) "); // Object [] args = new Object[]{mobileNo, msg, pkOrg, 0}; // getJdbcTemplates().update(sql.toString(), args); // 把群发改成单发 final String[] mobilenos = mobileNo.split(";"); BatchPreparedStatementSetter psss = new BatchPreparedStatementSetter(){ public int getBatchSize() { return mobilenos.length; } public void setValues(PreparedStatement ps, int arg1) throws SQLException { ps.setString(1, mobilenos[arg1]); ps.setString(2, msg); ps.setString(3, pkOrg); ps.setString(4, "0"); logger.info("发送短信:" + mobilenos[arg1] + ",字数:" + msg.length() + "," + msg); } }; getJdbcTemplates().batchUpdate(sql.toString(), psss); return true; } /** * 发送短信 * @param mobileNo * @param msg */ @Transactional /* public String sendSms(String mobileNo, Short type, Object [] args, String pkOrg) { String error = ""; if (StringUtils.isEmpty(mobileNo) || !mobileNo.matches("^[0-9;]+$")) { throw new BusinessException("号码不正确,请注意格式,多个号码以\";\"号分隔!"); } // TODO:后面要使用缓存,目前使用sql,因为模板会经常变动 String ssql = " SELECT CONTENT FROM TB_PLATFORM_MOBILE_SALUTATION WHERE MOBILE_USE = ? "; String content = getJdbcTemplates().queryForObject(ssql,new Object[]{type}, String.class).toString(); content = String.format(content, args); if (content.length() > (MAXMSGCOUNT - 5)){ content = content.substring(0,(MAXMSGCOUNT - 5)); } logger.info("测试:type:" + type + "\t" + type.compareTo((short)8)); if (type.compareTo((short)8) == 0){ content += "【花族网】"; } else { content += "【爱花族】"; } List<String> list = MobileKeyWordFilter.getInstance().doFilter(content); if(list.size() != 0){ StringBuffer sb = new StringBuffer(); sb.append("发送短信失败,您包含以下关键字:"); for (String s : list) { sb.append(s + ","); } error += sb.toString(); } if(error.equals("")){ StringBuffer sql = new StringBuffer(); sql.append(" INSERT INTO SMS_WAITSEND( "); sql.append(" MOBILENO, MSGTEXT, "); sql.append(" CHARTYPE, COMLIMIT, "); sql.append(" BILLSTATUS, PK_ORG "); sql.append(" ) VALUES( "); sql.append(" ?, ?, "); sql.append(" 'U', 0, "); sql.append(" 1, ? "); sql.append(" ) "); args = new Object[]{mobileNo, content, pkOrg}; getJdbcTemplates().update(sql.toString(), args); }else{ throw new BusinessException( error +"请您联系客服95105386处理"); } return error; } /** * 获取17位订单号 * @return */ public String getOrderNo(){ return new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new java.util.Date()); } /** * getDateTime * 取系统时间(当前服务器时间) * * @return String */ public static String getCurDateTime() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date()); } /** * getDate * 取系统日期(当前服务器时间) * * @return String */ public static String getCurDate() { return new SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date()); } /** * getTs * 生成时间戳 * * @return String */ public static String getCurTs() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date()); } /** * getDateTime * 取系统时间(当前服务器时间) * * @return String */ public String getDateTime() { return getCurDateTime(); } /** * getDate * 取系统日期(当前服务器时间) * * @return String */ public String getDate() { return getCurDate(); } /** * getTs * 生成时间戳 * * @return String */ public String getTs() { return getCurTs(); } /** * getTimestamp * 生成时间戳 * * @return String "yyyy-MM-dd HH:mm:ss.SSS" */ public String getTimestamp() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new java.util.Date()); } /** * 校验时间戳 * @param sourceBill * @param ts * @param tableName * @param filed * @return */ protected Date checkTs(String sourceBill, Date ts, String tableName, String filed) { String sql = " SELECT TS, NOW() NOW_DATE FROM " + tableName + " WHERE " + filed + " = ? "; Map<String, Object> map = getJdbcTemplates().queryForMap(sql, new Object[]{sourceBill}); String dateStr = (String) map.get("TS"); Date date = null; try { date = SDF.parse(dateStr); } catch (ParseException e) { e.printStackTrace(); } Assert.notNull(date, "元数据错误,没有TS信息!"); if (date.after(ts)){ logger.info("数据已经被修改,请刷新后重新操作!传入时间:" + SDF.format(ts) + " 查询当前时间:" + SDF.format(date)); throw new BusinessException("数据已经被修改,请刷新后重新操作!"); } Date now = (Date) map.get("NOW_DATE"); return now; } }
package com.birivarmi.birivarmiapp.model; import javax.persistence.Column; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name="BV_CURRENCY") @DiscriminatorValue("BV_CURRENCY") public class Currency extends BirivarmiItem{ @Column(name="CODE", length=3, nullable=false) private String code; @Column(name="NAME", length=40, nullable=false) private String name; @Column(name="DESCRIPTION", length=80, nullable=true) private String description; @Column(name="ENABLED", nullable=false) private Character enabled; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Character getEnabled() { return enabled; } public void setEnabled(Character enabled) { this.enabled = enabled; } }
package kr.ac.kopo.day02.homework; import java.util.Scanner; public class HomeworkMain04 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("첫번째 정수 입력: "); int first = sc.nextInt(); System.out.print("두번째 정수 입력: "); int second = sc.nextInt(); sc.close(); if(second != 0 && first % second == 0){ System.out.println(first + "가 " + second + "의 배수인지 판단 결과 : " + true); } else { System.out.println(first + "가 " + second + "의 배수인지 판단 결과 : " + false); } System.out.println(first + "가 " + second + "의 배수인지 판단 결과 : " + (second > 0 && first % second == 0)); } }
package Agents; import Classes.InformStationState; import jade.core.AID; import jade.core.Agent; import jade.core.behaviours.CyclicBehaviour; import jade.core.behaviours.OneShotBehaviour; import jade.core.behaviours.TickerBehaviour; import jade.domain.DFService; import jade.domain.FIPAAgentManagement.DFAgentDescription; import jade.domain.FIPAAgentManagement.ServiceDescription; import jade.domain.FIPAException; import jade.lang.acl.ACLMessage; import jade.lang.acl.MessageTemplate; import jade.lang.acl.UnreadableException; import org.knowm.xchart.*; import org.knowm.xchart.demo.charts.ExampleChart; import org.knowm.xchart.demo.charts.pie.PieChart02; import org.knowm.xchart.style.Styler; import java.util.*; import javax.swing.*; import java.awt.*; import java.time.LocalTime; import java.util.Timer; import java.util.TimerTask; public class Interface extends Agent implements ExampleChart { private PieChart piechart; private CategoryChart bar_chart; private CategoryChart bar_chart_percentages; private int[] numberofUsers=new int[] {9,9,9,9,9}; private Number[] percentageTotal=new Number[] {66,66,66,66,66}; private String[] array = {"Repouso", "Andamento","Total"}; private String[] array_stations = {"S1","S2","S3","S4","S5"}; private Number[] barchart=new Number[] {40,0,40}; private AID[] Agents; private Map<AID, InformStationState> stations; private int nUsers; private int UsersTotal; StringBuilder sb; String paneltext; JTextPane textPane; @Override protected void setup() { super.setup(); this.addBehaviour(new searchStation()); stations = new HashMap<AID, InformStationState>(); this.addBehaviour(new StationRequest()); textPane = new JTextPane(); sb = new StringBuilder(); XChartPanel<PieChart> exampleChart = new XChartPanel<PieChart>(getPieChart()); XChartPanel<CategoryChart> barchart = new XChartPanel<CategoryChart>(getBarChart()); XChartPanel<CategoryChart> barchartpercentages = new XChartPanel<CategoryChart>(getBarChart02()); javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { JFrame frame = new JFrame("XChart"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(exampleChart, BorderLayout.WEST); frame.getContentPane().add(barchart, BorderLayout.EAST); frame.getContentPane().add(barchartpercentages, BorderLayout.SOUTH); frame.getContentPane().add(textPane, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); } }); this.addBehaviour(new TickerBehaviour(this, 500) { protected void onTick() { showInterface(); } }); TimerTask chartUpdaterTask = new TimerTask() { public void run() { updateData(); textPane.setText(paneltext); exampleChart.revalidate(); barchart.revalidate(); barchartpercentages.revalidate(); exampleChart.repaint(); barchart.repaint(); barchartpercentages.repaint(); } }; java.util.Timer timer = new Timer(); timer.scheduleAtFixedRate(chartUpdaterTask, 0, 500); } public PieChart getPieChart() { // Create Chart piechart = new PieChartBuilder().width(800).height(600).title(getClass().getSimpleName()).build(); // Customize Chart Color[] sliceColors = new Color[] { new Color(187, 47, 169), new Color(56, 118, 29), new Color(66, 79, 220), new Color(194, 182, 68), new Color(213, 6, 6) }; piechart.getStyler().setSeriesColors(sliceColors); // Series piechart.addSeries("Station1", numberofUsers[0]); piechart.addSeries("Station2", numberofUsers[1]); piechart.addSeries("Station3", numberofUsers[2]); piechart.addSeries("Station4", numberofUsers[3]); piechart.addSeries("Station5", numberofUsers[4]); return piechart; } public CategoryChart getBarChart() { // Create Chart bar_chart = new CategoryChartBuilder().width(800).height(600).title("Andamento vs. Repouso").xAxisTitle("Users").yAxisTitle("Total").theme(Styler.ChartTheme.XChart).build(); // Series bar_chart.addSeries("Utilizadores", new ArrayList<String>(Arrays.asList(array)), new ArrayList<Number>(Arrays.asList(barchart))); return bar_chart; } public CategoryChart getBarChart02() { // Create Chart bar_chart_percentages = new CategoryChartBuilder().width(800).height(600).title("percentagens").xAxisTitle("Estaçoes").yAxisTitle("Percentagem").theme(Styler.ChartTheme.XChart).build(); // Series bar_chart_percentages.addSeries("Estaçoes", new ArrayList<String>(Arrays.asList(array_stations)), new ArrayList<Number>(Arrays.asList(percentageTotal))); return bar_chart_percentages; } public void updateData() { piechart.updatePieSeries("Station1", numberofUsers[0]); piechart.updatePieSeries("Station2", numberofUsers[1]); piechart.updatePieSeries("Station3", numberofUsers[2]); piechart.updatePieSeries("Station4", numberofUsers[3]); piechart.updatePieSeries("Station5", numberofUsers[4]); bar_chart.updateCategorySeries("Utilizadores", new ArrayList<String>(Arrays.asList(array)), new ArrayList<Number>(Arrays.asList(barchart)), null); bar_chart_percentages.updateCategorySeries("Estaçoes", new ArrayList<String>(Arrays.asList(array_stations)), new ArrayList<Number>(Arrays.asList(percentageTotal)), null); } @Override public PieChart getChart() { return null; } @Override public String getExampleChartName() { return null; } protected void showInterface(){ addBehaviour(new searchUsers()); double count = 0; sb.setLength(0); UsersTotal = 0; for(Map.Entry<AID, InformStationState> c : stations.entrySet()) { if(c.getValue().getName().equals("Station1")){ numberofUsers[0] = c.getValue().getnBikes(); count = (double) numberofUsers[0]/12*100; percentageTotal[0] = (Number) count; } if(c.getValue().getName().equals("Station2")){ numberofUsers[1] = c.getValue().getnBikes(); count = (double) numberofUsers[1]/12*100; percentageTotal[1] = (Number) count; } if(c.getValue().getName().equals("Station3")){ numberofUsers[2] = c.getValue().getnBikes(); count = (double) numberofUsers[2]/12*100; percentageTotal[2] = (Number) count; } if(c.getValue().getName().equals("Station4")){ numberofUsers[3] = c.getValue().getnBikes(); count = (double) numberofUsers[3]/12*100; percentageTotal[3] = (Number) count; } if(c.getValue().getName().equals("Station5")){ numberofUsers[4] = c.getValue().getnBikes(); count = (double) numberofUsers[4]/12*100; percentageTotal[4] = (Number) count; } paneltext = sb.append(c.getValue().getName() +" | Cap: "+ c.getValue().getnBikes() + "/"+c.getValue().getCap() + " | Coords: " + c.getValue().getCoords() + " | Desc A: "+c.getValue().getAcceptedDisc()+ " | Desc R: " + c.getValue().getDeniedDisc() + " | Total Users: " + c.getValue().getTotalUsers() + "\n\n").toString(); UsersTotal += c.getValue().getTotalUsers(); } paneltext = sb.append("Numero de Bicicletas em circulação: "+ nUsers + "\n\n" + "Numero de Total de Users: "+ UsersTotal + "\n").toString(); barchart[1] = nUsers; barchart[0] = 40-nUsers; } /* Procura utilizadores e conta-os */ private class searchUsers extends OneShotBehaviour { @Override public void action() { DFAgentDescription template = new DFAgentDescription(); ServiceDescription sd = new ServiceDescription(); sd.setType("User"); template.addServices(sd); try { DFAgentDescription[] result = DFService.search(myAgent, template); nUsers = result.length; } catch (FIPAException fe) { fe.printStackTrace(); } } } /* Procura e guarda todas as stations registadas */ private class searchStation extends OneShotBehaviour { @Override public void action() { DFAgentDescription template = new DFAgentDescription(); ServiceDescription sd = new ServiceDescription(); sd.setType("Station"); template.addServices(sd); try { DFAgentDescription[] result = DFService.search(myAgent, template); Agents = new AID[result.length]; for (int i = 0; i < result.length; i++) { Agents[i] = result[i].getName(); } } catch (FIPAException fe) { fe.printStackTrace(); } if (Agents.length != 0) { for (int i = 0; i < Agents.length; i++) { stations.put(Agents[i], new InformStationState()); } } } } /* serve para receber todas as mensagens do agente Station, contendo todos os dados importantes.*/ private class StationRequest extends CyclicBehaviour { AID estacao; InformStationState est; @Override public void action() { MessageTemplate mt = MessageTemplate.MatchPerformative(ACLMessage.INFORM); ACLMessage msg = myAgent.receive(mt); if (msg != null) { try { InformStationState content = (InformStationState) msg.getContentObject(); estacao = msg.getSender(); if (!stations.containsKey(estacao)){ stations.put(estacao, content); } else { stations.get(estacao).setName(content.getName()); stations.get(estacao).setCoords(content.getCoords()); stations.get(estacao).setnBikes(content.getnBikes()); stations.get(estacao).setCap(content.getCap()); stations.get(estacao).setTotalUsers(content.getTotalUsers()); stations.get(estacao).setAcceptedDisc(content.getAcceptedDisc()); stations.get(estacao).setDeniedDisc(content.getDeniedDisc()); } }catch (UnreadableException e){ } } else { block(); } } } @Override protected void takeDown() { super.takeDown(); } }
import java.util.*; public class Anagrams { public static List<Integer> allAnagrams(String s, String l) { // Write your solution here. List<Integer> result = new ArrayList<>(); if (s == null || s.length() == 0 || l == null || l.length() == 0) return result; HashMap<Character, Integer> eleMap = mapify(s); int winL = -1; int winR = -1; int eleMatch = 0; while (winR < l.length() - 1) { winR++; char rEnd = l.charAt(winR); Integer count = eleMap.get(rEnd); if (count != null) { eleMap.put(rEnd, count - 1); if (count == 1) { eleMatch++; } } if (winR >= s.length()) { winL++; char lEnd = l.charAt(winL); count = eleMap.get(lEnd); if (count != null) { eleMap.put(lEnd, count + 1); if (count == 0) { eleMatch--; } } } if (eleMatch == eleMap.size()) { result.add(winR - s.length() + 1); } } return result; } private static HashMap<Character, Integer> mapify(String s) { HashMap<Character, Integer> result = new HashMap<>(); for (int i = 0; i < s.length(); i++) { Integer count = result.get(s.charAt(i)); if (count == null) { result.put(s.charAt(i), 1); } else { result.put(s.charAt(i), count + 1); } } return result; } public static void main(String[] args) { String l = "bcdefg"; String s = "a"; List<Integer> result = Anagrams.allAnagrams(s, l); int idle = 0; } }
package com.sozolab.clientserver; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.ArrayList; public class UDPListAdapter extends BaseAdapter { private ArrayList<UDPData> listData; private LayoutInflater layoutInflater; public UDPListAdapter(Context aContext, ArrayList<UDPData> listData) { this.listData = listData; layoutInflater = LayoutInflater.from(aContext); } @Override public int getCount() { return listData.size(); } @Override public Object getItem(int position) { return listData.get(position); } @Override public long getItemId(int position) { return position; } public View getView(int position, View v, ViewGroup vg) { ViewHolder holder; if (v == null) { v = layoutInflater.inflate(R.layout.list_item, null); holder = new ViewHolder(); holder.messageItem = (TextView) v.findViewById(R.id.messageItem); v.setTag(holder); } else { holder = (ViewHolder) v.getTag(); } holder.messageItem.setText(listData.get(position).getMessage()); return v; } static class ViewHolder { TextView messageItem; } }
package com.mcode.nescompiler.program.directives; import java.util.ArrayList; import java.util.List; import com.mcode.nescompiler.program.AddressTable; import com.mcode.nescompiler.program.Parameter; public class AdjustAddressDirective implements Directive { private List<Parameter> params = new ArrayList<Parameter>(); @Override public void init(List<Parameter> parameters) { params.addAll(parameters); } @Override public void execute() { AddressTable.setAddressAdjustment(params.get(0).evaluate()); } }
package de.varylab.discreteconformal.unwrapper; import static de.varylab.discreteconformal.util.CuttingUtility.cutManifoldToDisk; import java.util.Collection; import java.util.Map; import java.util.Set; import no.uib.cipr.matrix.DenseVector; import no.uib.cipr.matrix.Matrix; import de.jtem.halfedgetools.adapter.AdapterSet; import de.varylab.discreteconformal.adapter.EuclideanLengthWeightAdapter; import de.varylab.discreteconformal.heds.CoEdge; import de.varylab.discreteconformal.heds.CoFace; import de.varylab.discreteconformal.heds.CoHDS; import de.varylab.discreteconformal.heds.CoVertex; import de.varylab.discreteconformal.unwrapper.numerics.CEuclideanOptimizable; import de.varylab.discreteconformal.util.CuttingUtility; import de.varylab.discreteconformal.util.CuttingUtility.CuttingInfo; import de.varylab.discreteconformal.util.Search.WeightAdapter; import de.varylab.discreteconformal.util.UnwrapUtility; import de.varylab.mtjoptimization.NotConvergentException; import de.varylab.mtjoptimization.newton.NewtonOptimizer; import de.varylab.mtjoptimization.newton.NewtonOptimizer.Solver; import de.varylab.mtjoptimization.stepcontrol.ArmijoStepController; public class EuclideanUnwrapper implements Unwrapper { private QuantizationMode conesMode = QuantizationMode.AllAngles, boundaryQuantMode = QuantizationMode.AllAngles; private BoundaryMode boundaryMode = BoundaryMode.Isometric; private int maxIterations = 150, numCones = 0; private double gradTolerance = 1E-8; private CoVertex layoutRoot = null; private CoVertex cutRoot = null; private Set<CoEdge> cutGraph = null; private CuttingInfo<CoVertex, CoEdge, CoFace> cutInfo = null; private Map<CoEdge, Double> lengthMap = null; @Override public void unwrap(CoHDS surface, int genus, AdapterSet aSet) throws Exception { CEuclideanOptimizable opt = new CEuclideanOptimizable(surface); UnwrapUtility.prepareInvariantDataEuclidean(opt.getFunctional(), surface, boundaryMode, boundaryQuantMode, aSet); // cones Collection<CoVertex> cones = ConesUtility.setUpCones(surface, numCones); // optimization int n = opt.getDomainDimension(); DenseVector u = new DenseVector(n); // set variable lambda start values for (CoEdge e : surface.getPositiveEdges()) { if (e.getSolverIndex() >= 0) { u.set(e.getSolverIndex(), e.getLambda()); } } Matrix H = opt.getHessianTemplate(); NewtonOptimizer optimizer = new NewtonOptimizer(H); optimizer.setStepController(new ArmijoStepController()); optimizer.setSolver(Solver.BiCGstab); optimizer.setError(gradTolerance); optimizer.setMaxIterations(maxIterations); try { optimizer.minimize(u, opt); } catch (NotConvergentException e) { throw new UnwrapException("Optimization did not succeed: " + e.getMessage()); } if (!cones.isEmpty()) { if (conesMode != QuantizationMode.AllAngles) { cones = ConesUtility.quantizeCones(surface, cones, conesMode); n = opt.getDomainDimension(); u = new DenseVector(n); H = opt.getHessianTemplate(); optimizer.setHessianTemplate(H); try { optimizer.minimize(u, opt); } catch (NotConvergentException e) { throw new UnwrapException("Cone quantization did not succeed: " + e.getMessage()); } } } WeightAdapter<CoEdge> weights = new EuclideanLengthWeightAdapter(u); CoVertex root = surface.getVertex(0); if (cutRoot != null) { root = cutRoot; } switch (genus) { case 0: cutInfo = ConesUtility.cutMesh(surface); break; case 1: if (cutGraph != null) { cutInfo = new CuttingInfo<CoVertex, CoEdge, CoFace>(); CuttingUtility.cutAtEdges(cutInfo, cutGraph); } else { cutInfo = CuttingUtility.cutTorusToDisk(surface, root, weights); } break; default: if (cutGraph != null) { cutInfo = new CuttingInfo<CoVertex, CoEdge, CoFace>(); cutInfo.cutRoot = root; CuttingUtility.cutAtEdges(cutInfo, cutGraph); } else { cutInfo = cutManifoldToDisk(surface, root, weights); } } lengthMap = EuclideanLayout.getLengthMap(surface, opt.getFunctional(), u); layoutRoot = EuclideanLayout.doLayout(surface, opt.getFunctional(), u); } public void setNumCones(int numCones) { this.numCones = numCones; } public void setConeMode(QuantizationMode quantizationMode) { this.conesMode = quantizationMode; } @Override public void setGradientTolerance(double tol) { gradTolerance = tol; } @Override public void setMaxIterations(int maxIterations) { this.maxIterations = maxIterations; } public void setBoundaryQuantMode(QuantizationMode boundaryQuantMode) { this.boundaryQuantMode = boundaryQuantMode; } public void setBoundaryMode(BoundaryMode boundaryMode) { this.boundaryMode = boundaryMode; } @Override public void setCutRoot(CoVertex root) { this.cutRoot = root; } @Override public CuttingInfo<CoVertex, CoEdge, CoFace> getCutInfo() { return cutInfo; } @Override public Map<CoEdge, Double> getlengthMap() { return lengthMap; } @Override public CoVertex getLayoutRoot() { return layoutRoot; } @Override public void setCutGraph(Set<CoEdge> cutEdges) { this.cutGraph = cutEdges; } }
package my.finder.console.service; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class NoReasultSearchPerDay implements Job { public void execute(JobExecutionContext context) throws JobExecutionException { java.util.Calendar calend = java.util.Calendar.getInstance(); calend.setTime(context.getFireTime()); calend.add(java.util.Calendar.DATE, -1); KPIService.searchNoResult(calend); } }
package generating; import java.util.Calendar; import java.util.Random; public class InterestRateColumnGenerator implements ColumnGenerator{ public String generateColumnValue(Calendar[] benchTime, String[] tradeDate, boolean[] tradeDateGenerateflag,boolean[] tradeIdExistence,int rowsNumber){ String fd = new String(); Random r = new Random(); float rfr = 3 + 2 * r.nextFloat(); rfr = (float) Math.round(rfr * 100) / 100; fd = String.valueOf(rfr); return fd; } }