blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
e51111d142e0a804cd94729a97571175dc5a5a1b
Java
bleujin/aradon
/test/net/ion/radon/core/TestBaseAradon.java
UTF-8
797
2.109375
2
[]
no_license
package net.ion.radon.core; import net.ion.framework.util.InstanceCreationException; import org.apache.commons.configuration.ConfigurationException; import org.restlet.Request; import org.restlet.Response; import org.restlet.data.Method; public class TestBaseAradon { protected Aradon testAradon() throws ConfigurationException, InstanceCreationException{ return testAradon("./resource/config/readonly-config.xml") ; } protected Aradon testAradon(String configPath) throws ConfigurationException, InstanceCreationException{ Aradon aradon = Aradon.create(configPath) ; aradon.start() ; return aradon ; } protected Response handle(Aradon aradon, String path, Method method) { return aradon.handle(new Request(method, "riap://component" + path)) ; } }
true
2fdae9e7798884a58a4f2b15cc39e1d2b20f4f47
Java
enesorhan95/JPokemon
/src/org/jpokemon/pokemon/ConditionEffect.java
UTF-8
1,971
2.875
3
[]
no_license
package org.jpokemon.pokemon; public enum ConditionEffect { BURN, PARALYZE, SLEEP, POISON, FREEZE, CONFUSE, WRAP, FLINCH; public double persistanceChance() { switch (this) { case BURN: case PARALYZE: case POISON: return 1; case SLEEP: return .333; case FREEZE: return .8; case CONFUSE: case WRAP: return .667; default: return 0; } } public boolean blocksAttack() { switch (this) { case FREEZE: case SLEEP: case FLINCH: case CONFUSE: return true; case PARALYZE: return Math.random() < .25; default: return false; } } public double damagePercentage() { switch (this) { case BURN: case POISON: case WRAP: return .1; case CONFUSE: return 0; // TODO default: return 0; } } public double catchBonus() { switch (this) { case FREEZE: case SLEEP: return 2; case BURN: case POISON: case PARALYZE: return 1.5; default: return 1; } } public String getPersistanceMessage() { switch (this) { case BURN: return " was injured by it's burn!"; case SLEEP: return " is still sleeping!"; case POISON: return " was injured by the poison!"; case FREEZE: return " is still frozen!"; case CONFUSE: return " hurt itself in it's confusion!"; case WRAP: return " was injured by the binding!"; case PARALYZE: return " is paralyzed!"; default: return null; } } public String getDissipationMessage() { switch (this) { case SLEEP: return " woke up!"; case FREEZE: return " broke out of the ice!"; case WRAP: return " freed itself!"; case CONFUSE: return " is no longer confused!"; default: return null; } } }
true
c40014cc17507106b34b85c8f3901ff0c1420f2d
Java
liangyuan109/109
/src/main/java/com/search/data/MyIndexFiles.java
UTF-8
13,379
1.726563
2
[]
no_license
package com.search.data; import org.apache.lucene.analysis.Analyzer; /** * 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. */ import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.search.similarities.BM25Similarity; import org.apache.lucene.search.similarities.BooleanSimilarity; import org.apache.lucene.search.similarities.IBSimilarity; import org.apache.lucene.search.similarities.LMDirichletSimilarity; import org.apache.lucene.search.similarities.LMSimilarity; import org.apache.lucene.search.similarities.Similarity; import org.apache.lucene.search.similarities.SimilarityBase; import org.apache.lucene.search.similarities.TFIDFSimilarity; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; //import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.Version; import org.apache.pdfbox.pdfparser.PDFParser; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.text.PDFTextStripper; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONObject; import com.dem.server.HttpURLConnectionExample; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.SimpleBookmark; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** Index all text files under a directory. */ public class MyIndexFiles { public MyIndexFiles() {} static final File INDEX_DIR = new File("./index"); static HashMap<String,ArrayList<SearchFileInfo>> m_sfi; static HashMap<String,ArrayList<SearchFileInfo>> m_Hmap = new HashMap<String,ArrayList<SearchFileInfo>>(); public void SetMapList(HashMap<String,ArrayList<SearchFileInfo>> sfi) { m_sfi = sfi; } public void listMap() { Set set = m_Hmap.entrySet(); Iterator iterator = set.iterator(); while(iterator.hasNext()) { Map.Entry mentry = (Map.Entry)iterator.next(); ArrayList<SearchFileInfo> say = (ArrayList)mentry.getValue(); for(int i=0;i<say.size();i++) { System.out.println(say.get(i).strPath+say.get(i).strTiel); } // System.out.println(mentry.getValue()); } } /** Index all text files under a directory. */ public static void doIndexFiles(String args) { String usage = "java org.apache.lucene.demo.IndexFiles <root_directory>"; /* if (args.length == 0) { System.err.println("Usage: " + usage); System.exit(1); }*/ if (INDEX_DIR.exists()) { System.out.println("Cannot save index to '" +INDEX_DIR+ "' directory, please delete it first"); // System.exit(1); return; } final File docDir = new File(args); if (!docDir.exists() || !docDir.canRead()) { System.out.println("Document directory '" +docDir.getAbsolutePath()+ "' does not exist or is not readable, please check the path"); // System.exit(1); return; } Date start = new Date(); try { Path p = INDEX_DIR.toPath(); Directory d = FSDirectory.open(p); Analyzer analyzer = new StandardAnalyzer(); IndexWriterConfig conf = new IndexWriterConfig(analyzer); LMDirichletSimilarity lmSimilarity = new LMDirichletSimilarity() ; conf.setSimilarity(lmSimilarity); IndexWriter writer = new IndexWriter(d, conf); System.out.println("Indexing to directory '" +INDEX_DIR+ "'..."); SearchFileInfo searchinfo = new SearchFileInfo(); indexDocs(writer, docDir, searchinfo); System.out.println("Optimizing..."); writer.commit(); writer.close(); Date end = new Date(); System.out.println(end.getTime() - start.getTime() + " total milliseconds"); } catch (Exception e) { System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage()); } } static void indexDocs(IndexWriter writer, File file, SearchFileInfo searchinfo) throws Exception { // do not try to index files that cannot be read if (file.canRead()) { if (file.isDirectory()) { String strname = file.getName(); String[] files = file.list(); // an IO error could occur if (files != null) { for (int i = 0; i < files.length; i++) { File f = new File(file, files[i]); String name = f.getName(); SearchFileInfo sinfo = new SearchFileInfo(); if(m_Hmap.containsKey(strname)) { ArrayList<SearchFileInfo> info = m_Hmap.get(strname); // if(info != null && info.size() >= i && info.size()>0) { sinfo = info.get(i); // System.out.println(name+sinfo.strTiel+sinfo.strPath); } indexDocs(writer, new File(file, files[i]), sinfo); }else { indexDocs(writer, new File(file, files[i]), sinfo); } } } } else { // System.out.println("adding " + searchinfo.strAutor+";"+searchinfo.strTiel+searchinfo.strDate+searchinfo.strUrl); try { String strpath = searchinfo.strPath; String strauthor = searchinfo.strAutor ; String strtiel = searchinfo.strTiel; String strdate = searchinfo.strDate; String strurl = searchinfo.strUrl; Document doc = new Document(); // System.out.println(file.getName()+strtiel+strpath); writer.addDocument(FileDocument.Document(file, strauthor, strtiel, strdate, strurl)); } // at least on windows, some temporary files raise this exception with an "access denied" message // checking if the file can be read doesn't help catch (FileNotFoundException fnfe) { ; } } } } static public int compare(String str, String target) { int d[][]; int n = str.length(); int m = target.length(); int i,j; char ch1,ch2; int temp; if(n==0) { return m; } if(m==0) { return n; } d = new int[n+1][m+1]; for(i=0;i<=n;i++) { d[i][0] = i; } for(j=0;j<=m;j++) { d[0][j]=j; } for(i=1;i<=n;i++) { ch1=str.charAt(i-1); for(j=1;j<=m;j++) { ch2=target.charAt(j-1); if(ch1==ch2) { temp=0; }else { temp=1; } d[i][j] = min(d[i-1][j]+1,d[i][j-1],d[i-1][j-1]+temp); } } return d[n][m]; } static private int min(int one, int two, int three) { return (one=one<two ? one:two)<three?one:three; } static public float getSimilarityRatio(String str, String target) { return 1-(float)compare(str,target)/Math.max(str.length(), target.length()); } static public boolean readFileByLines(File file, String strsuch, String strs) throws IOException { String strname = file.getName(); String str = strsuch.toLowerCase(); if(strname.endsWith("txt")) { String tempString = null; BufferedReader reader = null; StringBuffer response = new StringBuffer(); String strss = strs.toLowerCase(); try { reader = new BufferedReader(new FileReader(file)); int line = 0; while(line < 5 && ((tempString = reader.readLine()) != null)) { response.append(tempString.toLowerCase()); if(0.95<getSimilarityRatio(response.toString(), str) && str.length()>20) { reader.close(); return true; } line++; } reader.close(); }catch(Exception e) { e.printStackTrace(); }finally { if(reader != null) { try { reader.close(); }catch(Exception el) { } } } return false; } else { PDFParsen pdf = new PDFParsen(); String strtitle = pdf.getPDFInformation(file.getAbsolutePath()); if(0.99<getSimilarityRatio(strtitle.toLowerCase(), str) && str.length()>20) { return true; } } return false; } public ArrayList<File> getFileList(String strPath) { ArrayList<File> filelist = new ArrayList<File>(); File dir = new File(strPath); File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组 if (files != null) { for (int i = 0; i < files.length; i++) { String fileName = files[i].getName(); if (files[i].isDirectory()) { // 判断是文件还是文件夹 getFileList(files[i].getAbsolutePath()); // 获取文件绝对路径 } else if (fileName.endsWith("txt")) { // 判断文件名是否以.txt结尾 String strFileName = files[i].getAbsolutePath(); // System.out.println("---" + strFileName); filelist.add(files[i]); } else { continue; } } } return filelist; } static public boolean findDocs(File file, String strsuch, String strs) throws Exception { // do not try to index files that cannot be read if (file.canRead()) { if (file.isDirectory()) { String strname = file.getName(); System.out.println(strname); String strpath = strname + ".txt"; // File _file = new File(strpath); // if(!_file.exists()) // _file.createNewFile(); // BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(_file)); if(!m_Hmap.containsKey(strname)/* && 0!=strname.compareTo("SIGIR")*/) { ArrayList<SearchFileInfo> ss = new ArrayList<SearchFileInfo>(); m_Hmap.put(strname, ss); } String[] files = file.list(); // an IO error could occur if (files != null) { for (int i = 0; i < files.length; i++) { SearchFileInfo sinfo = new SearchFileInfo(); File f = new File(file, files[i]); String name = f.getName(); sinfo.strPath = name; ArrayList<SearchFileInfo> m = m_Hmap.get(strname); if(m_sfi.containsKey(strname)) { ArrayList<SearchFileInfo> info = m_sfi.get(strname); for(int j = 0; j < info.size(); j++) { boolean b = findDocs(new File(file, files[i]), info.get(j).strTiel, info.get(j).strAutor); if(b) { sinfo.strAutor = info.get(j).strAutor; sinfo.strTiel = info.get(j).strTiel; sinfo.strUrl = info.get(j).strUrl; sinfo.strDate = info.get(j).strDate; sinfo.strDescrip = info.get(j).strDescrip; sinfo.strPath = name; m.add(sinfo); // bufferedWriter.write(sinfo.strPath+"\r\n"); // bufferedWriter.write(sinfo.strTiel+"\r\n"); // bufferedWriter.flush(); break; } } } else { findDocs(new File(file, files[i]), strsuch, strs); } // File fs = new File(file, files[i]); if(sinfo.strTiel.isEmpty()) { m.add(sinfo); } } } // bufferedWriter.close(); } else { try { return readFileByLines(file, strsuch, strs); } // at least on windows, some temporary files raise this exception with an "access denied" message // checking if the file can be read doesn't help catch (Exception fnfe) { ; } } } return false; } }
true
af7e4a46f91d4f818030a9c6e960e7539ccd37e2
Java
Gamalhassan95/Into-to-Java
/src/Classes/GradeBookTest2.java
UTF-8
833
3.3125
3
[]
no_license
package Classes; import java.util.Scanner; public class GradeBookTest2 { public static void main( String[] args) { Scanner input = new Scanner( System.in ); GradeBook2 myGradeBook = new GradeBook2("g", "h" ); System.out.printf("Initial course name is: %s\n\n", myGradeBook.getCourseName() ); System.out.printf("Initial course Instructor is: %s\n\n", myGradeBook.getCourseInstructor()); System.out.println("Please enter the course name:" ); String theName = input.nextLine(); System.out.println("Please enter the Instructor name:" ); String theInstructor = input.nextLine(); myGradeBook.setCourseName( theName ); myGradeBook.setCourseInstructor( theInstructor); System.out.println(); myGradeBook.displayMessage(); } }
true
b8550549fb94209742a9efa4227bd157dd764a01
Java
nanoxic/jNano
/src/test/java/uk/oczadly/karl/jnano/util/CurrencyDivisorTest.java
UTF-8
3,570
2.859375
3
[ "MIT" ]
permissive
package uk.oczadly.karl.jnano.util; import uk.oczadly.karl.jnano.tests.UtilTests; import org.junit.Test; import org.junit.experimental.categories.Category; import java.math.BigDecimal; import java.math.BigInteger; import static org.junit.Assert.*; @Category(UtilTests.class) public class CurrencyDivisorTest { @Test public void testValues() { assertEquals("1000000000000000000000000000000000", CurrencyDivisor.GIGA.getValue().toString()); assertEquals("1000000000000000000000000", CurrencyDivisor.XRB.getValue().toString()); assertEquals("1", CurrencyDivisor.RAW.getValue().toString()); } @Test public void testDecimalConversionUpscale() { //Convert RAW to GIGA assertEquals("25", CurrencyDivisor.GIGA.convert(new BigDecimal("25000000000000000000000000000000000"), CurrencyDivisor.RAW).stripTrailingZeros().toPlainString()); //Convert RAW to GIGA assertEquals("25.000000000000000000000000000000001", CurrencyDivisor.GIGA.convert(new BigDecimal("25000000000000000000000000000000001"), CurrencyDivisor.RAW).stripTrailingZeros().toPlainString()); //Convert RAW to GIGA assertEquals("24.999999999999999999999999999999999", CurrencyDivisor.GIGA.convert(new BigDecimal("24999999999999999999999999999999999"), CurrencyDivisor.RAW).stripTrailingZeros().toPlainString()); //Convert MILLI to XRB assertEquals("2", CurrencyDivisor.XRB.convert(new BigDecimal("2000"), CurrencyDivisor.MILLI).stripTrailingZeros().toPlainString()); } @Test public void testDecimalConversionDownscale() { //Convert 25 GIGA to RAW assertEquals("25000000000000000000000000000000000", CurrencyDivisor.RAW.convert(new BigDecimal(25), CurrencyDivisor.GIGA).stripTrailingZeros().toPlainString()); //Convert 1 GIGA to MEGA assertEquals("1000", CurrencyDivisor.MEGA.convert(BigDecimal.ONE, CurrencyDivisor.GIGA).stripTrailingZeros().toPlainString()); //Convert 1 GIGA to KILO assertEquals("1000000", CurrencyDivisor.KILO.convert(BigDecimal.ONE, CurrencyDivisor.GIGA).stripTrailingZeros().toPlainString()); } @Test public void testIntegerConversionUpscale() { //Convert RAW to GIGA assertEquals("25", CurrencyDivisor.GIGA.convertInt(new BigInteger("25000000000000000000000000000000000"), CurrencyDivisor.RAW).toString()); //Convert RAW to GIGA assertEquals("25", CurrencyDivisor.GIGA.convertInt(new BigInteger("25000000000000000000000000000000001"), CurrencyDivisor.RAW).toString()); //Convert RAW to GIGA assertEquals("24", CurrencyDivisor.GIGA.convertInt(new BigInteger("24999999999999999999999999999999999"), CurrencyDivisor.RAW).toString()); //Convert MILLI to XRB assertEquals("2", CurrencyDivisor.XRB.convertInt(new BigInteger("2000"), CurrencyDivisor.MILLI).toString()); } @Test public void testIntegerConversionDownscale() { //Convert 25 GIGA to RAW assertEquals("25000000000000000000000000000000000", CurrencyDivisor.RAW.convertInt(BigInteger.valueOf(25), CurrencyDivisor.GIGA).toString()); //Convert 1 GIGA to MEGA assertEquals("1000", CurrencyDivisor.MEGA.convertInt(BigInteger.ONE, CurrencyDivisor.GIGA).toString()); //Convert 1 GIGA to KILO assertEquals("1000000", CurrencyDivisor.KILO.convertInt(BigInteger.ONE, CurrencyDivisor.GIGA).toString()); } }
true
9630869657fa30b20559b439fcd2767ac292308a
Java
bjuncklaus/KohonenMap
/src/br/com/unisul/Window.java
UTF-8
705
2.625
3
[]
no_license
package br.com.unisul; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import javax.swing.JFrame; public class Window extends JFrame { private static final long serialVersionUID = 4930891648824266753L; private BufferedImage imagem; public Window() { super("Learning Process"); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); } public void paint(Graphics g) { super.paint(g); Graphics2D g2 = (Graphics2D)g.create(); g2.drawImage(imagem, 0, 0, null); } public BufferedImage getImagem() { return imagem; } public void setImagem(BufferedImage imagem) { this.imagem = imagem; } }
true
e3bf59e066a451c2c3303fe62aa4026dfa7adcf3
Java
yanru0213/JigsawPuzzle
/puzzle/src/puzzle/Puzzle.java
UTF-8
42,474
2.78125
3
[]
no_license
package puzzle; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.Timer; public class Puzzle extends JFrame { JPanel menuP; JPanel gameP; JPanel gameoverP; String types[] = {"Number", "Picture"}; String levels[] = {"Easy(3x3)", "Normal(5x5)", "Hard(7x7)"}; int levelRow[] = {3, 5, 7}; int moveTimes = 0; String Time = "00:00"; String data[] = {" ", " ", " "}; JButton[] button; int order[][]; String orderColor[][]; GridLayout gridLayout; int Row; int number; String color[] = {"#f37152", "#eab34b", "#7d7d1e", "#15a4b4"}; String[] imgType = {"easy", "normal", "difficult"}; int imageNum; JLabel information2; Timer timer; public Puzzle() { super("Klotski"); setResizable(false); //不可改變大小 setSize(400, 300); setLocationRelativeTo(null); //視窗置中 ImageIcon icon = new ImageIcon(("img/pageicon.png")); setIconImage(icon.getImage()); //設定icon //menu畫面 menuP = new JPanel(); menuP.setBackground(Color.decode("#e9e5d0")); add(menuP); menuP.setLayout(new GridLayout(4, 1)); Panel p1 = new Panel(new FlowLayout(FlowLayout.CENTER)); menuP.add(p1); JLabel title = new JLabel("<html><h1>Klotski Game</h1></html>"); p1.add(title); Panel p2 = new Panel(new FlowLayout(FlowLayout.CENTER)); menuP.add(p2); JLabel nameLabel = new JLabel("Enter Your Name:"); p2.add(nameLabel); JTextField nameText = new JTextField(10); p2.add(nameText); Panel p3 = new Panel(new FlowLayout(FlowLayout.CENTER)); menuP.add(p3); JLabel typeLabel = new JLabel("Type:"); p3.add(typeLabel); JComboBox type = new JComboBox(types); p3.add(type); type.setBackground(Color.decode("#15a4b4")); type.setForeground(Color.decode("#3f3534")); JLabel blank = new JLabel(" "); p3.add(blank); JLabel levelLabel = new JLabel("Level:"); p3.add(levelLabel); JComboBox level = new JComboBox(levels); p3.add(level); level.setBackground(Color.decode("#eab34b")); level.setForeground(Color.decode("#3f3534")); Panel p4 = new Panel(new FlowLayout(FlowLayout.CENTER)); menuP.add(p4); JButton start = new JButton("START"); p4.add(start); start.setBackground(Color.decode("#f37152")); start.setBorderPainted(false); start.setForeground(Color.decode("#3f3534")); //menu頁面的按鈕 start.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (nameText.getText().equals("")) { data[0] = "player1"; } else { data[0] = nameText.getText(); } data[1] = types[type.getSelectedIndex()]; data[2] = levels[level.getSelectedIndex()]; moveTimes = 0; remove(menuP); //game畫面 gameP = new JPanel(); gameP.setBackground(Color.decode("#e9e5d0")); BorderLayout borderLayout = new BorderLayout(); gameP.setLayout(borderLayout); setSize(600, 600); setLocationRelativeTo(null); add(gameP); Panel p5 = new Panel(new GridLayout(2, 1)); gameP.add(p5, BorderLayout.NORTH); Panel p51 = new Panel(new FlowLayout(FlowLayout.CENTER)); p5.add(p51); JLabel title2 = new JLabel("<html><h1>Klotski Game</h1></html>"); p51.add(title2); Panel p52 = new Panel(new GridLayout(2, 1)); p5.add(p52); Panel p521 = new Panel(new FlowLayout(FlowLayout.CENTER)); p52.add(p521); JLabel information = new JLabel("Player:" + data[0] + " Type:" + data[1] + " Level:" + data[2]); p521.add(information); Panel p522 = new Panel(new FlowLayout(FlowLayout.CENTER)); p52.add(p522); information2 = new JLabel("Moves:" + moveTimes + " Time:" + Time); p522.add(information2); JPanel klotski; //images puzzle if (type.getSelectedIndex() == 1) { Row = levelRow[level.getSelectedIndex()]; number = Row * Row; gridLayout = new GridLayout(Row, Row); order = new int[Row][Row]; imageNum = level.getSelectedIndex(); for (int i = 0; i < Row; i++) { for (int j = 0; j < Row; j++) { order[i][j] = 1000; } } klotski = new JPanel(gridLayout); klotski.setSize(400, 400); button = new JButton[number]; for (int i = 0; i < number - 1; i++) { while (true) { int randomNum; randomNum = (int) (Math.random() * (number - 1)); boolean comfirm = false; for (int a = 0; a < Row; a++) { for (int b = 0; b < Row; b++) { if (randomNum == order[a][b]) { comfirm = true; } } } if (comfirm) { comfirm = false; } else { button[randomNum] = new JButton(""); button[randomNum].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String emptyName = button[number - 1].getName(); String empty[] = emptyName.split(""); int emptyR = Integer.valueOf(empty[0]); int emptyC = Integer.valueOf(empty[1]); char emptyRow = emptyName.charAt(0);//空白按鈕行 char emptyCol = emptyName.charAt(1);//空白按鈕列 JButton clickButton = (JButton) e.getSource(); String clickName = clickButton.getName(); String click[] = clickName.split(""); int clickR = Integer.valueOf(click[0]); int clickC = Integer.valueOf(click[1]); char clickRow = clickName.charAt(0); char clickCol = clickName.charAt(1); //判斷是否相鄰 if (Math.abs(clickRow - emptyRow) + Math.abs(clickCol - emptyCol) == 1) { //將被單擊的圖片移動到空白按鈕上 moveTimes++; information2.setText("Moves:" + moveTimes + " Time:" + Time); button[number - 1].setIcon(clickButton.getIcon()); button[number - 1].setEnabled(true); clickButton.setIcon(new ImageIcon("img/picture/" + imgType[imageNum] + "/" + number + ".jpg")); clickButton.setEnabled(false); button[number - 1] = clickButton; int n = order[emptyR][emptyC]; order[emptyR][emptyC] = order[clickR][clickC]; order[clickR][clickC] = n; } int count = 0; boolean countRight = true; for (int i = 0; i < Row; i++) { for (int j = 0; j < Row; j++) { if (order[i][j] == count) { count += 1; } else { countRight = false; } } } if (countRight) { timer.cancel(); JOptionPane.showMessageDialog(null, "Congratulations! You finished the Klotski.", "GameOver", JOptionPane.PLAIN_MESSAGE); remove(gameP); setSize(230, 270); setLocationRelativeTo(null); //gameoverP畫面 gameoverP = new JPanel(); gameoverP.setBackground(Color.decode("#e9e5d0")); gameoverP.setLayout(new BorderLayout()); Panel p9 = new Panel(new FlowLayout(FlowLayout.CENTER)); gameoverP.add(p9, BorderLayout.NORTH); JLabel title3 = new JLabel("<html><h2>---Play Result---</h2></html>"); p9.add(title3); Panel p10 = new Panel(new FlowLayout(FlowLayout.CENTER)); gameoverP.add(p10, BorderLayout.CENTER); Panel p101 = new Panel(new GridLayout(5, 1, 250, 10)); p10.add(p101); JLabel result1 = new JLabel("Player:" + data[0]); p101.add(result1); JLabel result2 = new JLabel("Type:" + data[1]); p101.add(result2); JLabel result3 = new JLabel("Level:" + data[2]); p101.add(result3); JLabel result4 = new JLabel("Moves:" + moveTimes); p101.add(result4); JLabel result5 = new JLabel("Time:" + Time); p101.add(result5); Panel p11 = new Panel(new FlowLayout(FlowLayout.CENTER)); gameoverP.add(p11, BorderLayout.SOUTH); JButton menu2 = new JButton("MENU"); p11.add(menu2); menu2.setBackground(Color.decode("#eab34b")); menu2.setBorderPainted(false); menu2.setForeground(Color.decode("#3f3534")); add(gameoverP); //gameover頁面的按鈕 menu2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { remove(gameoverP); setSize(400, 300); setLocationRelativeTo(null); nameText.setText(""); add(menuP); } }); } } }); button[randomNum].setBackground(Color.decode("#e9e5d0")); ImageIcon icon = new ImageIcon("img/picture/" + imgType[imageNum] + "/" + (randomNum + 1) + ".jpg"); button[randomNum].setIcon(icon); //button[randomNum].setBorder(BorderFactory.createLineBorder(Color.decode("#3f3534"))); button[randomNum].setBorderPainted(false); int x = i / Row; int y = i % Row; button[randomNum].setName(x + "" + y); order[x][y] = randomNum; klotski.add(button[randomNum]); break; } } } button[number - 1] = new JButton(""); button[number - 1].setName((Row - 1) + "" + (Row - 1)); button[number - 1].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String emptyName = button[number - 1].getName(); String empty[] = emptyName.split(""); int emptyR = Integer.valueOf(empty[0]); int emptyC = Integer.valueOf(empty[1]); char emptyRow = emptyName.charAt(0);//空白按鈕行 char emptyCol = emptyName.charAt(1);//空白按鈕列 JButton clickButton = (JButton) e.getSource(); String clickName = clickButton.getName(); String click[] = clickName.split(""); int clickR = Integer.valueOf(click[0]); int clickC = Integer.valueOf(click[1]); char clickRow = clickName.charAt(0); char clickCol = clickName.charAt(1); //判斷是否相鄰 if (Math.abs(clickRow - emptyRow) + Math.abs(clickCol - emptyCol) == 1) { //將被單擊的圖片移動到空白按鈕上 moveTimes++; information2.setText("Moves:" + moveTimes + " Time:" + Time); button[number - 1].setIcon(clickButton.getIcon()); button[number - 1].setEnabled(true); clickButton.setIcon(new ImageIcon("img/picture/" + imgType[imageNum] + "/" + number + ".jpg")); clickButton.setEnabled(false); button[number - 1] = clickButton; int n = order[emptyR][emptyC]; order[emptyR][emptyC] = order[clickR][clickC]; order[clickR][clickC] = n; } int count = 0; boolean countRight = true; for (int i = 0; i < Row; i++) { for (int j = 0; j < Row; j++) { if (order[i][j] == count) { count += 1; } else { countRight = false; } } } if (countRight) { timer.cancel(); JOptionPane.showMessageDialog(null, "Congratulations! You finished the Klotski.", "GameOver", JOptionPane.PLAIN_MESSAGE); remove(gameP); setSize(230, 270); setLocationRelativeTo(null); //gameoverP畫面 gameoverP = new JPanel(); gameoverP.setBackground(Color.decode("#e9e5d0")); gameoverP.setLayout(new BorderLayout()); Panel p9 = new Panel(new FlowLayout(FlowLayout.CENTER)); gameoverP.add(p9, BorderLayout.NORTH); JLabel title3 = new JLabel("<html><h2>---Play Result---</h2></html>"); p9.add(title3); Panel p10 = new Panel(new FlowLayout(FlowLayout.CENTER)); gameoverP.add(p10, BorderLayout.CENTER); Panel p101 = new Panel(new GridLayout(5, 1, 250, 10)); p10.add(p101); JLabel result1 = new JLabel("Player:" + data[0]); p101.add(result1); JLabel result2 = new JLabel("Type:" + data[1]); p101.add(result2); JLabel result3 = new JLabel("Level:" + data[2]); p101.add(result3); JLabel result4 = new JLabel("Moves:" + moveTimes); p101.add(result4); JLabel result5 = new JLabel("Time:" + Time); p101.add(result5); Panel p11 = new Panel(new FlowLayout(FlowLayout.CENTER)); gameoverP.add(p11, BorderLayout.SOUTH); JButton menu2 = new JButton("MENU"); p11.add(menu2); menu2.setBackground(Color.decode("#eab34b")); menu2.setBorderPainted(false); menu2.setForeground(Color.decode("#3f3534")); add(gameoverP); //gameover頁面的按鈕 menu2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { remove(gameoverP); setSize(400, 300); setLocationRelativeTo(null); nameText.setText(""); add(menuP); } }); } } }); ImageIcon icon2 = new ImageIcon("img/picture/" + imgType[imageNum] + "/" + number + ".jpg"); button[number - 1].setIcon(icon2); //button[number - 1].setBorder(BorderFactory.createLineBorder(Color.decode("#3f3534"))); button[number - 1].setBorderPainted(false); button[number - 1].setEnabled(false); order[Row - 1][Row - 1] = number - 1; klotski.add(button[number - 1]); gameP.add(klotski, BorderLayout.CENTER); //number puzzle } else { Row = levelRow[level.getSelectedIndex()]; number = Row * Row; gridLayout = new GridLayout(Row, Row); order = new int[Row][Row]; orderColor = new String[Row][Row]; for (int i = 0; i < Row; i++) { for (int j = 0; j < Row; j++) { order[i][j] = 1000; } } klotski = new JPanel(gridLayout); klotski.setSize(400, 400); button = new JButton[number]; for (int i = 0; i < number - 1; i++) { while (true) { int randomNum; randomNum = (int) (Math.random() * (number - 1)); boolean comfirm = false; for (int a = 0; a < Row; a++) { for (int b = 0; b < Row; b++) { if (randomNum == order[a][b]) { comfirm = true; } } } if (comfirm) { comfirm = false; } else { button[randomNum] = new JButton("" + (randomNum + 1)); button[randomNum].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String emptyName = button[number - 1].getName(); String empty[] = emptyName.split(""); int emptyR = Integer.valueOf(empty[0]); int emptyC = Integer.valueOf(empty[1]); char emptyRow = emptyName.charAt(0);//空白按鈕行 char emptyCol = emptyName.charAt(1);//空白按鈕列 JButton clickButton = (JButton) e.getSource(); String clickName = clickButton.getName(); String click[] = clickName.split(""); int clickR = Integer.valueOf(click[0]); int clickC = Integer.valueOf(click[1]); char clickRow = clickName.charAt(0); char clickCol = clickName.charAt(1); //判斷是否相鄰 if (Math.abs(clickRow - emptyRow) + Math.abs(clickCol - emptyCol) == 1) { moveTimes++; information2.setText("Moves:" + moveTimes + " Time:" + Time); //將被單擊的圖片移動到空白按鈕上 Font f = new Font("Arial", Font.BOLD, 30); button[number - 1].setFont(f); button[number - 1].setText("" + (order[clickR][clickC] + 1)); button[number - 1].setBackground(Color.decode(orderColor[clickR][clickC])); button[number - 1].setForeground(Color.decode("#3f3534")); button[number - 1].setEnabled(true); clickButton.setBorder(BorderFactory.createLineBorder(Color.decode("#3f3534"))); clickButton.setBackground(Color.decode("#FFFFFF")); clickButton.setEnabled(false); clickButton.setText(""); button[number - 1] = clickButton; int n = order[emptyR][emptyC]; order[emptyR][emptyC] = order[clickR][clickC]; order[clickR][clickC] = n; String s = orderColor[emptyR][emptyC]; orderColor[emptyR][emptyC] = orderColor[clickR][clickC]; orderColor[clickR][clickC] = s; } int count = 0; boolean countRight = true; for (int i = 0; i < Row; i++) { for (int j = 0; j < Row; j++) { if (order[i][j] == count) { } else { countRight = false; } count++; } } if (countRight) { timer.cancel(); JOptionPane.showMessageDialog(null, "Congratulations! You finished the Klotski.", "GameOver", JOptionPane.PLAIN_MESSAGE); remove(gameP); setSize(230, 270); setLocationRelativeTo(null); //gameoverP畫面 gameoverP = new JPanel(); gameoverP.setBackground(Color.decode("#e9e5d0")); gameoverP.setLayout(new BorderLayout()); Panel p9 = new Panel(new FlowLayout(FlowLayout.CENTER)); gameoverP.add(p9, BorderLayout.NORTH); JLabel title3 = new JLabel("<html><h2>---Play Result---</h2></html>"); p9.add(title3); Panel p10 = new Panel(new FlowLayout(FlowLayout.CENTER)); gameoverP.add(p10, BorderLayout.CENTER); Panel p101 = new Panel(new GridLayout(5, 1, 250, 10)); p10.add(p101); JLabel result1 = new JLabel("Player:" + data[0]); p101.add(result1); JLabel result2 = new JLabel("Type:" + data[1]); p101.add(result2); JLabel result3 = new JLabel("Level:" + data[2]); p101.add(result3); JLabel result4 = new JLabel("Moves:" + moveTimes); p101.add(result4); JLabel result5 = new JLabel("Time:" + Time); p101.add(result5); Panel p11 = new Panel(new FlowLayout(FlowLayout.CENTER)); gameoverP.add(p11, BorderLayout.SOUTH); JButton menu2 = new JButton("MENU"); p11.add(menu2); menu2.setBackground(Color.decode("#eab34b")); menu2.setBorderPainted(false); menu2.setForeground(Color.decode("#3f3534")); add(gameoverP); //gameover頁面的按鈕 menu2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { remove(gameoverP); setSize(400, 300); setLocationRelativeTo(null); nameText.setText(""); add(menuP); } }); } } }); int c = (int) (Math.random() * 4); Font f = new Font("Arial", Font.BOLD, 30); button[randomNum].setFont(f); button[randomNum].setBackground(Color.decode(color[c])); button[randomNum].setBorder(BorderFactory.createLineBorder(Color.decode("#3f3534"))); button[randomNum].setForeground(Color.decode("#3f3534")); int x = i / Row; int y = i % Row; button[randomNum].setName(x + "" + y); order[x][y] = randomNum; orderColor[x][y] = color[c]; klotski.add(button[randomNum]); break; } } } button[number - 1] = new JButton(""); button[number - 1].setName((Row - 1) + "" + (Row - 1)); button[number - 1].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String emptyName = button[number - 1].getName(); String empty[] = emptyName.split(""); int emptyR = Integer.valueOf(empty[0]); int emptyC = Integer.valueOf(empty[1]); char emptyRow = emptyName.charAt(0);//空白按鈕行 char emptyCol = emptyName.charAt(1);//空白按鈕列 JButton clickButton = (JButton) e.getSource(); String clickName = clickButton.getName(); String click[] = clickName.split(""); int clickR = Integer.valueOf(click[0]); int clickC = Integer.valueOf(click[1]); char clickRow = clickName.charAt(0); char clickCol = clickName.charAt(1); //判斷是否相鄰 if (Math.abs(clickRow - emptyRow) + Math.abs(clickCol - emptyCol) == 1) { moveTimes++; information2.setText("Moves:" + moveTimes + " Time:" + Time); //將被單擊的圖片移動到空白按鈕上 Font f = new Font("Arial", Font.BOLD, 30); button[number - 1].setFont(f); button[number - 1].setText("" + (order[clickR][clickC] + 1)); button[number - 1].setBackground(Color.decode(orderColor[clickR][clickC])); button[number - 1].setForeground(Color.decode("#3f3534")); button[number - 1].setEnabled(true); clickButton.setBorder(BorderFactory.createLineBorder(Color.decode("#3f3534"))); clickButton.setBackground(Color.decode("#FFFFFF")); clickButton.setEnabled(false); clickButton.setText(""); button[number - 1] = clickButton; int n = order[emptyR][emptyC]; order[emptyR][emptyC] = order[clickR][clickC]; order[clickR][clickC] = n; String s = orderColor[emptyR][emptyC]; orderColor[emptyR][emptyC] = orderColor[clickR][clickC]; orderColor[clickR][clickC] = s; } int count = 0; boolean countRight = true; for (int i = 0; i < Row; i++) { for (int j = 0; j < Row; j++) { if (order[i][j] == count) { } else { countRight = false; } count++; } } if (countRight) { timer.cancel(); JOptionPane.showMessageDialog(null, "Congratulations! You finished the Klotski.", "GameOver", JOptionPane.PLAIN_MESSAGE); remove(gameP); setSize(230, 270); setLocationRelativeTo(null); //gameoverP畫面 gameoverP = new JPanel(); gameoverP.setBackground(Color.decode("#e9e5d0")); gameoverP.setLayout(new BorderLayout()); Panel p9 = new Panel(new FlowLayout(FlowLayout.CENTER)); gameoverP.add(p9, BorderLayout.NORTH); JLabel title3 = new JLabel("<html><h2>---Play Result---</h2></html>"); p9.add(title3); Panel p10 = new Panel(new FlowLayout(FlowLayout.CENTER)); gameoverP.add(p10, BorderLayout.CENTER); Panel p101 = new Panel(new GridLayout(5, 1, 250, 10)); p10.add(p101); JLabel result1 = new JLabel("Player:" + data[0]); p101.add(result1); JLabel result2 = new JLabel("Type:" + data[1]); p101.add(result2); JLabel result3 = new JLabel("Level:" + data[2]); p101.add(result3); JLabel result4 = new JLabel("Moves:" + moveTimes); p101.add(result4); JLabel result5 = new JLabel("Time:" + Time); p101.add(result5); Panel p11 = new Panel(new FlowLayout(FlowLayout.CENTER)); gameoverP.add(p11, BorderLayout.SOUTH); JButton menu2 = new JButton("MENU"); p11.add(menu2); menu2.setBackground(Color.decode("#eab34b")); menu2.setBorderPainted(false); menu2.setForeground(Color.decode("#3f3534")); add(gameoverP); //gameover頁面的按鈕 menu2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { remove(gameoverP); setSize(400, 300); setLocationRelativeTo(null); nameText.setText(""); add(menuP); } }); } } }); button[number - 1].setBackground(Color.decode("#FFFFFF")); button[number - 1].setBorder(BorderFactory.createLineBorder(Color.decode("#3f3534"))); button[number - 1].setEnabled(false); order[Row - 1][Row - 1] = number - 1; orderColor[Row - 1][Row - 1] = "#FFFFFF"; klotski.add(button[number - 1]); gameP.add(klotski, BorderLayout.CENTER); } Panel p6 = new Panel(new FlowLayout(FlowLayout.LEFT)); gameP.add(p6, BorderLayout.WEST); if (type.getSelectedIndex() == 1) { JLabel model = new JLabel(new ImageIcon("img/picture/model.jpg")); p6.add(model); } else { } Panel p8 = new Panel(new FlowLayout(FlowLayout.CENTER)); gameP.add(p8, BorderLayout.SOUTH); JButton pass = new JButton("PASS"); p8.add(pass); pass.setBackground(Color.decode("#f37152")); pass.setBorderPainted(false); pass.setForeground(Color.decode("#3f3534")); JLabel blank2 = new JLabel(" "); p8.add(blank2); JButton menu = new JButton("MENU"); p8.add(menu); menu.setBackground(Color.decode("#eab34b")); menu.setBorderPainted(false); menu.setForeground(Color.decode("#3f3534")); //Time計時 timer = new Timer(); Time = "00:00"; timer.schedule(new Timing(), 0, 1000); //game頁面的按鈕 menu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { timer.cancel(); remove(gameP); setSize(400, 300); setLocationRelativeTo(null); nameText.setText(""); add(menuP); } }); pass.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { timer.cancel(); JOptionPane.showMessageDialog(null, "Congratulations! You finished the Klotski.", "GameOver", JOptionPane.PLAIN_MESSAGE); remove(gameP); setSize(230, 270); setLocationRelativeTo(null); gameoverP = new JPanel(); add(gameoverP); //gameoverP畫面 gameoverP.setBackground(Color.decode("#e9e5d0")); gameoverP.setLayout(new BorderLayout()); Panel p9 = new Panel(new FlowLayout(FlowLayout.CENTER)); gameoverP.add(p9, BorderLayout.NORTH); JLabel title3 = new JLabel("<html><h2>---Play Result---</h2></html>"); p9.add(title3); Panel p10 = new Panel(new FlowLayout(FlowLayout.CENTER)); gameoverP.add(p10, BorderLayout.CENTER); Panel p101 = new Panel(new GridLayout(5, 1, 250, 10)); p10.add(p101); JLabel result1 = new JLabel("Player:" + data[0]); p101.add(result1); JLabel result2 = new JLabel("Type:" + data[1]); p101.add(result2); JLabel result3 = new JLabel("Level:" + data[2]); p101.add(result3); JLabel result4 = new JLabel("Moves:" + moveTimes); p101.add(result4); JLabel result5 = new JLabel("Time:" + Time); p101.add(result5); Panel p11 = new Panel(new FlowLayout(FlowLayout.CENTER)); gameoverP.add(p11, BorderLayout.SOUTH); JButton menu2 = new JButton("MENU"); p11.add(menu2); menu2.setBackground(Color.decode("#eab34b")); menu2.setBorderPainted(false); menu2.setForeground(Color.decode("#3f3534")); //gameover頁面的按鈕 menu2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { remove(gameoverP); setSize(400, 300); setLocationRelativeTo(null); nameText.setText(""); add(menuP); } }); } }); } }); } class Timing extends java.util.TimerTask { int t = 0; int m = 0; int s = 0; @Override public void run() { t++; m = t / 60; s = t % 60; if (m < 10) { Time = "0" + m + ":"; } else { Time = m + ":"; } if (s < 10) { Time += "0" + s; } else { Time += s; } information2.setText("Moves:" + moveTimes + " Time:" + Time); } } }
true
c99eb8a3f2d624831614cb1bd3cf02e22f126330
Java
DesKar/TShirtSort
/test/SortingAlgorithmsTest/TestSortBySizeColorFabric.java
UTF-8
4,214
2.578125
3
[]
no_license
package SortingAlgorithmsTest; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import tshirtsort.models.Color; import tshirtsort.models.Fabric; import tshirtsort.models.Size; import tshirtsort.models.TShirt; import tshirtsort.sorting.algorithms.BubbleSort; import tshirtsort.sorting.algorithms.BucketSort; import tshirtsort.sorting.algorithms.ISortingAlgorithm; import tshirtsort.sorting.algorithms.QuickSort; import tshirtsort.sorting.strategies.ISortingStrategy; import tshirtsort.sorting.strategies.SortBySizeColorFabricAsc; import tshirtsort.sorting.strategies.SortBySizeColorFabricDesc; public class TestSortBySizeColorFabric { List<TShirt> tShirts = new ArrayList(); List<TShirt> sortedTShirtsAsc = new ArrayList<>(); List<TShirt> sortedTShirtsDesc = new ArrayList<>(); ISortingAlgorithm bubbleSort = new BubbleSort(); ISortingAlgorithm bucketSort = new BucketSort(); ISortingAlgorithm quickSort = new QuickSort(); ISortingStrategy bySizeColorFabricAsc = new SortBySizeColorFabricAsc(); ISortingStrategy bySizeColorFabricDesc = new SortBySizeColorFabricDesc(); TShirt tShirt1 = new TShirt("Red-S-Cotton", Color.RED, Size.S, Fabric.COTTON); TShirt tShirt2 = new TShirt("Red-S-Silk", Color.RED, Size.S, Fabric.SILK); TShirt tShirt3 = new TShirt("Blue-M-Silk", Color.BLUE, Size.M, Fabric.SILK); TShirt tShirt4 = new TShirt("Violete-M-Silk", Color.VIOLET, Size.M, Fabric.SILK); TShirt tShirt5 = new TShirt("Violette-XXL-Polyester", Color.VIOLET, Size.XXL, Fabric.POLYESTER); TShirt tShirt6 = new TShirt("Violette-XS-Cashmere", Color.VIOLET, Size.XS, Fabric.CASHMERE); TShirt tShirt7 = new TShirt("Indigo-XXXL-Polyester", Color.INDIGO, Size.XXL, Fabric.POLYESTER); TShirt tShirt8 = new TShirt("Red-L-Cashmere", Color.RED, Size.L, Fabric.CASHMERE); @Before public void setUp() { tShirts.add(tShirt1); tShirts.add(tShirt2); tShirts.add(tShirt3); tShirts.add(tShirt4); tShirts.add(tShirt5); tShirts.add(tShirt6); tShirts.add(tShirt7); sortedTShirtsAsc.add(tShirt6); sortedTShirtsAsc.add(tShirt1); sortedTShirtsAsc.add(tShirt2); sortedTShirtsAsc.add(tShirt3); sortedTShirtsAsc.add(tShirt4); sortedTShirtsAsc.add(tShirt8); sortedTShirtsAsc.add(tShirt7); sortedTShirtsDesc.add(tShirt7); sortedTShirtsDesc.add(tShirt8); sortedTShirtsDesc.add(tShirt4); sortedTShirtsDesc.add(tShirt3); sortedTShirtsDesc.add(tShirt2); sortedTShirtsDesc.add(tShirt1); sortedTShirtsDesc.add(tShirt6); } @Test public void BubbleSortTestBySizeColorFabricAsc() { bubbleSort.sort(tShirts, bySizeColorFabricAsc); Assert.assertArrayEquals(sortedTShirtsAsc.toArray(), tShirts.toArray()); } @Test public void BubbleSortTestBySizeColorFabricDesc() { bubbleSort.sort(tShirts, bySizeColorFabricDesc); List<TShirt> sortedTShirts = new ArrayList<>(); sortedTShirts.add(tShirt2); sortedTShirts.add(tShirt4); sortedTShirts.add(tShirt3); sortedTShirts.add(tShirt1); sortedTShirts.add(tShirt5); Assert.assertArrayEquals(sortedTShirtsDesc.toArray(), tShirts.toArray()); } @Test public void BucketSortTestBySizeColorFabricAsc() { bucketSort.sort(tShirts, bySizeColorFabricAsc); Assert.assertArrayEquals(sortedTShirtsAsc.toArray(), tShirts.toArray()); } @Test public void BucketSortTestBySizeColorFabricDesc() { bucketSort.sort(tShirts, bySizeColorFabricDesc); Assert.assertArrayEquals(sortedTShirtsDesc.toArray(), tShirts.toArray()); } @Test public void QuickSortTestBySizeColorFabricAsc() { quickSort.sort(tShirts, bySizeColorFabricAsc); Assert.assertArrayEquals(sortedTShirtsAsc.toArray(), tShirts.toArray()); } @Test public void QuickSortTestBySizeColorFabricDesc() { quickSort.sort(tShirts, bySizeColorFabricDesc); Assert.assertArrayEquals(sortedTShirtsDesc.toArray(), tShirts.toArray()); } }
true
73316a01db2a1feb8d98b01b4d200382c76a5a6a
Java
TomasBasile/Spring
/springDemo/src/main/java/com/example/springDemo/controller/BlogController.java
UTF-8
1,915
2.234375
2
[]
no_license
package com.example.springDemo.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.example.springDemo.model.Blog; import com.example.springDemo.service.BlogService; @RestController public class BlogController { @Autowired private BlogService blogService; @RequestMapping(value="/blog", method=RequestMethod.GET) public ResponseEntity<List<Blog>> consulta(){ return new ResponseEntity<List<Blog>>(blogService.consulta(), HttpStatus.OK); } @RequestMapping(value="/blog/{id}", method=RequestMethod.GET) public ResponseEntity<Blog> consultaPorId(@PathVariable("id") int id){ return new ResponseEntity<Blog>(blogService.consultaPorId(id), HttpStatus.OK); } @RequestMapping(value="/blog", method=RequestMethod.POST) public ResponseEntity<Blog> registro(@RequestBody Blog blog){ return new ResponseEntity<Blog>(blogService.registro(blog), HttpStatus.OK); } @RequestMapping(value="/blog/{id}", method=RequestMethod.PUT) public ResponseEntity<Blog> actualizar(@RequestBody Blog blog){ return new ResponseEntity<Blog>(blogService.registro(blog), HttpStatus.OK); } @RequestMapping(value="/blog/{id}", method=RequestMethod.DELETE) public ResponseEntity<String> eliminarBlog(@PathVariable("id") int id){ Blog blog=blogService.consultaPorId(id); blogService.eliminarBlog(blog); return new ResponseEntity<String>("Blog Eliminado", HttpStatus.OK); } }
true
f59f2adc86b0f0c94abb0a3f069625ff6ca2e576
Java
tinyplan/SuperMarket-MS
/src/main/java/com/software/demo/entity/ApiResult.java
UTF-8
1,056
2.71875
3
[]
no_license
package com.software.demo.entity; /** * 统一请求返回体 * * @param <T> 数据体类型 */ public class ApiResult<T> { protected int code; protected String message; protected T data; protected ApiResult(int code, String message, T data) { this.code = code; this.message = message; this.data = data; } public ApiResult(ResultStatus resultStatus, T data) { this(resultStatus.getCode(), resultStatus.getMessage(), data); } /** * 覆盖原始信息 * * @param resultStatus 消息状态 * @param message 自定义消息 * @param data 返回信息 */ public ApiResult(ResultStatus resultStatus, String message, T data) { this(resultStatus.getCode(), message, data); } public int getCode() { return code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public T getData() { return data; } }
true
e0516ab9d76800d24353ccf6730855d06069168b
Java
a24otorandell/ProjectAutotest
/src/main/java/screen/AT2ACCDI0028/AT2ACCDI0028Locators.java
UTF-8
59,248
1.921875
2
[]
no_license
package screen.AT2ACCDI0028; import java.util.HashMap; import java.util.Map; /** * Created by vsolis on 29/11/2016. */ public class AT2ACCDI0028Locators { Map<String, String> elements = new HashMap<>(); public AT2ACCDI0028Locators (String enviroment){ setElements(); } public Map<String, String> getElements (){ return elements; } public void setElements (){ //ADD elements.put("category_b_add", "//*[contains(@id, 'pc1:pcgt1:boton_add')]"); elements.put("category_sl_reason", "//*[contains(@id, 'pc1:pcgt1:soc1::content')]"); elements.put("category_i_add_start_date", "//*[contains(@id, 'pc1:pcgt1:id3::content')]"); elements.put("category_lov_add_ttoo", "//*[contains(@id, 'pc1:pcgt1:seqTtooId::lovIconId')]"); elements.put("category_i_add_ttoo", "//*[contains(@id, 'pc1:pcgt1:seqTtooId::content')]"); elements.put("category_e_add_ttoo_description", "//*[contains(@id, 'pc1:pcgt1:it3::content')]"); elements.put("category_lov_add_category", "//*[contains(@id, 'pc1:pcgt1:codCategoriaId::lovIconId')]"); elements.put("category_i_add_category_description", "//*[contains(@id, 'pc1:pcgt1:it2::content')]"); elements.put("category_i_add_category", "//*[contains(@id, 'pc1:pcgt1:codCategoriaId::content')]"); elements.put("category_i_add_category_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("category_lov_add_hotel_type", "//*[contains(@id, 'pc1:pcgt1:codTipoEstabId::lovIconId')]"); elements.put("category_i_add_hotel_type", "//*[contains(@id, 'pc1:pcgt1:codTipoEstabId::content')]"); elements.put("category_i_add_hotel_type_description", "//*[contains(@id, 'pc1:pcgt1:it4::content')]"); elements.put("category_cb_add_active", "//*[contains(@id, 'pc1:pcgt1:sbc2::content')]"); elements.put("category_b_add_save", "//*[contains(@id, 'pc1:pcgt1:btn_commitExit')]"); //SEARCH elements.put("category_b_search", "//*[contains(@id, 'qryId1::search')]"); elements.put("category_e_result", "//*[contains(@id, 'pc1:t1::db')]/table/tbody/tr[1]/td[1]"); elements.put("category_n_records", "//*[contains(@id, 'pc1:ot13')]"); elements.put("category_b_reset", "//*[contains(@id, 'qryId1::reset')]"); elements.put("category_i_search_reason", "//*[contains(@id, 'qryId1:value00::content')]"); elements.put("category_i_search_start_date", "//*[contains(@id, 'qryId1:value10::content')]"); elements.put("category_i_search_desactivation_date", "//*[contains(@id, 'qryId1:value20::content')]"); elements.put("category_lov_search_ttoo", "//*[contains(@id, 'qryId1:value30::lovIconId')]"); elements.put("category_i_search_ttoo", "//*[contains(@id, 'qryId1:value30::content')]"); elements.put("category_i_search_ttoo_description", "//*[contains(@id, 'qryId1:value40::content')]"); elements.put("category_lov_search_category", "//*[contains(@id, 'qryId1:value50::lovIconId')]"); elements.put("category_i_search_category", "//*[contains(@id, 'qryId1:value50::content')]"); elements.put("category_i_search_category_description", "//*[contains(@id, 'qryId1:value60::content')]"); elements.put("category_lov_search_hotel_type", "//*[contains(@id, 'qryId1:value70::lovIconId')]"); elements.put("category_i_search_hotel_type", "//*[contains(@id, 'qryId1:value70::content')]"); elements.put("category_i_search_hotel_type_description", "//*[contains(@id, 'qryId1:value80::content')]"); //EDIT elements.put("category_b_edit", "//*[contains(@id, 'pc1:pcgt1:boton_edit')]"); elements.put("category_i_edit_reason", "//*[contains(@id, 'pc1:pcgt1:soc1::content')]"); elements.put("category_i_edit_start_date", "//*[contains(@id, 'pc1:pcgt1:id3::content')]"); elements.put("category_lov_edit_ttoo", "//*[contains(@id, 'pc1:pcgt1:seqTtooId::lovIconId')]"); elements.put("category_i_edit_ttoo", "//*[contains(@id, 'pc1:pcgt1:seqTtooId::content')]"); elements.put("category_i_edit_ttoo_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("category_lov_edit_category", "//*[contains(@id, 'pc1:pcgt1:codCategoriaId::lovIconId')]"); elements.put("category_i_edit_category", "//*[contains(@id, 'pc1:pcgt1:codCategoriaId::content')]"); elements.put("category_i_edit_category_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("category_lov_edit_hotel_type", "//*[contains(@id, 'pc1:pcgt1:codTipoEstabId::lovIconId')]"); elements.put("category_i_edit_hotel_type", "//*[contains(@id, 'pc1:pcgt1:codTipoEstabId::content')]"); elements.put("category_i_edit_hotel_type_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("category_cb_edit_active", "//*[contains(@id, 'pc1:pcgt1:sbc2::content')]"); elements.put("category_b_edit_save", "//*[contains(@id, 'pc1:pcgt1:btn_commitExit')]"); elements.put("category_inactive_b_ok", "//*[contains(@id, 'd3::ok')]"); elements.put("category_i_desactivation_date", "//*[contains(@id, 'pc1:pcgt1:id4::content')]"); //DETACH elements.put("category_b_detach", "//*[contains(@id, 'pc1:_dchTbr')]"); //AUDITDATA elements.put("category_b_action", "//*[contains(@id, 'pc1:pcgm1:dc_m1')]"); elements.put("category_b_audit", "//*[contains(@id, 'pc1:pcgm1:dc_cmi0')]/td[2]"); elements.put("category_b_audit_b_ok", "//*[contains(@id, 'pc1:pcgm1:d22::ok')]"); //QBE elements.put("category_b_qbe", "//*[contains(@id, 'pc1:_qbeTbr')]"); elements.put("category_b_qbe_reset", "//*[contains(@id, 'pc1:t1::ch::t')]/tbody/tr[2]/th/a"); elements.put("category_i_qbe_reason", "//*[contains(@id, 'pc1:t1:soc10::content')]"); elements.put("category_i_qbe_start_date", "//*[contains(@id, 'pc1:t1:id6::content')]"); elements.put("category_sel_qbe_active", "//*[contains(@id, 'pc1:t1:soc12::content')]"); elements.put("category_i_qbe_ttoo", "//*[contains(@id, 'pc1_afr_t1_afr_c3::content')]"); elements.put("category_i_qbe_category", "//*[contains(@id, 'pc1_afr_t1_afr_c5::content')]"); elements.put("category_i_qbe_hotel_type", "//*[contains(@id, 'pc1_afr_t1_afr_c2::content')]"); elements.put("category_i_qbe_desactivation_date", "//*[contains(@id, 'pc1:t1:id5::content')]"); //DELETE elements.put("category_b_delete", "//*[contains(@id, 'pc1:pcgt1:boton_remove')]"); elements.put("category_b_delete_b_ok", "//*[contains(@id, 'pc1:pcgt1:cbt1')]"); ///////////////////////////////////////////// BINDING TAB ///////////////////////////////////////////////////// elements.put("binding_tab", "//*[contains(@id, 'sdi1::disAcr')]"); elements.put("binding_b_menu", "//*[contains(@id, 'pc1:pcgt2:dc_t1::eoi')]"); //ADD elements.put("binding_b_add", "//*[contains(@id, 'pc1:pcgt2:boton_add')]"); elements.put("binding_add_e_sequence", "//*[contains(@id, 'pc1:pcgt2:it15::content')]"); elements.put("binding_i_add_reason", "//*[contains(@id, 'pc1:pcgt2:soc2::content')]"); elements.put("binding_i_add_start_date", "//*[contains(@id, 'pc1:pcgt2:id3::content')]"); elements.put("binding_i_add_ttoo", "//*[contains(@id, 'pc1:pcgt2:seqTtooId::content')]"); elements.put("binding_lov_add_ttoo", "//*[contains(@id, 'pc1:pcgt2:seqTtooId::lovIconId')]"); elements.put("binding_i_add_ttoo_description", "//*[contains(@id, 'pc1:pcgt2:sbc3::content')]"); elements.put("binding_cb_add_main", "//*[contains(@id, 'pc1:pcgt2:sbc3::content')]"); elements.put("binding_cb_add_active", "//*[contains(@id, 'pc1:pcgt2:sbc4::content')]"); elements.put("binding_i_add_market", "//*[contains(@id, 'pc1:pcgt2:codPaisId::content')]"); elements.put("binding_lov_add_market", "//*[contains(@id, 'pc1:pcgt2:codPaisId::lovIconId')]"); elements.put("binding_i_add_market_description", "//*[contains(@id, 'pc1:pcgt2:it8')]"); elements.put("binding_i_add_hotel", "//*[contains(@id, 'pc1:pcgt2:seqHotelId::content')]"); elements.put("binding_lov_add_hotel", "//*[contains(@id, 'pc1:pcgt2:seqHotelId::lovIconId')]"); elements.put("binding_i_add_hotel_description", "//*[contains(@id, 'pc1:pcgt2:it12::content')]"); elements.put("binding_i_add_chain", "//*[contains(@id, 'pcgt2:codCadenaId::content')]"); elements.put("binding_lov_add_chain", "//*[contains(@id, 'pc1:pcgt2:codCadenaId::lovIconId')]"); elements.put("binding_i_add_des_cadena", "//*[contains(@id, 'pc1:pcgt2:it7::content')]"); elements.put("binding_i_add_destination", "//*[contains(@id, 'pc1:pcgt2:codDestinoId::content')]"); elements.put("binding_lov_add_destination", "//*[contains(@id, 'pc1:pcgt2:codDestinoId::lovIconId')]"); elements.put("binding_i_add_destination_description", "//*[contains(@id, 'pc1:pcgt2:it10::content')]"); elements.put("binding_i_add_country", "//*[contains(@id, 'pc1:pcgt2:codPaisDestinoId::content')]"); elements.put("binding_lov_add_country", "//*[contains(@id, 'pc1:pcgt2:codPaisDestinoId::lovIconId')]"); elements.put("binding_i_add_country_description", "//*[contains(@id, 'pc1:pcgt2:it13::content')]"); elements.put("binding_b_add_save", "//*[contains(@id, 'pcgt2:btn_commitExit')]"); //SEARCH elements.put("binding_b_search", "//*[contains(@id, 'qryId1::search')]"); elements.put("binding_b_reset", "//*[contains(@id, 'qryId1::reset')]"); elements.put("binding_n_records", "//*[contains(@id, 'r1:0:pc1:exBindCount')]"); elements.put("binding_e_result", "//*[contains(@id, 'pc1:exBind::db')]/table/tbody/tr[1]/td[1]"); elements.put("binding_i_search_sequence", "//*[contains(@id, 'qryId1:value00::content')]"); elements.put("binding_i_search_reason", "//*[contains(@id, 'qryId1:value10::content')]"); elements.put("binding_i_search_start_date", "//*[contains(@id, 'qryId1:value30::content')]"); elements.put("binding_cb_main", "//*[contains(@id, 'qryId1:value50::content')]"); elements.put("binding_lov_search_ttoo", "//*[contains(@id, 'qryId1:value60::lovIconId')]"); elements.put("binding_i_search_ttoo", "//*[contains(@id, 'qryId1:value60::content')]"); elements.put("binding_i_search_ttoo_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("binding_lov_search_market", "//*[contains(@id, 'qryId1:value80::lovIconId')]"); elements.put("binding_i_search_market", "//*[contains(@id, 'qryId1:value80::content')]"); elements.put("binding_i_search_market_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("binding_lov_search_hotel", "//*[contains(@id, 'qryId1:value100::lovIconId')]"); elements.put("binding_i_search_hotel", "//*[contains(@id, 'qryId1:value100::content')]"); elements.put("binding_i_search_hotel_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("binding_i_search_chain", "//*[contains(@id, 'qryId1:value120::content')]"); elements.put("binding_lov_search_chain", "//*[contains(@id, 'qryId1:value120::lovIconId')]"); elements.put("binding_i_search_chain_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("binding_lov_search_destination", "//*[contains(@id, 'qryId1:value140::lovIconId')]"); elements.put("binding_i_search_destination", "//*[contains(@id, 'qryId1:value140::content')]"); elements.put("binding_i_search_destination_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("binding_lov_search_country", "//*[contains(@id, 'qryId1:value160::lovIconId')]"); elements.put("binding_i_search_country", "//*[contains(@id, 'qryId1:value160::content')]"); elements.put("binding_i_search_country_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); //EDIT elements.put("binding_b_edit", "//*[contains(@id, 'pc1:pcgt2:boton_edit')]"); //QBE elements.put("binding_b_qbe", "//*[contains(@id, 'pc1:_qbeTbr')]"); elements.put("binding_i_qbe_reason", "//*[contains(@id, 'pc1:exBind:socid0::content')]"); elements.put("binding_i_qbe_start_date", "//*[contains(@id, 'pc1:exBind:id2::content')]"); elements.put("binding_i_qbe_ttoo", "//*[contains(@id, 'pc1_afr_exBind_afr_c13::content')]"); elements.put("binding_i_qbe_market", "//*[contains(@id, 'pc1_afr_exBind_afr_c9::content')]"); elements.put("binding_i_qbe_hotel", "//*[contains(@id, 'pc1_afr_exBind_afr_c2::content')]"); elements.put("binding_i_qbe_chain", "//*[contains(@id, 'pc1_afr_exBind_afr_c14::content')]"); elements.put("binding_i_qbe_destination", "//*[contains(@id, 'pc1_afr_exBind_afr_c8::content')]"); elements.put("binding_i_qbe_country", "//*[contains(@id, 'pc1_afr_exBind_afr_c12::content')]"); //AUDITDATA elements.put("binding_b_actions", "//*[contains(@id, 'pc1:pcgm1:dc_m1')]"); elements.put("binding_b_audit", "//*[contains(@id, 'pc1:pcgm1:dc_cmi0')]/td[2]"); //DETACH elements.put("binding_b_detach", "//*[contains(@id, 'pc1:_dchTbr')]"); ///////////////////////////////////////////// GENERALS TAB ///////////////////////////////////////////////////// elements.put("generals_tab", "//*[contains(@id, 'sdi2::disAcr')]"); elements.put("generals_b_reset", "//*[contains(@id, 'qryId1::reset')]"); elements.put("generals_e_sequence", "//*[contains(@id, 'pc1:exGeneral::db')]/table/tbody/tr[1]/td[2]/div/table/tbody/tr/td[1]"); //SEARCH elements.put("generals_b_search", "//*[contains(@id, 'qryId1::search')]"); elements.put("generals_i_search_reason", "//*[contains(@id, 'qryId1:value10::content')]"); elements.put("generals_i_search_sequence", "//*[contains(@id, 'qryId1:value00::content')]"); elements.put("generals_i_search_ie", "//*[contains(@id, 'qryId1:value20::content')]"); elements.put("generals_i_search_start_date", "//*[contains(@id, 'qryId1:value30::content')]"); elements.put("generals_i_search_ttoo", "//*[contains(@id, 'qryId1:value60::content')]"); elements.put("generals_lov_search_ttoo", "//*[contains(@id, 'qryId1:value60::lovIconId')]"); elements.put("generals_i_search_ttoo_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("generals_cb_search_b2b", "//*[contains(@id, 'qryId1:value80::content')]"); elements.put("generals_cb_search_main_acount", "//*[contains(@id, 'qryId1:value50::content')]"); elements.put("generals_i_search_classification", "//*[contains(@id, 'qryId1:value90::content')]"); elements.put("generals_lov_search_classification", "//*[contains(@id, 'qryId1:value90::lovIconId')]"); elements.put("generals_i_search_classification_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("generals_i_search_hotel", "//*[contains(@id, 'qryId1:value110::content')]"); elements.put("generals_lov_search_hotel", "//*[contains(@id, 'qryId1:value110::lovIconId')]"); elements.put("generals_i_search_hotel_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("generals_i_search_chain", "//*[contains(@id, 'qryId1:value130::content')]"); elements.put("generals_lov_search_chain", "//*[contains(@id, 'qryId1:value130::lovIconId')]"); elements.put("generals_i_search_chain_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("generals_i_search_destination", "//*[contains(@id, 'qryId1:value150::content')]"); elements.put("generals_lov_search_destination", "//*[contains(@id, 'qryId1:value150::lovIconId')]"); elements.put("generals_i_search_destination_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("generals_i_search_market", "//*[contains(@id, 'qryId1:value170::content')]"); elements.put("generals_lov_search_market", "//*[contains(@id, 'qryId1:value170::lovIconId')]"); elements.put("generals_i_search_market_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("generals_i_search_country", "//*[contains(@id, 'qryId1:value190::content')]"); elements.put("generals_lov_search_country", "//*[contains(@id, 'qryId1:value190::lovIconId')]"); elements.put("generals_i_search_country_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("generals_i_search_application", "//*[contains(@id, 'qryId1:value210::content')]"); elements.put("generals_n_records", "//*[contains(@id, 'r6:0:pc1:exGeneralCount')]"); elements.put("generals_e_result", "//*[contains(@id, 'pc1:exGeneral::db')]/table/tbody/tr[1]/td[1]"); //EDIT elements.put("generals_b_edit", "//*[contains(@id, 'pc1:pcgt2:boton_edit')]"); //ADD elements.put("generals_b_add", "//*[contains(@id, 'pc1:pcgt2:boton_add')]"); elements.put("generals_e_secuence", "//*[contains(@id, 'pcgt2:it17::content')]"); elements.put("generals_i_add_reason", "//*[contains(@id, 'pc1:pcgt2:soc8::content')]"); elements.put("generals_sl_add_ie", "//*[contains(@id, 'pc1:pcgt2:soc5::content')]"); elements.put("generals_i_add_start_date", "//*[contains(@id, 'pc1:pcgt2:id2::content')]"); elements.put("generals_i_add_ttoo", "//*[contains(@id, 'pc1:pcgt2:seqTtooId::content')]"); elements.put("generals_lov_add_ttoo", "//*[contains(@id, 'pc1:pcgt2:seqTtooId::lovIconId')]"); elements.put("generals_e_add_ttoo_descriptión", "//*[contains(@id, 'pc1:pcgt2:it15::content')]"); elements.put("generals_i_add_classification", "//*[contains(@id, 'pc1:pcgt2:codClasifId::content')]"); elements.put("generals_lov_add_classification", "//*[contains(@id, 'pc1:pcgt2:codClasifId::lovIconId')]"); elements.put("generals_e_add_classification_description", "//*[contains(@id, 'pc1:pcgt2:it6::content')]"); elements.put("generals_i_add_hotel", "//*[contains(@id, 'pc1:pcgt2:seqHotelId::content')]"); elements.put("generals_lov_add_hotel", "//*[contains(@id, 'pc1:pcgt2:seqHotelId::lovIconId')]"); elements.put("generals_e_add_hotel_description", "//*[contains(@id, 'pc1:pcgt2:it5::content')]"); elements.put("generals_i_add_chain", "//*[contains(@id, 'pc1:pcgt2:codCadenaId::content')]"); elements.put("generals_lov_add_chain", "//*[contains(@id, 'pc1:pcgt2:codCadenaId::lovIconId')]"); elements.put("generals_lov_add_chain_description", "//*[contains(@id, 'pc1:pcgt2:it14::content')]"); elements.put("generals_i_add_destination", "//*[contains(@id, 'pc1:pcgt2:codDestinoId::content')]"); elements.put("generals_lov_add_destination", "//*[contains(@id, 'pc1:pcgt2:codDestinoId::lovIconId')]"); elements.put("generals_e_add_destination_description", "//*[contains(@id, 'pc1:pcgt2:it11::content')]"); elements.put("generals_i_add_market", "//*[contains(@id, 'pc1:pcgt2:codPaisId::content')]"); elements.put("generals_lov_add_market", "//*[contains(@id, 'pc1:pcgt2:codPaisId::lovIconId')]"); elements.put("generals_e_add_market_description", "//*[contains(@id, 'pc1:pcgt2:it13::content')]"); elements.put("generals_i_add_country", "//*[contains(@id, 'pc1:pcgt2:codPaisDestinoId::content')]"); elements.put("generals_lov_add_country", "//*[contains(@id, 'pc1:pcgt2:codPaisDestinoId::lovIconId')]"); elements.put("generals_e_add_country_description", "//*[contains(@id, 'pc1:pcgt2:it16::content')]"); elements.put("generals_b_add_save", "//*[contains(@id, 'pc1:pcgt2:btn_commitExit')]"); elements.put("generals_sl_aplication", "//*[contains(@id, 'pc1:pcgt2:soc4::content')]"); elements.put("generals_cb_add_b2b", "//*[contains(@id, 'pc1:pcgt2:sbc4::content')]"); elements.put("generals_cb_add_main_acount", "//*[contains(@id, 'pc1:pcgt2:sbc7::content')]"); elements.put("generals_i_add_active", "//*[contains(@id, 'pc1:pcgt2:sbc6::content')]"); elements.put("generals_lov_add_active_yes", "//*[contains(@id, 'pc1:d2::yes')]"); //QBE elements.put("generals_b_qbe", "//*[contains(@id, 'pc1:_qbeTbr')]"); elements.put("generals_i_qbe_sequence", "//*[contains(@id, 'pc1_afr_exGeneral_afr_resId1c1::content')]"); elements.put("generals_i_qbe_reason", "//*[contains(@id, 'pc1:exGeneral:socid0::content')]"); elements.put("generals_i_qbe_ie", "//*[contains(@id, 'pc1:exGeneral:soc6::content')]"); elements.put("generals_i_qbe_start_date", "//*[contains(@id, 'pc1:exGeneral:id5::content')]"); elements.put("generals_i_qbe_active", "//*[contains(@id, 'pc1:exGeneral:soc7::content')]"); elements.put("generals_i_qbe_ttoo", "//*[contains(@id, '_pc1_afr_exGeneral_afr_resId1c8::content')]"); elements.put("generals_i_qbe_main_acount", "//*[contains(@id, 'pc1:exGeneral:soc1::content')]"); elements.put("generals_i_qbe_classification", "//*[contains(@id, '_pc1_afr_exGeneral_afr_resId1c11::content')]"); elements.put("generals_i_qbe_exclude_b2b", "//*[contains(@id, 'pc1:exGeneral:soc9::content')]"); elements.put("generals_i_qbe_hotel", "//*[contains(@id, '_pc1_afr_exGeneral_afr_resId1c13::content')]"); elements.put("generals_i_qbe_chain", "//*[contains(@id, '_pc1_afr_exGeneral_afr_resId1c15::content')]"); elements.put("generals_i_qbe_destination", "//*[contains(@id, '_pc1_afr_exGeneral_afr_resId1c16::content')]"); elements.put("generals_i_qbe_market", "//*[contains(@id, '_pc1_afr_exGeneral_afr_resId1c17::content')]"); elements.put("generals_i_qbe_country", "//*[contains(@id, '_pc1_afr_exGeneral_afr_resId1c18::content')]"); elements.put("generals_i_qbe_application", "//*[contains(@id, 'pc1:exGeneral:soc10::content')]"); //AUDIT elements.put("generals_b_actions", "//*[contains(@id, 'pc1:pcgm1:dc_m1')]"); elements.put("generals_b_audit", "//*[contains(@id, 'pc1:pcgm1:dc_cmi0')]/td[2]"); elements.put("generals_b_ok", "//*[contains(@id, 'd22::ok')]"); //DETACH elements.put("generals_b_detach", "//*[contains(@id, 'pc1:_dchTbr')]"); // ACTIONS COPY EXCLUSIONS elements.put("generals_b_copy_exclusions", "//*[contains(@id, 'pc1:pcgm1:dc_cmi1')]/td[2]"); elements.put("generals_copy_exclusions_tour_operators_b_qbe", "//*[contains(@id, 'pc1:r1:0:pc1:_qbeTbr')]/a"); elements.put("generals_copy_exclusions_tour_operators_qbe_i_to", "//*[contains(@id, 'pc1_afr_ttoTab_afr_c2::content')]"); elements.put("generals_copy_exclusions_tour_operators_qbe_i_to_name", "//*[contains(@id, 'pc1_afr_ttoTab_afr_c1::content')]"); elements.put("generals_copy_exclusions_tour_operators_qbe_e_to", "//*[contains(@id, 'pc1:ttoTab::db')]/table/tbody/tr[1]/td[2]/div/table/tbody/tr/td[1]"); elements.put("generals_copy_exclusions_tour_operators_qbe_e_to_name", "//*[contains(@id, 'pc1:ttoTab::db')]/table/tbody/tr[1]/td[2]/div/table/tbody/tr/td[2]"); elements.put("generals_copy_exclusions_hotel_name_b_qbe", "//*[contains(@id, 'pc1:r1:0:pc1:_qbeTbr')]/a"); elements.put("generals_copy_exclusions_hotel_name_qbe_i_hotel", "//*[contains(@id, 'pc2_afr_hotTab_afr_c5::content')]"); elements.put("generals_copy_exclusions_hotel_name_qbe_i_hotel_name", "//*[contains(@id, 'pc2_afr_hotTab_afr_c4::content')]"); elements.put("generals_copy_exclusions_hotel_name_qbe_e_hotel", "//*[contains(@id, 'pc2:ttoTab::db')]/table/tbody/tr[1]/td[2]/div/table/tbody/tr/td[1]"); elements.put("generals_copy_exclusions_hotel_name_qbe_e_hotel_name", "//*[contains(@id, 'pc2:ttoTab::db')]/table/tbody/tr[1]/td[2]/div/table/tbody/tr/td[2]"); elements.put("generals_copy_exclusions_e_result", "//*[contains(@id, 'pc1:ttoTab::db')]/table/tbody/tr[1]/td[1]"); elements.put("generals_copy_exclusions_e_result", "//*[contains(@id, 'pc2:ttoTab::db')]/table/tbody/tr[1]/td[1]"); elements.put("generals_copy_exclusions_e_detach_tour_operators", "//*[contains(@id, 'pc1:_dchTbr')]/a"); elements.put("generals_copy_exclusions_e_detach_hotels", "//*[contains(@id, 'pc2:_dchTbr')]/a"); elements.put("generals_copy_exclusions_b_copy", "//*[contains(@id, 'pc1:r1:0:cb1')]"); ///////////////////////////////////////////// ATLAS TAB ///////////////////////////////////////////////////// elements.put("atlas_tab", "//*[contains(@id, 'sdi3::disAcr')]"); elements.put("atlas_b_reset", "//*[contains(@id, 'qryId1::reset')]"); //ADD elements.put("atlas_b_add", "//*[contains(@id, 'pc1:pcgt2:boton_add')]"); elements.put("atlas_i_add_reasons", "//*[contains(@id, 'pc1:pcgt2:soc2::content')]"); elements.put("atlas_i_add_sequence", "//*[contains(@id, 'pc1:pcgt2:it4::content')]"); elements.put("atlas_sl_add_ie", "//*[contains(@id, 'pc1:pcgt2:soc3::content')]"); elements.put("atlas_i_add_start_date", "//*[contains(@id, 'pc1:pcgt2:id3::content')]"); elements.put("atlas_i_add_ttoo", "//*[contains(@id, 'pc1:pcgt2:seqTtooId::content')]"); elements.put("atlas_lov_add_ttoo", "//*[contains(@id, 'pc1:pcgt2:seqTtooId::lovIconId')]"); elements.put("atlas_e_add_ttoo_description", "//*[contains(@id, 'pc1:pcgt2:it1::content')]"); elements.put("atlas_cb_add_b2b", "//*[contains(@id, 'pc1:pcgt2:sbc2::content')]"); elements.put("atlas_cb_add_main_acount", "//*[contains(@id, 'pc1:pcgt2:sbc1::content')]"); elements.put("atlas_i_add_classification", "//*[contains(@id, 'pc1:pcgt2:codClasifId::content')]"); elements.put("atlas_lov_add_classification", "//*[contains(@id, 'pc1:pcgt2:codClasifId::lovIconId')]"); elements.put("atlas_e_add_classification_description", "//*[contains(@id, 'pc1:pcgt2:it2::content')]"); elements.put("atlas_i_add_receptive", "//*[contains(@id, 'pc1:pcgt2:seqRecId::content')]"); elements.put("atlas_lov_add_receptive", "//*[contains(@id, 'pc1:pcgt2:seqRecId::lovIconId')]"); elements.put("atlas_i_add_contract", "//*[contains(@id, 'pc1:pcgt2:seqContrId::content')]"); elements.put("atlas_lov_add_contract", "//*[contains(@id, 'pc1:pcgt2:seqContrId::lovIconId')]"); elements.put("atlas_i_add_hotel", "//*[contains(@id, 'pc1:pcgt2:seqHotelId::content')]"); elements.put("atlas_lov_add_hotel", "//*[contains(@id, 'pc1:pcgt2:seqHotelId::lovIconId')]"); elements.put("atlas_e_add_hotel_description", "//*[contains(@id, 'pc1:pcgt2:it12::content')]"); elements.put("atlas_i_add_chain", "//*[contains(@id, 'pc1:pcgt2:codCadenaId::content')]"); elements.put("atlas_lov_add_chain", "//*[contains(@id, 'pc1:pcgt2:codCadenaId::lovIconId')]"); elements.put("atlas_e_add_chain_description", "//*[contains(@id, 'pc1:pcgt2:it7::content')]"); elements.put("atlas_i_add_destination", "//*[contains(@id, 'pc1:pcgt2:codDestinoId::content')]"); elements.put("atlas_lov_add_destination", "//*[contains(@id, 'pc1:pcgt2:codDestinoId::lovIconId')]"); elements.put("atlas_e_add_destination_description", "//*[contains(@id, 'pc1:pcgt2:it3::content')]"); elements.put("atlas_i_add_market", "//*[contains(@id, 'pc1:pcgt2:codPaisId::content')]"); elements.put("atlas_lov_add_market", "//*[contains(@id, 'pc1:pcgt2:codPaisId::lovIconId')]"); elements.put("atlas_e_add_market_description", "//*[contains(@id, 'pc1:pcgt2:it10::content')]"); elements.put("atlas_i_add_country", "//*[contains(@id, 'pc1:pcgt2:codPaisDestinoId::content')]"); elements.put("atlas_lov_add_country", "//*[contains(@id, 'pc1:pcgt2:codPaisDestinoId::lovIconId')]"); elements.put("atlas_lov_add_country_description", "//*[contains(@id, 'pc1:pcgt2:it8::content')]"); elements.put("atlas_i_add_application", "//*[contains(@id, 'pc1:pcgt2:soc1::content')]"); elements.put("atlas_b_add_save", "//*[contains(@id, 'pc1:pcgt2:btn_commitExit')]"); //SEARCH elements.put("atlas_b_search", "//*[contains(@id, 'qryId1::search')]"); elements.put("atlas_n_records", "//*[contains(@id, 'r5:0:pc1:exAtlasTbCount')]"); elements.put("atlas_e_result", "//*[contains(@id, 'pc1:exAtlasTb::db')]/table/tbody/tr[1]/td[1]"); elements.put("atlas_i_search_reasons", "//*[contains(@id, 'qryId1:value10::content')]"); elements.put("atlas_i_search_ie", "//*[contains(@id, 'qryId1:value20::content')]"); elements.put("atlas_i_search_start_date", "//*[contains(@id, 'qryId1:value30::content')]"); elements.put("atlas_i_search_ttoo", "//*[contains(@id, 'qryId1:value60::content')]"); elements.put("atlas_lov_search_ttoo", "//*[contains(@id, 'qryId1:value60::lovIconId')]"); elements.put("atlas_i_search_ttoo_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("atlas_cb_search_b2b", "//*[contains(@id, 'qryId1:value80::content')]"); elements.put("atlas_cb_search_main_acount", "//*[contains(@id, 'qryId1:value50::content')]"); elements.put("atlas_i_search_classification", "//*[contains(@id, 'qryId1:value90::content')]"); elements.put("atlas_lov_search_classification", "//*[contains(@id, 'qryId1:value90::lovIconId')]"); elements.put("atlas_i_search_classification_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("atlas_i_search_receptive", "//*[contains(@id, 'qryId1:value110::content')]"); elements.put("atlas_lov_search_receptive", "//*[contains(@id, 'qryId1:value110::lovIconId')]"); elements.put("atlas_i_search_receptive_code", "//*[contains(@id, '_afrLovInternalQueryId:value30::content')]"); elements.put("atlas_i_search_contract", "//*[contains(@id, 'qryId1:value120::content')]"); elements.put("atlas_lov_search_contract", "//*[contains(@id, 'qryId1:value120::lovIconId')]"); elements.put("atlas_i_search_contract_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("atlas_i_search_hotel", "//*[contains(@id, 'qryId1:value140::content')]"); elements.put("atlas_lov_search_hotel", "//*[contains(@id, 'qryId1:value140::lovIconId')]"); elements.put("atlas_i_search_hotel_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("atlas_i_search_chain", "//*[contains(@id, 'qryId1:value160::content')]"); elements.put("atlas_lov_search_chain", "//*[contains(@id, 'qryId1:value160::lovIconId')]"); elements.put("atlas_i_search_chain_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("atlas_i_search_destination", "//*[contains(@id, 'qryId1:value180::content')]"); elements.put("atlas_lov_search_destination", "//*[contains(@id, 'qryId1:value180::lovIconId')]"); elements.put("atlas_i_search_destination_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("atlas_i_search_market", "//*[contains(@id, 'qryId1:value200::content')]"); elements.put("atlas_lov_search_market", "//*[contains(@id, 'qryId1:value200::lovIconId')]"); elements.put("atlas_i_search_market_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("atlas_i_search_country", "//*[contains(@id, 'qryId1:value220::content')]"); elements.put("atlas_lov_search_country", "//*[contains(@id, 'qryId1:value220::lovIconId')]"); elements.put("atlas_i_search_country_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("atlas_i_search_application", "//*[contains(@id, 'qryId1:value240::content')]"); elements.put("atlas_e_search_sequence", "//*[contains(@id, 'pc1:exAtlasTb::db')]/table/tbody/tr[1]/td[2]/div/table/tbody/tr/td[1]"); elements.put("atlas_i_search_sequence", "//*[contains(@id, 'qryId1:value00::content')]"); //EDIT elements.put("atlas_b_edit", "//*[contains(@id, 'pc1:pcgt2:boton_edit')]"); //QBE elements.put("atlas_b_qbe", "//*[contains(@id, 'pc1:_qbeTbr')]"); elements.put("atlas_i_qbe_reason", "//*[contains(@id, 'pc1_afr_exAtlasTb_afr_resId1c1::content')]"); elements.put("atlas_i_qbe_sequence", "//*[contains(@id, 'pc1:exAtlasTb:socid0::content')]"); elements.put("atlas_i_qbe_ie", "//*[contains(@id, 'pc1:exAtlasTb:socid0::content')]"); elements.put("atlas_i_qbe_start_date", "//*[contains(@id, 'pc1:exAtlasTb:id1::content')]"); elements.put("atlas_i_qbe_active", "//*[contains(@id, 'pc1:exAtlasTb:id1::content')]"); elements.put("atlas_i_qbe_main_acount", "//*[contains(@id, 'pc1:exAtlasTb:socid0::content')]"); elements.put("atlas_i_qbe_exclude_b2b", "//*[contains(@id, 'pc1:exAtlasTb:socid0::content')]"); elements.put("atlas_i_qbe_ttoo", "//*[contains(@id, 'pc1_afr_exAtlasTb_afr_resId1c7::content')]"); elements.put("atlas_i_qbe_classification", "//*[contains(@id, 'pc1_afr_exAtlasTb_afr_resId1c10::content')]"); elements.put("atlas_i_qbe_receptive", "//*[contains(@id, 'pc1_afr_exAtlasTb_afr_resId1c12::content')]"); elements.put("atlas_i_qbe_contract", "//*[contains(@id, 'pc1_afr_exAtlasTb_afr_resId1c13::content')]"); elements.put("atlas_i_qbe_hotel", "//*[contains(@id, 'pc1_afr_exAtlasTb_afr_resId1c15::content')]"); elements.put("atlas_i_qbe_chain", "//*[contains(@id, 'pc1_afr_exAtlasTb_afr_resId1c17::content')]"); elements.put("atlas_i_qbe_destination", "//*[contains(@id, 'pc1_afr_exAtlasTb_afr_resId1c19::content')]"); elements.put("atlas_i_qbe_market", "//*[contains(@id, 'pc1_afr_exAtlasTb_afr_resId1c21::content')]"); elements.put("atlas_i_qbe_country", "//*[contains(@id, 'pc1_afr_exAtlasTb_afr_resId1c23::content')]"); elements.put("atlas_i_qbe_application", "//*[contains(@id, 'pc1:exAtlasTb:soc10::content')]"); //AUDIT elements.put("atlas_b_actions", "//*[contains(@id, 'pc1:pcgm1:dc_m1')]"); elements.put("atlas_b_audit", "//*[contains(@id, 'pc1:pcgm1:dc_cmi0')]/td[2]"); elements.put("atlas_b_ok", "//*[contains(@id, 'd22::ok')]"); //DETACH elements.put("atlas_b_detach", "//*[contains(@id, 'pc1:_dchTbr')]"); //COPY EXCLUSIONS elements.put("actions_b_copy_exclusions", "//*[contains(@id, 'pc1:pcgm1:dc_cmi1')]/td[2]"); elements.put("actions_copy_exclusions_tour_operators_b_qbe", "//*[contains(@id, 'pc1:_qbeTbr')]/a"); elements.put("actions_copy_exclusions_tour_operators_qbe_i_tto", "//*[contains(@id, 'pc1_afr_ttoTab_afr_c2::content')]"); elements.put("actions_copy_exclusions_tour_operators_qbe_i_tto_name", "//*[contains(@id, 'pc1_afr_ttoTab_afr_c1::content')]"); elements.put("actions_copy_exclusions_tour_operators_qbe_e_tto", "//*[contains(@id, 'pc1:ttoTab::db')]/table/tbody/tr[1]/td[2]/div/table/tbody/tr/td[1]"); elements.put("actions_copy_exclusions_tour_operators_qbe_e_tto_name", "//*[contains(@id, 'pc1:ttoTab::db')]/table/tbody/tr[1]/td[2]/div/table/tbody/tr/td[2]"); elements.put("actions_copy_exclusions_hotels_b_qbe", "//*[contains(@id, 'pc2:_qbeTbr')]/a"); elements.put("actions_copy_exclusions_hotels_qbe_hotel", "//*[contains(@id, 'pc2_afr_hotTab_afr_c5::content')]"); elements.put("actions_copy_exclusions_hotels_qbe_hotel_name", "//*[contains(@id, 'pc2_afr_hotTab_afr_c4::content')]"); elements.put("actions_copy_exclusions_hotels_e_hotel", "//*[contains(@id, 'pc2:hotTab::db')]/table/tbody/tr[1]/td[2]/div/table/tbody/tr/td[1]"); elements.put("actions_copy_exclusions_hotels_e_hotel_name", "//*[contains(@id, 'pc2:hotTab::db')]/table/tbody/tr[1]/td[2]/div/table/tbody/tr/td[2]"); elements.put("actions_copy_exclusions_e_result_tour_operators", "//*[contains(@id, 'pc1:ttoTab::db')]/table/tbody/tr[1]/td[1]"); elements.put("actions_copy_exclusions_e_result_hotels", "//*[contains(@id, 'pc2:hotTab::db')]/table/tbody/tr[1]/td[1]"); elements.put("actions_copy_exclusions_tour_operators_b_detach", "//*[contains(@id, 'pc1:_dchTbr')]/a"); elements.put("actions_copy_exclusions_hotels_b_detach", "//*[contains(@id, 'pc2:_dchTbr')]/a"); elements.put("actions_copy_exclusions_b_copy", "//*[contains(@id, 'pc1:r1:0:cb1')]"); ///////////////////////////////////////////// SI TAB ///////////////////////////////////////////////////// elements.put("si_tab", "//*[contains(@id, 'sdi4::disAcr')]"); //ADD elements.put("si_b_add", "//*[contains(@id, 'pc1:pcgt2:boton_add')]"); elements.put("si_i_add_reason", "//*[contains(@id, 'pc1:pcgt2:soc2::content')]"); elements.put("si_i_add_start_date", "//*[contains(@id, 'pc1:pcgt2:id8::content')]"); elements.put("si_i_add_ttoo", "//*[contains(@id, 'pc1:pcgt2:seqTtooId::content')]"); elements.put("si_lov_add_ttoo", "//*[contains(@id, 'pc1:pcgt2:seqTtooId::lovIconId')]"); elements.put("si_cb_add_b2b", "//*[contains(@id, 'pc1:pcgt2:sbc3::content')]"); elements.put("si_i_add_classification", "//*[contains(@id, 'pc1:pcgt2:codClasifId::content')]"); elements.put("si_lov_add_classification", "//*[contains(@id, 'pc1:pcgt2:codClasifId::lovIconId')]"); elements.put("si_i_add_agency", "//*[contains(@id, 'pc1:pcgt2:ageExtCodId::content')]"); elements.put("si_lov_add_agency", "//*[contains(@id, 'pc1:pcgt2:ageExtCodId::lovIconId')]"); elements.put("si_i_add_agency_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("si_i_add_crs", "//*[contains(@id, 'pc1:pcgt2:codCrsId::content')]"); elements.put("si_lov_add_crs", "//*[contains(@id, 'pc1:pcgt2:codCrsId::lovIconId')]"); elements.put("si_i_add_brand", "//*[contains(@id, 'pc1:pcgt2:codCrsBrandId::content')]"); elements.put("si_lov_add_brand", "//*[contains(@id, 'pc1:pcgt2:codCrsBrandId::lovIconId')]"); elements.put("si_i_add_rate", "//*[contains(@id, 'pc1:pcgt2:codRateId::content')]"); elements.put("si_lov_add_rate", "//*[contains(@id, 'pc1:pcgt2:codRateId::lovIconId')]"); elements.put("si_i_add_hotel", "//*[contains(@id, 'pc1:pcgt2:seqHotelId::content')]"); elements.put("si_lov_add_hotel", "//*[contains(@id, 'pc1:pcgt2:seqHotelId::lovIconId')]"); elements.put("si_i_add_chain", "//*[contains(@id, 'pc1:pcgt2:codCadenaId::content')]"); elements.put("si_lov_add_chain", "//*[contains(@id, 'pc1:pcgt2:codCadenaId::lovIconId')]"); elements.put("si_i_add_destination", "//*[contains(@id, 'pc1:pcgt2:codDestinoId::content')]"); elements.put("si_lov_add_destination", "//*[contains(@id, 'pc1:pcgt2:codDestinoId::lovIconId')]"); elements.put("si_i_add_market", "//*[contains(@id, 'pc1:pcgt2:codPaisId::content')]"); elements.put("si_lov_add_market", "//*[contains(@id, 'pc1:pcgt2:codPaisId::lovIconId')]"); elements.put("si_i_add_country", "//*[contains(@id, 'pc1:pcgt2:codPaisDestinoId::content')]"); elements.put("si_lov_add_country", "//*[contains(@id, 'pc1:pcgt2:codPaisDestinoId::lovIconId')]"); elements.put("si_i_add_application", "//*[contains(@id, 'pc1:pcgt2:soc10::content')]"); elements.put("si_b_add_save", "//*[contains(@id, 'pc1:pcgt2:btn_commitExit')]"); //EDIT elements.put("si_b_edit", "//*[contains(@id, 'pc1:pcgt2:boton_edit')]"); //SEARCH elements.put("si_b_search", "//*[contains(@id, 'qryId1::search')]"); elements.put("si_b_reset", "//*[contains(@id, 'qryId1::reset')]"); elements.put("si_e_result", "//*[contains(@id, 'pc1:siTabTb::db')]/table/tbody/tr[1]/td[1]"); elements.put("si_n_records", "//*[contains(@id, 'pc1:siTabTbCount')]"); elements.put("si_i_search_reason", "//*[contains(@id, 'qryId1:value10::content')]"); elements.put("si_i_search_start_date", "//*[contains(@id, 'qryId1:value30::content')]"); elements.put("si_i_search_ttoo", "//*[contains(@id, 'qryId1:value60::content')]"); elements.put("si_lov_search_ttoo", "//*[contains(@id, 'qryId1:value60::lovIconId')]"); elements.put("si_i_search_ttoo_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("si_cb_search_b2b", "//*[contains(@id, 'qryId1:value80::content')]"); elements.put("si_i_search_classification", "//*[contains(@id, 'qryId1:value90::content')]"); elements.put("si_lov_search_classification", "//*[contains(@id, 'qryId1:value90::lovIconId')]"); elements.put("si_i_search_classification_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("si_i_search_agency", "//*[contains(@id, 'qryId1:value110::content')]"); elements.put("si_lov_search_agency", "//*[contains(@id, 'qryId1:value110::lovIconId')]"); elements.put("si_i_search_agency_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("si_i_search_crs", "//*[contains(@id, 'qryId1:value130::content')]"); elements.put("si_lov_search_crs", "//*[contains(@id, 'qryId1:value130::lovIconId')]"); elements.put("si_i_search_crs_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("si_i_search_brand", "//*[contains(@id, 'qryId1:value150::content')]"); elements.put("si_lov_search_brand", "//*[contains(@id, 'qryId1:value150::lovIconId')]"); elements.put("si_i_search_brand_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("si_i_search_rate", "//*[contains(@id, 'qryId1:value170::content')]"); elements.put("si_lov_search_rate", "//*[contains(@id, 'qryId1:value170::lovIconId')]"); elements.put("si_i_search_rate_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("si_i_search_hotel", "//*[contains(@id, 'qryId1:value190::content')]"); elements.put("si_lov_search_hotel", "//*[contains(@id, 'qryId1:value190::lovIconId')]"); elements.put("si_i_search_hotel_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("si_i_search_chain", "//*[contains(@id, 'qryId1:value210::content')]"); elements.put("si_lov_search_chain", "//*[contains(@id, 'qryId1:value210::lovIconId')]"); elements.put("si_i_search_chain_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("si_i_search_destination", "//*[contains(@id, 'qryId1:value230::content')]"); elements.put("si_lov_search_destination", "//*[contains(@id, 'qryId1:value230::lovIconId')]"); elements.put("si_i_search_destination_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("si_i_search_market", "//*[contains(@id, 'qryId1:value250::content')]"); elements.put("si_lov_search_market", "//*[contains(@id, 'qryId1:value250::lovIconId')]"); elements.put("si_i_search_market_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("si_i_search_country", "//*[contains(@id, 'qryId1:value270::content')]"); elements.put("si_lov_search_country", "//*[contains(@id, 'qryId1:value270::lovIconId')]"); elements.put("si_i_search_country_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("si_i_search_application", "//*[contains(@id, 'qryId1:value290::content')]"); //AUDIT elements.put("si_b_actions", "//*[contains(@id, 'pc1:pcgm1:dc_m1')]"); elements.put("si_b_audit", "//*[contains(@id, 'pc1:pcgm1:dc_cmi0')]/td[2]"); elements.put("si_b_ok", "//*[contains(@id, 'd22::ok')]"); //DETACH elements.put("si_b_detach", "//*[contains(@id, 'pc1:_dchTbr')]"); //QBE elements.put("si_b_qbe", "//*[contains(@id, 'pc1:_qbeTbr')]"); elements.put("si_i_qbe_reason", "//*[contains(@id, 'pc1:siTabTb:selectOneChoice121::content')]"); elements.put("si_i_qbe_start_date", "//*[contains(@id, 'pc1:siTabTb:id5::content')]"); elements.put("si_i_qbe_ttoo", "//*[contains(@id, 'pc1_afr_siTabTb_afr_resId1c7::content')]"); elements.put("si_i_qbe_classification", "//*[contains(@id, 'pc1_afr_siTabTb_afr_resId1c9::content')]"); elements.put("si_i_qbe_agency", "//*[contains(@id, 'pc1_afr_siTabTb_afr_resId1c10::content')]"); elements.put("si_i_qbe_crs", "//*[contains(@id, 'pc1_afr_siTabTb_afr_resId1c11::content')]"); elements.put("si_i_qbe_brand", "//*[contains(@id, 'pc1_afr_siTabTb_afr_resId1c12::content')]"); elements.put("si_i_qbe_rate", "//*[contains(@id, 'pc1_afr_siTabTb_afr_resId1c13::content')]"); elements.put("si_i_qbe_hotel", "//*[contains(@id, 'pc1_afr_siTabTb_afr_resId1c14::content')]"); elements.put("si_i_qbe_chain", "//*[contains(@id, 'pc1_afr_siTabTb_afr_resId1c15::content')]"); elements.put("si_i_qbe_destination", "//*[contains(@id, 'pc1_afr_siTabTb_afr_resId1c16::content')]"); elements.put("si_i_qbe_market", "//*[contains(@id, 'pc1_afr_siTabTb_afr_resId1c17::content')]"); elements.put("si_i_qbe_country", "//*[contains(@id, 'pc1_afr_siTabTb_afr_resId1c18::content')]"); elements.put("si_i_qbe_application", "//*[contains(@id, 'pc1:siTabTb:soc9::content')]"); ///////SI PARADAS B2B///////////// elements.put("si_e_result_b2b", "//*[contains(@id, 'pc2:tb2Tab::db')]/table/tbody/tr[1]/td[1]"); elements.put("si_n_records_b2b", "//*[contains(@id, 'pc2:ot4')]"); //ADD elements.put("si_b_add_b2b", "//*[contains(@id, 'pc1:pcgt1:boton_add')]"); elements.put("si_i_add_b2b_stop_hour", "//*[contains(@id, 'pc2:pcgt1:it9::content')]"); elements.put("si_i_add_b2b_start_hour", "//*[contains(@id, 'pc2:pcgt1:it10::content')]"); elements.put("si_b_add_b2b_save", "//*[contains(@id, 'pc2:pcgt1:btn_commitExit')]"); //EDIT elements.put("si_b_edit_b2b", "//*[contains(@id, 'pc2:pcgt1:boton_edit')]"); elements.put("si_i_edit_b2b_stop_hour", "//*[contains(@id, 'pc2:pcgt1:it9::content')]"); elements.put("si_i_edit_b2b_start_hour", "//*[contains(@id, 'pc2:pcgt1:it10::content')]"); elements.put("si_b_edit_b2b_save", "//*[contains(@id, 'pc2:pcgt1:btn_commitExit')]"); //DETACH elements.put("si_b_detach_b2b", "//*[contains(@id, 'pc2:_dchTbr')]"); //QBE elements.put("si_b_qbe_b2b", "//*[contains(@id, 'pc2:_qbeTbr')]"); elements.put("si_i_qbe_b2b_agency", "//*[contains(@id, 'pc2_afr_tb2Tab_afr_c4::content')]"); elements.put("si_i_qbe_b2b_stop_hour", "//*[contains(@id, 'pc2_afr_tb2Tab_afr_c2::content')]"); elements.put("si_i_qbe_b2b_start_hour", "//*[contains(@id, 'pc2_afr_tb2Tab_afr_c5::content')]"); //DELETE elements.put("si_b_delete_b2b", "//*[contains(@id, 'pc2:pcgt1:boton_remove')]"); //////////////////////////////////////////// PRODUCT /////////////////////////////////////////////////////////// elements.put("product_tab", "//*[contains(@id, 'sdi9::disAcr')]"); elements.put("product_e_result", "//*[contains(@id, 'pc1:t1::db')]/table/tbody/tr/td[1]"); elements.put("product_n_records", "//*[contains(@id, 'pc1:outputText2')]"); //ADD elements.put("product_b_add", "//*[contains(@id, 'pc1:pcgt1:boton_add')]"); elements.put("product_i_add_reason", "//*[contains(@id, 'pc1:pcgt1:soc1::content')]"); elements.put("product_i_add_destination", "//*[contains(@id, 'pc1:pcgt1:codDestinoId::content')]"); elements.put("product_lov_add_destination", "//*[contains(@id, 'pc1:pcgt1:codDestinoId::lovIconId')]"); elements.put("product_i_add_destination_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("product_i_add_area", "//*[contains(@id, 'pc1:pcgt1:seqZonaGeId::content')]"); elements.put("product_lov_add_area", "//*[contains(@id, 'pc1:pcgt1:seqZonaGeId::lovIconId')]"); elements.put("product_i_add_hotel", "//*[contains(@id, 'pc1:pcgt1:codCategoriaId::content')]"); elements.put("product_lov_add_hotel", "//*[contains(@id, 'pc1:pcgt1:codCategoriaId::lovIconId')]"); elements.put("product_i_add_chain", "//*[contains(@id, 'pc1:pcgt1:codCadenaId::content')]"); elements.put("product_lov_add_chain", "//*[contains(@id, 'pc1:pcgt1:codCadenaId::lovIconId')]"); elements.put("product_i_add_reservation_from", "//*[contains(@id, 'pc1:pcgt1:id8::content')]"); elements.put("product_i_add_arrival_from", "//*[contains(@id, 'pc1:pcgt1:id9::content')]"); elements.put("product_i_add_explain", "//*[contains(@id, 'pc1:pcgt1:it9::content')]"); elements.put("product_b_add_save", "//*[contains(@id, 'pc1:pcgt1:btn_commitExit')]"); elements.put("product_b_add_save_yes", "//*[contains(@id, 'd2::yes')]"); //SEARCH elements.put("product_b_search", "//*[contains(@id, 'qryId1::search')]"); elements.put("product_i_search_reason", "//*[contains(@id, 'qryId1:value10::content')]"); elements.put("product_i_search_destination", "//*[contains(@id, 'qryId1:value20::content')]"); elements.put("product_lov_search_destination", "//*[contains(@id, 'qryId1:value20::lovIconId')]"); elements.put("product_i_search_destination_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("product_i_search_area", "//*[contains(@id, 'qryId1:value40::content')]"); elements.put("product_lov_search_area", "//*[contains(@id, 'qryId1:value40::lovIconId')]"); elements.put("product_i_search_area_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("product_i_search_hotel", "//*[contains(@id, 'qryId1:value60::content')]"); elements.put("product_lov_search_hotel", "//*[contains(@id, 'qryId1:value60::lovIconId')]"); elements.put("product_i_search_hotel_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("product_i_search_chain", "//*[contains(@id, 'qryId1:value80::content')]"); elements.put("product_lov_search_chain", "//*[contains(@id, 'qryId1:value80::lovIconId')]"); elements.put("product_i_search_chain_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("product_i_search_reservation_from", "//*[contains(@id, 'qryId1:value120::content')]"); elements.put("product_i_search_arrival_from", "//*[contains(@id, 'qryId1:value140::content')]"); elements.put("product_i_search_explain", "//*[contains(@id, 'qryId1:value160::content')]"); //EDIT elements.put("product_b_edit", "//*[contains(@id, 'pc1:pcgt1:boton_edit')]"); elements.put("product_i_edit_reason", "//*[contains(@id, 'pc1:pcgt1:soc1::content')]"); elements.put("product_i_edit_destination", "//*[contains(@id, 'pc1:pcgt1:codDestinoId::content')]"); elements.put("product_lov_edit_destination", "//*[contains(@id, 'pc1:pcgt1:codDestinoId::lovIconId')]"); elements.put("product_i_edit_destination_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("product_i_edit_area", "//*[contains(@id, 'pc1:pcgt1:seqZonaGeId::content')]"); elements.put("product_lov_edit_area", "//*[contains(@id, 'pc1:pcgt1:seqZonaGeId::lovIconId')]"); elements.put("product_i_edit_hotel", "//*[contains(@id, 'pc1:pcgt1:codCategoriaId::content')]"); elements.put("product_lov_edit_hotel", "//*[contains(@id, 'pc1:pcgt1:codCategoriaId::lovIconId')]"); elements.put("product_i_edit_chain", "//*[contains(@id, 'pc1:pcgt1:codCadenaId::content')]"); elements.put("product_lov_edit_chain", "//*[contains(@id, 'pc1:pcgt1:codCadenaId::lovIconId')]"); elements.put("product_i_edit_reservation_from", "//*[contains(@id, 'pc1:pcgt1:id8::content')]"); elements.put("product_i_edit_arrival_from", "//*[contains(@id, 'pc1:pcgt1:id9::content')]"); elements.put("product_i_edit_explain", "//*[contains(@id, 'pc1:pcgt1:it9::content')]"); elements.put("product_b_edit_save", "//*[contains(@id, 'pc1:pcgt1:btn_commitExit')]"); elements.put("product_b_edit_save_yes", "//*[contains(@id, 'd2::yes')]"); //DELETE elements.put("product_b_delete", "//*[contains(@id, 'pc1:pcgt1:boton_remove')]"); //AUDIT DATA elements.put("product_b_actions", "//*[contains(@id, 'pc1:pcgm1:dc_m1')]"); elements.put("product_b_audit", "//*[contains(@id, 'pc1:pcgm1:dc_cmi0')]/td[2]"); //DETACH elements.put("product_b_detach", "//*[contains(@id, 'pc1:_dchTbr')]"); //QBE elements.put("product_b_qbe", "//*[contains(@id, 'pc1:_qbeTbr')]"); elements.put("product_i_qbe_reason", "//*[contains(@id, 'pc1:t1:soc3::content')]"); elements.put("product_i_qbe_destination", "//*[contains(@id, 'pc1_afr_t1_afr_c14::content')]"); elements.put("product_i_qbe_area", "//*[contains(@id, 'pc1_afr_t1_afr_c8::content')]"); elements.put("product_i_qbe_hotel", "//*[contains(@id, 'pc1_afr_t1_afr_c1::content')]"); elements.put("product_i_qbe_chain", "//*[contains(@id, 'pc1_afr_t1_afr_c10::content')]"); elements.put("product_i_qbe_reservation_from", "//*[contains(@id, 'pc1:t1:id4::content')]"); elements.put("product_i_qbe_arrival_from", "//*[contains(@id, 'pc1:t1:id3::content')]"); elements.put("product_i_qbe_explain", "//*[contains(@id, 'pc1_afr_t1_afr_c4::content')]"); ///////////////////////////////////////////// SI RULES TAB ///////////////////////////////////////////////////// elements.put("rules_tab", "//*[contains(@id, 'r1:1:sdi5::disAcr')]"); //ADD elements.put("rules_b_add", "//*[contains(@id, 'pc1:pcgt2:boton_add')]"); elements.put("rules_i_add_client", "//*[contains(@id, 'pc1:pcgt2:it4::content')]"); elements.put("rules_i_add_product", "//*[contains(@id, 'pc1:pcgt2:it1::content')]"); elements.put("rules_i_add_description", "//*[contains(@id, 'pc1:pcgt2:it2::content')]"); elements.put("rules_b_add_save", "//*[contains(@id, 'pc1:pcgt2:btn_commitExit')]"); //EDIT elements.put("rules_b_edit", "//*[contains(@id, 'pc1:pcgt2:boton_edit')]"); elements.put("rules_i_edit_client", "//*[contains(@id, 'pc1:pcgt2:it4::content')]"); elements.put("rules_i_edit_product", "//*[contains(@id, 'pc1:pcgt2:it1::content')]"); elements.put("rules_i_edit_description", "//*[contains(@id, 'pc1:pcgt2:it2::content')]"); elements.put("rules_b_edit_save", "//*[contains(@id, 'pc1:pcgt2:btn_commitExit')]"); //SEARCH elements.put("rules_e_result", "//*[contains(@id, 'pc1:resId1::db')]/table/tbody/tr[1]/td[1]"); elements.put("rules_n_records", "//*[contains(@id, 'pc1:outputText1')]"); elements.put("rules_b_search", "//*[contains(@id, 'qryId1::search')]"); elements.put("rules_i_search_client", "//*[contains(@id, 'qryId1:value10::content')]"); elements.put("rules_i_search_product", "//*[contains(@id, 'qryId1:value20::content')]"); elements.put("rules_i_search_description", "//*[contains(@id, 'qryId1:value30::content')]"); //DELETE elements.put("rules_b_delete", "//*[contains(@id, 'pc1:pcgt2:boton_remove')]"); //DETACH elements.put("rules_b_detach", "//*[contains(@id, 'pc1:_dchTbr')]"); //AUDIT DATA elements.put("rules_b_actions", "//*[contains(@id, 'pc1:pcgm1:dc_m1')]"); elements.put("rules_b_audit", "//*[contains(@id, 'pc1:pcgm1:dc_cmi0')]/td[2]"); //QBE elements.put("rules_b_qbe", "//*[contains(@id, 'pc1:_qbeTbr')]"); elements.put("rules_i_qbe_client", "//*[contains(@id, 'pc1_afr_resId1_afr_resId1c2::content')]"); elements.put("rules_i_qbe_product", "//*[contains(@id, 'pc1_afr_resId1_afr_resId1c3::content')]"); elements.put("rules_i_qbe_description", "//*[contains(@id, 'pc1_afr_resId1_afr_resId1c4::content')]"); ///////////////////////////////////////////// QUERY TAB ///////////////////////////////////////////////////// elements.put("query_tab", "//*[contains(@id, 'sdi6::disAcr')]"); //SEARCH elements.put("query_b_search", "//*[contains(@id, '0:cb1')]"); elements.put("query_n_records", "//*[contains(@id, 'pc1:outputText1')]"); elements.put("query_e_result", "//*[contains(@id, 'pc1:excQTb::db')]/table/tbody/tr[1]/td[1]"); elements.put("query_i_search_ttoo", "//*[contains(@id, 'consTtooId::content')]"); elements.put("query_lov_search_ttoo", "//*[contains(@id, 'consTtooId::lovIconId')]"); elements.put("query_i_search_ttoo_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("query_i_search_chain", "//*[contains(@id, 'consCadenaId::content')]"); elements.put("query_lov_search_chain", "//*[contains(@id, 'consCadenaId::lovIconId')]"); elements.put("query_i_search_chain_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); elements.put("query_i_search_market", "//*[contains(@id, 'consPaisId::content')]"); elements.put("query_lov_search_market", "//*[contains(@id, 'consPaisId::lovIconId')]"); elements.put("query_i_search_market_code", "//*[contains(@id, '_afrLovInternalQueryId:value00::content')]"); //QBE elements.put("query_b_qbe", "//*[contains(@id, 'pc1:_qbeTbr')]"); elements.put("query_i_qbe_ttoo", "//*[contains(@id, 'pc1_afr_excQTb_afr_c9::content')]"); elements.put("query_i_qbe_chain", "//*[contains(@id, 'pc1_afr_excQTb_afr_c1::content')]"); elements.put("query_i_qbe_market", "//*[contains(@id, 'pc1_afr_excQTb_afr_c7::content')]"); //AUDIT elements.put("query_b_actions", "//*[contains(@id, 'pc1:pcgm1:dc_m1')]"); elements.put("query_b_audit", "//*[contains(@id, 'pc1:pcgm1:dc_cmi0')]/td[2]"); //DETACH elements.put("query_b_detach", "//*[contains(@id, 'pc1:_dchTbr')]"); //////////////////////////////////////////// DISCONNECT TAB //////////////////////////////////////////////////// elements.put("disconnect_tab", "//*[contains(@id, 'r1:1:sdi7::disAcr')]"); } }
true
e9ec54e37949dcf9f009face4b1bc58369ea2115
Java
junyuo/AlbertGitProject
/src/albert/practice/designpattern/strategy/PdfExporter.java
UTF-8
270
2.25
2
[]
no_license
package albert.practice.designpattern.strategy; import lombok.extern.slf4j.Slf4j; @Slf4j public class PdfExporter implements ExportStrategy { @Override public void exportData(String data) { log.debug("exporting " + data + " into pdf file."); } }
true
4444c485b17e1844fd1719a9b676eee2c1da72e3
Java
Noahhhhha/leetcode
/src/problem/array/[56]合并区间.java
UTF-8
1,242
3.515625
4
[]
no_license
//给出一个区间的集合,请合并所有重叠的区间。 // // 示例 1: // // 输入: [[1,3],[2,6],[8,10],[15,18]] //输出: [[1,6],[8,10],[15,18]] //解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6]. // // // 示例 2: // // 输入: [[1,4],[4,5]] //输出: [[1,5]] //解释: 区间 [1,4] 和 [4,5] 可被视为重叠区间。 // Related Topics 排序 数组 //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int[][] merge(int[][] intervals) { List<int[]> res = new ArrayList<>(); if (intervals == null || intervals.length == 0) return res.toArray(new int[0][]); Arrays.sort(intervals, (x, y) -> x[0] - y[0]); // 根据左区间排序,很重要 for (int[] i : intervals){ int last = res.size() - 1; if (res.isEmpty() || res.get(last)[1] < i[0]) // 如果区间没有相交,直接加到结果集中 res.add(i); else res.get(last)[1] = Math.max(i[1], res.get(last)[1]); // 有相交的区间,就要比较两个的右区间 } return res.toArray(new int [0][]); } } //leetcode submit region end(Prohibit modification and deletion)
true
e0e124733a44eb3f2bb24336b46147c0a4007bc4
Java
immutables/immutables
/criteria/common/src/org/immutables/criteria/expression/Operators.java
UTF-8
1,394
2.34375
2
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
/* * Copyright 2019 Immutables Authors and Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.immutables.criteria.expression; import java.lang.reflect.Type; public enum Operators implements Operator { /** * One element equal ({@code =}) to another (object equality) */ EQUAL(Arity.BINARY), /** * One element NOT equal ({@code !=}) to another (object equality) */ NOT_EQUAL(Arity.BINARY), /** * Element present in a collection */ IN(Arity.BINARY), /** * Element NOT present in a collection */ NOT_IN(Arity.BINARY), // boolean ops AND(Arity.BINARY), OR(Arity.BINARY), NOT(Arity.UNARY); private final Arity arity; Operators(Arity arity) { this.arity = arity; } @Override public Arity arity() { return arity; } @Override public Type returnType() { return Boolean.class; } }
true
132aaa07e942bbb80d15652cf03f8db45c7098d2
Java
akuuindra/Digitalent-Project
/Note/Note/app/src/main/java/com/example/note/Registrasi.java
UTF-8
3,027
2.375
2
[]
no_license
package com.example.note; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.io.File; import java.io.FileOutputStream; public class Registrasi extends AppCompatActivity { public static final String FILENAME = "login.txt"; Button simpan; EditText username, password, email, name, school, address; String user, pass, mail, nama, sekolah, alamat; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registrasi); String title = "Registrasi"; getSupportActionBar().setTitle(title); username = findViewById(R.id.usernamereg); password = findViewById(R.id.passwordreg); email = findViewById(R.id.emailreg); name = findViewById(R.id.namereg); school = findViewById(R.id.schoolreg); address = findViewById(R.id.addressreg); simpan = findViewById(R.id.btn_savereg); simpan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(isValidation()) { simpanRegistrasi(); } else { Toast.makeText(Registrasi.this, "Mohon Lengkapi Seluruh Data", Toast.LENGTH_SHORT).show(); } } }); } boolean isValidation() { user = username.getText().toString(); pass = password.getText().toString(); mail = email.getText().toString(); nama = name.getText().toString(); sekolah = school.getText().toString(); alamat = address.getText().toString(); if(user.equals("") || pass.equals("") || mail.equals("") || nama.equals("") || sekolah.equals("") || alamat.equals("")) { return false; } else { return true; } } void simpanRegistrasi() { user = username.getText().toString(); pass = password.getText().toString(); mail = email.getText().toString(); nama = name.getText().toString(); sekolah = school.getText().toString(); alamat = address.getText().toString(); String isiFile = user + ";" + pass + ";" + mail + ";" + nama + ";" + sekolah + ";" + alamat + '\n' ; File file = new File(getFilesDir(), FILENAME); FileOutputStream outputStream = null; try { file.createNewFile(); outputStream = new FileOutputStream(file, true); outputStream.write(isiFile.getBytes()); outputStream.flush(); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } Toast.makeText(this, "Registrasi Berhasil", Toast.LENGTH_SHORT).show(); onBackPressed(); } }
true
10cb4b2dd864508dd8be516b3046419ee0babcc7
Java
dx4321/Calk
/com/company/operator/IOperator.java
UTF-8
158
2.234375
2
[]
no_license
package com.company.operator; import java.math.BigInteger; public interface IOperator { String symbol(); Integer calculate(int val1, int val2); }
true
65166e043b110fbf0be348283b189db22586554d
Java
ewardb/spring-cloud-demo
/spring-cloud-demo/src/main/java/org/wq/demo/springclouddemo/node_event_driver/v2/event/Subject.java
UTF-8
425
1.710938
2
[]
no_license
package org.wq.demo.springclouddemo.node_event_driver.v2.event; import java.util.HashMap; /** * @author wangqiang26 * @mail wangqiang26@jd.com * @Date 19:30 2018/11/12 */ public interface Subject { HashMap<String, String> post(String type, String subject, HashMap<String, String> params) ; // void posth(String type, String subject, String response) ; // void poste(String type, String subject, String response) ; }
true
6796cca4ffda9c1f8a925ad2230beda15bff4379
Java
clementinej/Quizness
/src/model/MultipleChoice.java
UTF-8
1,404
3.28125
3
[]
no_license
package model; import java.util.ArrayList; import java.util.Set; public class MultipleChoice extends Question { private String question; private String[] choices; private double pointValue; private Answers answer; //private String questionType = "MultipleChoice"; //Multiple choice questions support one question and one correct answer among a string of choices public MultipleChoice(String question, String[] choices, ArrayList<Set<String>> answer, double pointValue){ this.question = question; this.answer = new Answers(answer); this.pointValue = pointValue; this.choices = choices; } //grabs the values of the answers. can be used to print all possible answers @Override public ArrayList<Set<String>> getAnswer(){ return answer.getValue(); } //divides the number of correct answers by the number of total entries //the returned point value is a fraction of the user's given point value. //the max is the point value @Override public double getPoints(String[] response) { return pointValue * answer.getNumCorrect(response); } @Override public double getMaxPoints() { return pointValue; } //simply returns the question @Override public String getQuestion() { return question; } //Return the possible choices as a array of strings public String[] getChoices(){ return choices; } @Override public int getQuestionType() { return 3; } }
true
15c6399b8336e89f0ee9d3a6649ccecaaf2ae239
Java
Donpommelo/Uplifted.VFFV
/src/dev/zt/UpliftedVFFV/statusEffects/EquipmentStatus/HiveRhythmItemBStatus.java
UTF-8
2,324
2.375
2
[]
no_license
package dev.zt.UpliftedVFFV.statusEffects.EquipmentStatus; import dev.zt.UpliftedVFFV.Battle.Action; import dev.zt.UpliftedVFFV.party.Schmuck; import dev.zt.UpliftedVFFV.states.BattleState; import dev.zt.UpliftedVFFV.statusEffects.PrismaticResistance; import dev.zt.UpliftedVFFV.statusEffects.status; import dev.zt.UpliftedVFFV.statusEffects.Stats.BonusStatBuff; import dev.zt.UpliftedVFFV.statusEffects.Stats.StatBuffMult; public class HiveRhythmItemBStatus extends status{ status buff; public HiveRhythmItemBStatus(Schmuck v,int pr, status st){ super("Hive Rhythm : B", v, pr); this.buff = st; } public void onActionUser(BattleState bs, Action a){ switch(buff.getExtraVar1()){ case 0: bs.bp.bt.addScene("Hive Rhythm A-B chord echoes Salubriously!"); for(Schmuck ally : bs.bp.getSelectableAllies(a.getUser())){ if(bs.bp.stm.checkStatus(ally, new HiveRhythmBuffStatus(ally,50))){ bs.bp.em.hpChange((int)(25*(1+a.getUser().getEquipPow())*(1+ally.getRegenBonus())), a.getUser(), ally, 1); } } break; case 2: bs.bp.bt.addScene("Hive Rhythm C-B chord echoes Smoothly!"); for(Schmuck ally : bs.bp.getSelectableAllies(a.getUser())){ if(bs.bp.stm.checkStatus(ally, new HiveRhythmBuffStatus(ally,50))){ bs.bp.stm.addStatus(ally, new BonusStatBuff(0, 1, 0.5*(1+a.getUser().getEquipPow()), a.getUser(), ally, 50)); } } break; case 3: bs.bp.bt.addScene("Hive Rhythm D-B chord echoes Protectively!"); for(Schmuck ally : bs.bp.getSelectableAllies(a.getUser())){ if(bs.bp.stm.checkStatus(ally, new HiveRhythmBuffStatus(ally,50))){ bs.bp.stm.addStatus(ally, new StatBuffMult(3, 3, 1.1*(1+a.getUser().getEquipPow()), a.getUser(), ally, 50)); } } break; case 4: bs.bp.bt.addScene("Hive Rhythm E-B chord echoes Resiliently!"); for(Schmuck ally : bs.bp.getSelectableAllies(a.getUser())){ if(bs.bp.stm.checkStatus(ally, new HiveRhythmBuffStatus(ally,50))){ bs.bp.stm.addStatus(ally, new PrismaticResistance(0, .5*(1+a.getUser().getEquipPow()), a.getUser(), ally, 50)); } } break; } for(Schmuck ally : bs.bp.getSelectableAllies(a.getUser())){ if(bs.bp.stm.checkStatus(ally, new HiveRhythmBuffStatus(ally,50))){ bs.bp.stm.findStatus(ally, new HiveRhythmBuffStatus(ally,50)).setExtraVar1(1); } } } }
true
ac7cea1423c7f9d31f2d90be15fec4011e0f9634
Java
dasarianudeep/healthcareinternet
/HealthCareInternetPortal/src/main/java/edu/neu/service/MedicationWorkRequestService.java
UTF-8
656
2.015625
2
[]
no_license
package edu.neu.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import edu.neu.dao.MedicationWorkRequestDAO; @Service public class MedicationWorkRequestService extends ImplementMedicationWorkRequest{ @Autowired private MedicationWorkRequestDAO medicationWorkRequestDAO; @Override public void addMedication(String pid, String eid, String drugname, String drugdosage, String quantity, String advice,String loginuser) { // TODO Auto-generated method stub medicationWorkRequestDAO.addMedication(pid, eid, drugname, drugdosage, quantity, advice,loginuser); } }
true
b5904a2762f7146e72f775ed401df6d9c083d605
Java
coder921/filterReloaded
/src/test/java/com/spark/filtering/rest/user/UserServiceTest.java
UTF-8
6,076
2.09375
2
[]
no_license
package com.spark.filtering.rest.user; import com.spark.filtering.model.City; import com.spark.filtering.model.Matches; import com.spark.filtering.model.User; import com.spark.filtering.rest.geo.GeoService; import com.spark.filtering.rest.geo.GeoServiceImpl; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Bean; import org.springframework.test.context.junit4.SpringRunner; import java.util.ArrayList; import static org.mockito.Mockito.when; import static org.junit.Assert.*; @RunWith(SpringRunner.class) public class UserServiceTest { @TestConfiguration static class TestContextConfiguration { @Bean public GeoService geoService() { return new GeoServiceImpl(); } @Bean public UserService userService() { return new UserServiceImpl(matches(), geoService()); } @Bean public Matches matches() { return new Matches(); } } @MockBean private Matches matches; @Autowired private UserService userService; @Autowired private GeoService geoService; private City city1; private City city2; @Before public void setUp() { city1 = new City(); city1.setName("Leeds"); city1.setLat(53.801277d); city1.setLon(-1.548567d); city2 = new City(); city2.setName("Solihull"); city2.setLat(52.412811d); city2.setLon(-1.778197d); } @Test public void test_Matches_hasPhoto() throws Exception { User user = new User(); user.setMain_photo("http://thecatapi.com/api/images/get?format=src&type=gif"); user.setCity(city1); ArrayList<User> listOfUsers = new ArrayList<>(); listOfUsers.add(user); when(matches.getMatches()).thenReturn(listOfUsers); FilterRequest request = new FilterRequest(); request.setHasPhoto(true); assertEquals(1, userService.find(request).size()) ; } @Test public void test_Matches_inContact() throws Exception { User user = new User(); user.setContacts_exchanged(2); user.setCity(city1); ArrayList<User> listOfUsers = new ArrayList<>(); listOfUsers.add(user); when(matches.getMatches()).thenReturn(listOfUsers); FilterRequest request = new FilterRequest(); request.setInContact(true); assertEquals(1, userService.find(request).size()) ; } @Test public void test_Matches_favourite_one_found() throws Exception { ArrayList<User> listOfUsers = new ArrayList<>(); User user1 = new User(); user1.setCity(city1); user1.setFavourite(true); listOfUsers.add(user1); User user2 = new User(); user2.setFavourite(false); user2.setCity(city1); listOfUsers.add(user2); when(matches.getMatches()).thenReturn(listOfUsers); FilterRequest request = new FilterRequest(); request.setFavourite(true); assertEquals(1, userService.find(request).size()) ; } @Test public void test_Matches_compatibility_score() throws Exception { ArrayList<User> listOfUsers = new ArrayList<>(); User user1 = new User(); user1.setCompatibility_score(0.76d); user1.setCity(city1); listOfUsers.add(user1); User user2 = new User(); user2.setCompatibility_score(0.95d); user2.setCity(city2); listOfUsers.add(user2); when(matches.getMatches()).thenReturn(listOfUsers); FilterRequest request = new FilterRequest(); request.setCompatibilityScore(95d); assertEquals(1, userService.find(request).size()) ; } @Test public void test_Matches_age() throws Exception { ArrayList<User> listOfUsers = new ArrayList<>(); User user1 = new User(); user1.setAge(45); user1.setCity(city1); listOfUsers.add(user1); User user2 = new User(); user2.setAge(44); user2.setCity(city2); listOfUsers.add(user2); when(matches.getMatches()).thenReturn(listOfUsers); FilterRequest request = new FilterRequest(); request.setAge(45); assertEquals(1, userService.find(request).size()) ; } @Test public void test_Matches_height() throws Exception { ArrayList<User> listOfUsers = new ArrayList<>(); User user1 = new User(); user1.setHeight_in_cm(135); user1.setCity(city1); listOfUsers.add(user1); User user2 = new User(); user2.setHeight_in_cm(200); user2.setCity(city1); listOfUsers.add(user2); User user3 = new User(); user3.setHeight_in_cm(210); user3.setCity(city2); listOfUsers.add(user3); when(matches.getMatches()).thenReturn(listOfUsers); FilterRequest request = new FilterRequest(); request.setHeight(185); assertEquals(2, userService.find(request).size()) ; } @Test public void test_Matches_distanceInKm() throws Exception { ArrayList<User> listOfUsers = new ArrayList<>(); User user1 = new User(); City city1 = new City(); city1.setName("Leeds"); city1.setLat(53.801277d); city1.setLon(-1.548567d); user1.setCity(city1); listOfUsers.add(user1); User user2 = new User(); City city2 = new City(); city2.setName("Solihull"); city2.setLat(52.412811d); city2.setLon(-1.778197d); user2.setCity(city2); listOfUsers.add(user2); when(matches.getMatches()).thenReturn(listOfUsers); FilterRequest request = new FilterRequest(); request.setDistanceInKm(272); assertEquals(1, userService.find(request).size()) ; } }
true
89c9395701e55d625498add98532cae2c98cf87f
Java
ydswinter/MultiModelLive
/app/src/main/java/com/yds/multimodellive/model/User.java
UTF-8
1,042
2.5625
3
[]
no_license
package com.yds.multimodellive.model; public class User { private String account; private String name; private String description; public User() { } public User(String account, String name, String description) { this.account = account; this.name = name; this.description = description; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User{" + "account='" + account + '\'' + ", name='" + name + '\'' + ", description='" + description + '\'' + '}'; } }
true
1c341e58816ea722f9b953ddb961defee7224169
Java
albertomv/workcraft
/WorkcraftCore/src/org/workcraft/commands/AbstractTimingCommand.java
UTF-8
432
2.09375
2
[ "MIT" ]
permissive
package org.workcraft.commands; import org.workcraft.MenuOrdering; public abstract class AbstractTimingCommand implements ScriptableCommand<Boolean>, MenuOrdering { @Override public final String getSection() { return "!Timing"; // 0 spaces - positions 5th } @Override public int getPriority() { return 0; } @Override public Position getPosition() { return null; } }
true
20ca498114247d6655b54da582e794011271c9da
Java
tcrct/duangframework
/duang-core/src/main/java/com/duangframework/core/config/ConfigFactory.java
UTF-8
703
2.03125
2
[]
no_license
package com.duangframework.core.config; import com.duangframework.config.apollo.api.SimpleApolloConfig; import com.duangframework.config.client.ConfigClient; import com.duangframework.core.interfaces.IConfig; /** * @author Created by laotang * @date createed in 2018/3/7. */ public class ConfigFactory { private static SimpleApolloConfig apolloConfig = null; public static IConfig getConfigClient() { IConfig iConfig = null; SimpleApolloConfig apolloConfig= ConfigClient.getApolloConfig(); if(null != apolloConfig) { iConfig = new ApolloConfig(); } else { iConfig = new PropertiesConfig(); } return iConfig; } }
true
476a5d5d2afcdc02409e56e07f963ef6e3e1e1e2
Java
toramuryo796/curriculum
/JavaStudy/Cat/src/Cat.java
UTF-8
409
3.9375
4
[]
no_license
public class Cat { private String name; public int age; //カプセル化していない //コンストラクタ public Cat(String n, int a) { this.name = n; this.age = a; } //メソッド public void showName() { System.out.println("名前は" + name + "です"); } public void showAge() { System.out.println("年齢は" + age + "才です"); } public void agePlus() { age++; } }
true
483ccd3d0364dd4f21b38af36448636c7288d770
Java
bgeng777/flink-ai-extended
/deep-learning-on-flink/flink-ml-framework/src/test/java/com/alibaba/flink/ml/cluster/storage/ZookeeperStorageImplTest.java
UTF-8
2,435
1.929688
2
[ "Apache-2.0", "MIT", "Python-2.0", "BSD-3-Clause", "BSD-2-Clause" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.flink.ml.cluster.storage; import com.alibaba.flink.ml.cluster.node.MLContext; import com.alibaba.flink.ml.util.MLConstants; import com.alibaba.flink.ml.util.DummyContext; import org.apache.curator.test.TestingServer; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.List; import static org.junit.Assert.assertEquals; public class ZookeeperStorageImplTest { private static TestingServer server; private static Storage client; @Before public void setUp() throws Exception { server = new TestingServer(2181, true); MLContext context = DummyContext.createDummyMLContext(); context.getProperties().put(MLConstants.JOB_VERSION, "0"); client = StorageFactory.getStorageInstance(context.getProperties()); } @After public void tearDown() throws Exception { client.close(); server.stop(); } @Test public void setGetValue() throws Exception { client.setValue("a", "aa".getBytes()); byte[] bytes = client.getValue("a"); Assert.assertEquals("aa", new String(bytes)); } @Test public void listChildren() throws Exception { String path = "aa"; int size = 3; for (int i = 0; i < size; i++) { client.setValue(path + "/" + i, String.valueOf(i).getBytes()); } boolean flag1 = client.exists(path); assertEquals(true, flag1); List<String> res = client.listChildren(path); Assert.assertEquals(size, res.size()); for (int i = 0; i < size; i++) { Assert.assertEquals(String.valueOf(i), res.get(i)); } client.removeValue(path); boolean flag = client.exists(path); assertEquals(false, flag); } }
true
d90e381ec7029cc277c802a07e55a05fd4f6c9f8
Java
SafwenBensaid/toolsSystem
/src/java/dto/livraison/CreationDossiers.java
UTF-8
6,511
2.203125
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package dto.livraison; import dto.EnvironnementDTO; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import threads.ExecuterCommandeJshOrT24Thread; import tools.Configuration; import tools.DeploiementParalleleTools; /** * * @author 04486 */ public class CreationDossiers implements Serializable { private String creationDossiersChemin; private String creationDossiersDroitR; private String creationDossiersDroitW; private String creationDossiersDroitX; public CreationDossiers() { } public CreationDossiers(String creationDossiersChemin, String creationDossiersDroitR, String creationDossiersDroitW, String creationDossiersDroitX) { this.creationDossiersChemin = creationDossiersChemin; this.creationDossiersDroitR = creationDossiersDroitR; this.creationDossiersDroitW = creationDossiersDroitW; this.creationDossiersDroitX = creationDossiersDroitX; } public String getCreationDossiersChemin() { return creationDossiersChemin; } public void setCreationDossiersChemin(String creationDossiersChemin) { this.creationDossiersChemin = creationDossiersChemin; } public String getCreationDossiersDroitR() { return creationDossiersDroitR; } public void setCreationDossiersDroitR(String creationDossiersDroitR) { this.creationDossiersDroitR = creationDossiersDroitR; } public String getCreationDossiersDroitW() { return creationDossiersDroitW; } public void setCreationDossiersDroitW(String creationDossiersDroitW) { this.creationDossiersDroitW = creationDossiersDroitW; } public String getCreationDossiersDroitX() { return creationDossiersDroitX; } public void setCreationDossiersDroitX(String creationDossiersDroitX) { this.creationDossiersDroitX = creationDossiersDroitX; } @Override public String toString() { StringBuilder resultat = new StringBuilder(); resultat.append(" <div class='center'>"); resultat.append(" <table class='tablePrincipale'>"); resultat.append(" <tr>"); resultat.append(" <td class='conteneurWrapper'>"); resultat.append(" <div id='wrapper'>"); resultat.append(" <div class='accordionButton on'>CREATION DOSSIERS<span class='errorBold'></span></div>"); resultat.append(" <div class='accordionContent' style='display: block;'>"); resultat.append(" <fieldset class='fieldSetResultatDeploiement'>"); resultat.append(" <li>"); resultat.append(" <span class = 'titre'>Chemin: </span>"); resultat.append(" ").append(creationDossiersChemin); resultat.append(" </li>"); resultat.append(" <li>"); resultat.append(" <span class = 'titre'>Droits: </span>"); resultat.append(" ").append(creationDossiersDroitR).append(creationDossiersDroitW).append(creationDossiersDroitX); resultat.append(" </li>"); resultat.append(" </fieldset>"); resultat.append(" </div>"); resultat.append(" </div>"); resultat.append(" </td>"); resultat.append(" </tr>"); resultat.append(" </table>"); resultat.append(" </div>"); return resultat.toString(); } public Map<String, String[]> traiter(String connectedUser, String[] tabEnvNameDestinationDeploiementLivraison) { Map<String, String[]> resultMap = new HashMap<>(); List<ExecuterCommandeJshOrT24Thread> listeThreads = new ArrayList<>(); for (String envName : tabEnvNameDestinationDeploiementLivraison) { EnvironnementDTO envDto = Configuration.environnementDTOMapUserHasEnvironnement.get(connectedUser).get(envName); String[] commandes = new String[3]; commandes[0] = "mkdir -p " + creationDossiersChemin; commandes[1] = "chmod " + creationDossiersDroitR + creationDossiersDroitW + creationDossiersDroitX + " " + creationDossiersChemin; commandes[2] = "if test -d " + creationDossiersChemin + "; then echo 'FOLDER EXISTS'; else echo 'FOLDER DOES NOT EXISTS' ;fi"; ExecuterCommandeJshOrT24Thread th = new ExecuterCommandeJshOrT24Thread(envDto, commandes, "CREATION_DOSSIER", ""); th.setName("Thread " + envDto.getNom() + ", CREATION_DOSSIER"); listeThreads.add(th); } new DeploiementParalleleTools().launchThreads(listeThreads); //fin test cob //Collecter le code HTML du résultat List<String> envDepOkList = new ArrayList<>(); StringBuilder resultatHTML = new StringBuilder(); String problems = ""; for (ExecuterCommandeJshOrT24Thread th : listeThreads) { resultatHTML.append(th.resultatHTML); if (th.problemExist == false) { envDepOkList.add(th.env.getNom()); } else { problems += th.resultatCommande + "<br>"; } } resultatHTML = getAllHtmlResult(resultatHTML); resultMap.put("PROBLEME", new String[]{"", ""}); resultMap.put("RESULTAT", new String[]{resultatHTML.toString(), problems}); resultMap.put("RESULTAT_HTML_COMPLET", new String[]{resultatHTML.toString()}); resultMap.put("ENV_DEP_OK", envDepOkList.toArray(new String[envDepOkList.size()])); return resultMap; } private StringBuilder getAllHtmlResult(StringBuilder unionHTML) { StringBuilder resultat = new StringBuilder(); resultat.append(" <div class='center'>"); resultat.append(" <table class='tablePrincipale'>"); resultat.append(" <tr>"); resultat.append(" <td class='conteneurWrapper'>"); resultat.append(" <div id='wrapper'>"); resultat.append(" <div class='accordionButton on'>CREATION DOSSIERS</div>"); resultat.append(" <div class='accordionContent' style='display: block;'>"); resultat.append(unionHTML); resultat.append(" </div>"); resultat.append(" </div>"); resultat.append(" </td>"); resultat.append(" </tr>"); resultat.append(" </table>"); resultat.append(" </div>"); return resultat; } }
true
06773ab80dc5d2c56f503063c64b64fc2d78805f
Java
impossibl/pgjdbc-ng
/driver/src/main/java/com/impossibl/postgres/utils/guava/ByteStreams.java
UTF-8
11,871
2.265625
2
[ "BSD-3-Clause" ]
permissive
/** * Copyright (c) 2013, impossibl.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of impossibl.com nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.impossibl.postgres.utils.guava; import static com.impossibl.postgres.utils.guava.Preconditions.checkArgument; import static com.impossibl.postgres.utils.guava.Preconditions.checkNotNull; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; /** * Provides utility methods for working with byte arrays and I/O streams. * * @author Chris Nokleberg * @author Colin Decker * @since 1.0 */ public final class ByteStreams { private static final int BUF_SIZE = 0x1000; // 4K private ByteStreams() { } /** * Copies all bytes from the input stream to the output stream. * Does not close or flush either stream. * * @param from the input stream to read from * @param to the output stream to write to * @return the number of bytes copied * @throws IOException if an I/O error occurs */ public static long copy(InputStream from, OutputStream to) throws IOException { checkNotNull(from); checkNotNull(to); byte[] buf = new byte[BUF_SIZE]; long total = 0; while (true) { int r = from.read(buf); if (r == -1) { break; } to.write(buf, 0, r); total += r; } return total; } /** * Copies all bytes from the readable channel to the writable channel. * Does not close or flush either channel. * * @param from the readable channel to read from * @param to the writable channel to write to * @return the number of bytes copied * @throws IOException if an I/O error occurs */ public static long copy(ReadableByteChannel from, WritableByteChannel to) throws IOException { checkNotNull(from); checkNotNull(to); ByteBuffer buf = ByteBuffer.allocate(BUF_SIZE); long total = 0; while (from.read(buf) != -1) { buf.flip(); while (buf.hasRemaining()) { total += to.write(buf); } buf.clear(); } return total; } /** * Reads all bytes from an input stream into a byte array. * Does not close the stream. * * @param in the input stream to read from * @return a byte array containing all the bytes from the stream * @throws IOException if an I/O error occurs */ public static byte[] toByteArray(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); copy(in, out); return out.toByteArray(); } private static final OutputStream NULL_OUTPUT_STREAM = new OutputStream() { /** Discards the specified byte. */ @Override public void write(int b) { } /** Discards the specified byte array. */ @Override public void write(byte[] b) { checkNotNull(b); } /** Discards the specified byte array. */ @Override public void write(byte[] b, int off, int len) { checkNotNull(b); } @Override public String toString() { return "ByteStreams.nullOutputStream()"; } }; /** * Returns an {@link OutputStream} that simply discards written bytes. * * @since 14.0 (since 1.0 as com.google.common.io.NullOutputStream) */ public static OutputStream nullOutputStream() { return NULL_OUTPUT_STREAM; } /** * Wraps a {@link InputStream}, limiting the number of bytes which can be * read. * * @param in the input stream to be wrapped * @param limit the maximum number of bytes to be read * @return a length-limited {@link InputStream} * @since 14.0 (since 1.0 as com.google.common.io.LimitInputStream) */ public static InputStream limit(InputStream in, long limit) { return new LimitedInputStream(in, limit); } public static final class LimitedInputStream extends FilterInputStream { private long limit; private long left; private long mark = -1; LimitedInputStream(InputStream in, long limit) { super(in); checkNotNull(in); checkArgument(limit >= 0, "limit must be non-negative"); this.left = limit; this.limit = limit; } public long limit() { return limit; } @Override public int available() throws IOException { return (int) Math.min(in.available(), left); } // it's okay to mark even if mark isn't supported, as reset won't work @Override public synchronized void mark(int readLimit) { in.mark(readLimit); mark = left; } @Override public int read() throws IOException { if (left == 0) { return -1; } int result = in.read(); if (result != -1) { --left; } return result; } @Override public int read(byte[] b, int off, int len) throws IOException { if (left == 0) { return -1; } len = (int) Math.min(len, left); int result = in.read(b, off, len); if (result != -1) { left -= result; } return result; } @Override public synchronized void reset() throws IOException { if (!in.markSupported()) { throw new IOException("Mark not supported"); } if (mark == -1) { throw new IOException("Mark not set"); } in.reset(); left = mark; } @Override public long skip(long n) throws IOException { n = Math.min(n, left); long skipped = in.skip(n); left -= skipped; return skipped; } } /** * Attempts to read enough bytes from the stream to fill the given byte array. * Does not close the stream. * * @param in * the input stream to read from. * @param b * the buffer into which the data is read. * @throws EOFException * if this stream reaches the end before reading all the bytes. * @throws IOException * if an I/O error occurs. */ public static void readFully(InputStream in, byte[] b) throws IOException { readFully(in, b, 0, b.length); } /** * Attempts to read {@code len} bytes from the stream into the given array * starting at {@code off}. Does not close the stream. * * @param in * the input stream to read from. * @param b * the buffer into which the data is read. * @param off * an int specifying the offset into the data. * @param len * an int specifying the number of bytes to read. * @throws EOFException * if this stream reaches the end before reading all the bytes. * @throws IOException * if an I/O error occurs. */ public static void readFully(InputStream in, byte[] b, int off, int len) throws IOException { int read = read(in, b, off, len); if (read != len) { throw new EOFException("reached end of stream after reading " + read + " bytes; " + len + " bytes expected"); } } /** * Discards {@code n} bytes of data from the input stream. This method * will block until the full amount has been skipped. Does not close the * stream. * * @param in the input stream to read from * @param n the number of bytes to skip * @throws EOFException if this stream reaches the end before skipping all * the bytes * @throws IOException if an I/O error occurs, or the stream does not * support skipping */ public static void skipFully(InputStream in, long n) throws IOException { long toSkip = n; while (n > 0) { long amt = in.skip(n); if (amt == 0) { // Force a blocking read to avoid infinite loop if (in.read() == -1) { long skipped = toSkip - n; throw new EOFException("reached end of stream after skipping " + skipped + " bytes; " + toSkip + " bytes expected"); } n--; } else { n -= amt; } } } /** * Reads some bytes from an input stream and stores them into the buffer array * {@code b}. This method blocks until {@code len} bytes of input data have * been read into the array, or end of file is detected. The number of bytes * read is returned, possibly zero. Does not close the stream. * * <p>A caller can detect EOF if the number of bytes read is less than * {@code len}. All subsequent calls on the same stream will return zero. * * <p>If {@code b} is null, a {@code NullPointerException} is thrown. If * {@code off} is negative, or {@code len} is negative, or {@code off+len} is * greater than the length of the array {@code b}, then an * {@code IndexOutOfBoundsException} is thrown. If {@code len} is zero, then * no bytes are read. Otherwise, the first byte read is stored into element * {@code b[off]}, the next one into {@code b[off+1]}, and so on. The number * of bytes read is, at most, equal to {@code len}. * * @param in the input stream to read from * @param b the buffer into which the data is read * @param off an int specifying the offset into the data * @param len an int specifying the number of bytes to read * @return the number of bytes read * @throws IOException if an I/O error occurs */ public static int read(InputStream in, byte[] b, int off, int len) throws IOException { checkNotNull(in); checkNotNull(b); if (len < 0) { throw new IndexOutOfBoundsException("len is negative"); } int total = 0; while (total < len) { int result = in.read(b, off + total, len - total); if (result == -1) { break; } total += result; } return total; } }
true
763ebb7962844bd585e76fbe7730b8bf2dd81232
Java
airmic/quizboot
/src/main/java/ru/otus/hw/quizboot/service/CommunicateService.java
UTF-8
277
1.523438
2
[]
no_license
package ru.otus.hw.quizboot.service; public interface CommunicateService { void putI10nCode(String str); void putI10nCode(String str, Object[] objs); void putString(String str); void putEmptyLines(int num); String getObject(); void inputLocale(); }
true
d05e87a925c4317793430a097ca4dcd86145c6eb
Java
xhom/spring-ioc
/src/main/java/com/visy/spring/test/AddUserTest4.java
UTF-8
561
2.4375
2
[]
no_license
package com.visy.spring.test; import com.visy.spring.core.BeanFactory; import com.visy.spring.model.User; import com.visy.spring.service.UserService; /** * 通过annotation配置实现自动注入属性值-set(1) */ public class AddUserTest4 { public static void main(String[] args) { //通过Bean工厂获取对象 UserService userService = (UserService)BeanFactory.getBean2("userService"); //创建要保存的用户 User user = new User(4,"陈六","004"); userService.add3(user);//添加用户 } }
true
3df8b4e43e12777a09e88d414b3c0bd9528be65b
Java
alexander-pimenov/javalesson
/chapter_write_with_TDD/src/main/java/ru/pimalex1978/PairOgDigits.java
UTF-8
485
2.859375
3
[]
no_license
package ru.pimalex1978; /** * Класс для хранения пар соответствия * 1 - I * 5 - V * 10 - X * 50 - L * 100 - C * 500 - D * 1000 - M */ public class PairOgDigits { private int arabic; private char roman; public PairOgDigits(int arabic, char roman) { this.arabic = arabic; this.roman = roman; } public int getArabic() { return arabic; } public char getRoman() { return roman; } }
true
7d323e6590410199dd974b06e0f367afcfc9256a
Java
qingyouzhuying/KEG-EntityLinkingSystem
/src/edu/tsinghua/el/web/action/LinkingAction.java
UTF-8
1,954
2.15625
2
[]
no_license
package edu.tsinghua.el.web.action; import java.util.ArrayList; import javax.servlet.http.HttpServletResponse; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.struts2.ServletActionContext; import org.apache.struts2.json.annotations.JSON; import com.opensymphony.xwork2.ActionSupport; import edu.tsinghua.el.model.LinkingResult; import edu.tsinghua.el.service.EntityLinkingServiceImpl; public class LinkingAction extends ActionSupport{ private static final long serialVersionUID = 1L; private static final Logger logger = LogManager.getLogger(LinkingAction.class); private String text; private String index_choose; private ArrayList<LinkingResult> resultList; @JSON(name="text") public String getText() { return text; } @JSON(name="text") public void setText(String text) { this.text = text; } @JSON(name="index_choose") public String getIndex_choose() { return index_choose; } @JSON(name="index_choose") public void setIndex_choose(String index_choose) { this.index_choose = index_choose; } @JSON(name="ResultList") public ArrayList<LinkingResult> getResultList() { return resultList; } public void setResultList(ArrayList<LinkingResult> resultList) { this.resultList = resultList; } public String execute(){ try{ logger.info("Text Acceptted: " + text); logger.info("Indedx Choose Acceptted: " + index_choose); EntityLinkingServiceImpl linkingIns = new EntityLinkingServiceImpl(); resultList = linkingIns.linking(text, index_choose); logger.info("Linking Result List:" + resultList); System.out.println("Linking Result List:" + resultList); HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/xml;charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); return SUCCESS; }catch(Exception e){ logger.error(e.getMessage(), e); throw e; } } }
true
4353ac04db0592ff85f5a74dc888b410e3b675ca
Java
iezhuhx/cloud
/springcloud-zuul/src/main/java/com/kiiik/web/system/mapper/UserMapper.java
UTF-8
632
1.757813
2
[]
no_license
package com.kiiik.web.system.mapper; import java.util.List; import com.github.pagehelper.Page; import com.kiiik.web.system.po.Menu; import com.kiiik.web.system.po.User; import com.kiiik.web.system.vo.UserCompanyInfor; import com.kiiik.web.system.vo.UserRoleVo; /** *作者 : iechenyb<br> *类描述: 说点啥<br> *创建时间: 2018年10月19日 */ public interface UserMapper { List<UserRoleVo> getUserRoles(Integer userId);//获取用户的角色 List<Menu> getUserMenus(Integer userId);//获取用户的菜单 Page<User> getUsers(User user); UserCompanyInfor getUserCompanyInfor(String empNo); }
true
2a580471837ebe18856468ba39b4274cf4ec4cdd
Java
zzambers/jenkins-scm-koji-plugin
/src/main/java/org/fakekoji/xmlrpc/server/FakeKojiDB.java
UTF-8
11,047
2.21875
2
[ "MIT" ]
permissive
/* * The MIT License * * Copyright 2015 user. * * 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 org.fakekoji.xmlrpc.server; import hudson.plugins.scm.koji.Constants; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.fakekoji.xmlrpc.server.core.FakeBuild; import org.fakekoji.xmlrpc.server.utils.DirFilter; /** * Hart beat of fake koji. This class works over directory, with similar * structure as koji have, and is trying to deduct informations just on content * and names. On those deductions it offers its content and even tags. */ public class FakeKojiDB { private final File mainDir; private final String[] projects; private final List<FakeBuild> builds; FakeKojiDB(File file) { System.out.println(new Date().toString() + " (re)initizing fake koji DB"); mainDir = file; File[] projectDirs = mainDir.listFiles(new DirFilter()); projects = new String[projectDirs.length]; builds = new ArrayList<>(); //read all projects for (int i = 0; i < projectDirs.length; i++) { File projectDir = projectDirs[i]; projects[i] = projectDir.getName(); //and all builds in those project File[] versions = projectDir.listFiles(new DirFilter()); for (File version : versions) { File[] releases = version.listFiles(new DirFilter()); for (File release : releases) { FakeBuild b = new FakeBuild(projectDir.getName(), version.getName(), release.getName(), release); builds.add(b); } } } } Integer getPkgId(String requestedProject) { String trayed = ""; for (String project : projects) { trayed += " " + project; if (project.equals(requestedProject)) { //is there better str->int function? //indeed, the file. But number of projects is small. return project.hashCode(); } } throw new RuntimeException("Unknown project " + requestedProject + ". Tried: " + trayed + "."); } /* Return is scary Object[] where mebers are hashmaps "size = 21" HashMap ObjectVariable [ 0] "start_ts => 1.47013406794314E9" [ 2] "owner_name => jvanek" [ 3] "completion_time => 2016-08-02 21:23:37.487583" [ 4] "volume_id => 0" [ 5] "owner_id => 1487" [ 6] "release => 3.b14.fc26" [ 7] "volume_name => DEFAULT" [ 8] "task_id => 15101251" [ 9] "epoch => 1" [10] "nvr => java-1.8.0-openjdk-1.8.0.101-3.b14.fc26" [11] "package_id => 15685" [12] "creation_event_id => 17490426" [13] "version => 1.8.0.101" [14] "start_time => 2016-08-02 10:34:27.943136" [15] "build_id => 787467" [16] "package_name => java-1.8.0-openjdk" [17] "name => java-1.8.0-openjdk" [18] "creation_ts => 1.47013406794314E9" [19] "completion_ts => 1.47017301748758E9" [20] "state => 1" [ 1] "creation_time => 2016-08-02 10:34:27.943136" */ Object[] getProjectBuildsByProjectIdAsMaps(Integer projectId) { List<FakeBuild> matchingBuilds = getProjectBuildsByProjectId(projectId); for (int i = 0; i < matchingBuilds.size(); i++) { FakeBuild get = matchingBuilds.get(i); boolean mayBeFailed = new IsFailedBuild(get.getDir()).reCheck().getLastResult(); if (mayBeFailed) { System.out.println("Removing build (" + i + "): " + get.toString() + " from result. Contains FAILED records"); matchingBuilds.remove(i); i--; } } Object[] res = new Object[matchingBuilds.size()]; for (int i = 0; i < matchingBuilds.size(); i++) { FakeBuild get = matchingBuilds.get(i); res[i] = get.toBuildMap(); } return res; } List<FakeBuild> getProjectBuildsByProjectId(Integer projectId) { List<FakeBuild> res = new ArrayList(builds.size()); for (int i = 0; i < builds.size(); i++) { FakeBuild get = builds.get(i); if (get.getProjectID() == projectId) { res.add(get); } } return res; } FakeBuild getBuildById(Integer buildId) { for (int i = 0; i < builds.size(); i++) { FakeBuild get = builds.get(i); if (get.getBuildID() == buildId) { return get; } } return null; } /** * This method is trying to deduct tags from content of build. Purpose is, * that if the build is for some os only, it should be tagged accodringly. * On contrary, if it is static, then it should pass anywhere * * @param parameter * @return */ Object[] getTags(Map parameter) { Integer buildId = (Integer) parameter.get(Constants.build); String[] tagNames = getTags(buildId); Map[] result = new Map[tagNames.length]; for (int i = 0; i < tagNames.length; i++) { String tagName = tagNames[i]; Map map = new HashMap(1); map.put(Constants.name, tagName); result[i] = map; } return result; } private String[] getTags(Integer buildId) { for (int i = 0; i < builds.size(); i++) { FakeBuild get = builds.get(i); if (get.getBuildID() == buildId) { try { return get.guessTags(); } catch (IOException ex) { throw new RuntimeException(ex); } } } return new String[0]; } void checkAll() { for (String project : projects) { check(project); } } void check(String string) { Integer id = getPkgId(string); if (id == null) { return; } System.out.println(string + " id=" + id); Object[] chBuilds = getProjectBuildsByProjectIdAsMaps(id); System.out.println(string + " builds#=" + chBuilds.length); int bn = 0; for (Object chBuild : chBuilds) { bn++; System.out.println("####### " + bn + " #######"); Map m = (Map) chBuild; Set keys = m.keySet(); for (Object key : keys) { Object value = m.get(key); System.out.println(" " + key + ": " + value); if (key.equals(Constants.build_id)) { System.out.println(" tags:"); Object[] tags = getTags((Integer) value); for (Object tag : tags) { System.out.println(" " + tag); } System.out.println("Artifacts for given build"); FakeBuild bld = getBuildById((Integer) value); bld.printExpectedArchesForThisBuild(); List<String> arches = bld.getArches(); System.out.println(" archs: " + arches.size()); for (String arch : arches) { System.out.println(" logs: " + arch); //list logs List<File> logs = bld.getLogs(arch); logs.stream().forEach((log) -> { System.out.println(log); }); //list others System.out.println(" all: " + arch); List<File> files = bld.getNonLogs(arch); files.stream().forEach((f) -> { System.out.println(f); }); } } if (key.equals(Constants.rpms)) { System.out.println(" mapped: "); Object[] rpms = (Object[]) value; for (Object rpm : rpms) { Map mrpms = (Map) rpm; Set rks = mrpms.keySet(); rks.stream().forEach((rk) -> { System.out.println(" " + rk + ": " + mrpms.get(rk)); }); } } } } System.out.println("Artifacts for given project " + string + " " + id); List<FakeBuild> blds = getProjectBuildsByProjectId(id); for (FakeBuild bld : blds) { List<String> arches = bld.getArches(); for (String arch : arches) { System.out.println(" arch: " + arch); //list logs List<File> logs = bld.getLogs(arch); logs.stream().forEach((log) -> { System.out.println(log); }); //list others List<File> files = bld.getNonLogs(arch); files.stream().forEach((f) -> { System.out.println(f); }); } } } Object[] getRpms(Object get, Object get0) { return getRpmsI((Integer) get, (Object[]) get0); } /** * * @param buildDd * @param archs String[] * @return array of hashmaps */ Object[] getRpmsI(Integer buildDd, Object[] archs) { FakeBuild build = getBuildById(buildDd); if (build == null) { return new Object[0]; } return build.getRpmsAsArrayOfMaps(archs); } Object[] getArchives(Object get, Object get0) { return getArchivesI((Integer) get, (Object[]) get0); } /** * same as rpms but on windows (solaris?) archives */ Object[] getArchivesI(Integer buildDd, Object[] archs) { return new Object[0]; } }
true
a26fd80a49112f3b23252931d04521e84acc681e
Java
thangchuot992011/NaiveBayesInJava
/naivebayes/src/naivebayes/TrainingData.java
UTF-8
3,259
3.15625
3
[]
no_license
/* * 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 naivebayes; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; // Apache Common IO import org.apache.commons.io.FileUtils; /** * * @author DELL */ public class TrainingData { // chuyen mot string rar lon thanh tap hop (set) cac tu nho hon khong lap public static Set<String> cvttBagOfWords(String str) { HashSet<String> bag = new HashSet<>(); // tach cac tu phan cach boi cac dau ,.!*"'() StringTokenizer str_token = new StringTokenizer(str, " ,.!*\"\'()"); while (str_token.hasMoreTokens()) { bag.add(str_token.nextToken()); } return bag; } // chuyen mot string rat lon thanh mot Arraylist public static ArrayList<String> cvttArrayList(String str) { ArrayList<String> arrl_bag = new ArrayList<>(); StringTokenizer str_token = new StringTokenizer(str, " ,.!*\"\'()"); while (str_token.hasMoreTokens()) { arrl_bag.add(str_token.nextToken()); } return arrl_bag; } public static void main(String[] args) throws IOException { System.out.println("Bat dau qua trinh huan luyen...\n"); // tien hanh doc file rt_polarity_pos.txt // chuyen thanh tui tu (bag of words) // va chuyen thanh ArrayList cac tu co trong file do File posFile = new File("data/positive/rt_polarity_pos.txt"); // su dung FileUtils cua Apache Common IO // doc file thanh string String posFileData = FileUtils.readFileToString(posFile, "UTF-8"); Set<String> posBagOfWords = cvttBagOfWords(posFileData); ArrayList<String> posArrayListBag = cvttArrayList(posFileData); // thuc hien tuong tu cho file rt_polarity_neg.txt File negFile = new File("data/negative/rt_polarity_neg.txt"); String negFileData = FileUtils.readFileToString(negFile, "UTF-8"); Set<String> negBagOfWords = cvttBagOfWords(negFileData); ArrayList<String> negArrayListBag = cvttArrayList(negFileData); // ghi cac Set vao file training_result.dat ObjectOutputStream outSet = new ObjectOutputStream( new FileOutputStream( new File("data/training_result/training_result.dat"))); outSet.writeObject(posBagOfWords); outSet.writeObject(negBagOfWords); outSet.close(); // ghi cac ArrayList vao file all_words.dat ObjectOutputStream outArrl = new ObjectOutputStream( new FileOutputStream( new File("data/training_result/all_words.dat"))); outArrl.writeObject(posArrayListBag); outArrl.writeObject(negArrayListBag); outArrl.close(); System.out.println("Hoan tat qua trinh huan luyen!"); } }
true
5deb9896dcffb81528183ac4ed86c5efe47fdd18
Java
aps2019project/project-43
/clientGame/src/Network.java
UTF-8
1,534
2.96875
3
[]
no_license
import GamePackage.NetworkObject; import java.io.EOFException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.ServerSocket; import java.net.Socket; public class Network { private Socket socket; private ObjectOutputStream output; private ObjectInputStream input; Network(String serverIP, int port) { try { socket = new Socket(serverIP, port); output = new ObjectOutputStream(socket.getOutputStream()); input = new ObjectInputStream(socket.getInputStream()); } catch (IOException e) { e.printStackTrace(); } } public void send(NetworkObject runnable) { try { output.writeObject(runnable); output.flush(); } catch (IOException e) { e.printStackTrace(); } } public NetworkObject receive() throws EOFException { NetworkObject sender=null; try { sender=(NetworkObject) input.readObject(); } catch (IOException | ClassNotFoundException e) { if(e instanceof EOFException) throw (EOFException)e; e.printStackTrace(); } return sender; } public void end(){ try { output.close(); input.close(); socket.close(); System.exit(-1); } catch (IOException e1) { e1.printStackTrace(); } } }
true
91f7cbfd41f1345ecf3b6510209340ea99f578f1
Java
SnehaSree28/ApiTesting
/src/test/java/BasicsTest.java
UTF-8
2,245
2.4375
2
[]
no_license
import Files.Payload; import io.restassured.RestAssured; import io.restassured.path.json.JsonPath; import io.restassured.response.Response; import org.testng.annotations.Test; import static io.restassured.RestAssured.*; import static org.hamcrest.Matchers.*; /** * Created by lovel on 14-Mar-20. */ public class BasicsTest { //Given--All Input Details //When--Submit the API Request -- Http Method //Then--Validate the response @Test public void addData() { RestAssured.baseURI = "https://rahulshettyacademy.com/"; String response=given().log().all().queryParam("key", "qaclick123").header("Content-Type", "application/json") .body(Payload.addPlace()).when().post("/maps/api/place/add/json") .then().log().all().assertThat().statusCode(200).body("scope",equalTo("APP")). header("server",equalTo("Apache/2.4.18 (Ubuntu)")).extract() .response().asString(); JsonPath jsonPath = new JsonPath(response); String placeId= jsonPath.getString("place_id"); String address = "Hyderabad"; //Put Request given().log().all().queryParam("key","qaclick123").header("Content-Type","application/json") .body("{\n" + "\"place_id\":\""+placeId+"\",\n" + "\"address\":\""+address+"\",\n" + "\"key\":\"qaclick123\"\n" + "}\n").when().put("maps/api/place/update/json"). then().log().all().assertThat().statusCode(200). body("msg",equalTo("Address successfully updated")); //Get Request String getPlaceResponse= given().log().all().queryParam("key","qaclick123").queryParam("place_id",placeId). header("Content-Type","application/json").when(). get("maps/api/place/get/json").then().log().all().assertThat().statusCode(200) .extract().response().asString(); JsonPath jsonPath1= new JsonPath(getPlaceResponse); String actualAddress= jsonPath1.getString("address"); } }
true
1e9c8a8af95df4da794676c1686ecaf1f4421018
Java
3588/cus1156
/Week9/SimpleGuiTester.java
UTF-8
149
1.710938
2
[]
no_license
package Week9; public class SimpleGuiTester { public static void main(String[] args) { SimpleGui1B gui = new SimpleGui1B(); gui.go(); } }
true
6258ec3b3e5f8eb7e65a136a962b6c51a7f62252
Java
XiaoFeng2016/RxJavaDemo
/app/src/main/java/im/vinci/materialdesign/module/FakeThing.java
UTF-8
112
1.53125
2
[]
no_license
package im.vinci.materialdesign.module; public class FakeThing { public int id; public String name; }
true
08a3db0e0ab89273079132e90ff44c747205d4b2
Java
kalodiodev/control-my-car-spring-web-app
/src/test/java/eu/kalodiodev/controlmycar/converter/ExpenseDtoToExpenseTest.java
UTF-8
1,628
2.53125
3
[ "MIT" ]
permissive
package eu.kalodiodev.controlmycar.converter; import eu.kalodiodev.controlmycar.converter.values.ExpenseValues; import eu.kalodiodev.controlmycar.domains.Expense; import eu.kalodiodev.controlmycar.web.model.ExpenseDto; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.time.LocalDate; import static org.junit.jupiter.api.Assertions.*; class ExpenseDtoToExpenseTest { private ExpenseDtoToExpense converter; @BeforeEach public void setUp() throws Exception { converter = new ExpenseDtoToExpense(); } @Test public void testEmptyObject() throws Exception { assertNotNull(converter.convert(new ExpenseDto())); } @Test public void convert() throws Exception { // given ExpenseDto expenseDto = ExpenseDto.builder() .id(ExpenseValues.ID_VALUE) .date(LocalDate.now()) .title(ExpenseValues.TITLE_VALUE) .description(ExpenseValues.DESCRIPTION_VALUE) .cost(ExpenseValues.COST_VALUE) .carId(ExpenseValues.CAR_ID_VALUE) .build(); // when Expense expense = converter.convert(expenseDto); // then assertNotNull(expense); assertEquals(ExpenseValues.ID_VALUE, expense.getId()); assertEquals(ExpenseValues.TITLE_VALUE, expense.getTitle()); assertEquals(ExpenseValues.DESCRIPTION_VALUE, expense.getDescription()); assertEquals(ExpenseValues.COST_VALUE, expense.getCost()); assertEquals(ExpenseValues.CAR_ID_VALUE, expense.getCar().getId()); } }
true
21a1f74113ecd754032e803d5499d2c193fd5249
Java
Leargy/openRemoteMDB
/mutliserver/src/uplink_bags/ExecuteBag.java
UTF-8
1,381
2.59375
3
[]
no_license
package uplink_bags; import instructions.concrete.ConcreteDecree; import java.nio.channels.SocketChannel; /** * Пакет исполнения, хранящий * клиентский канал и команду, * что клиента заказал * @author Come_1LL_F00 aka Lenar Khannanov * @author Leargy aka Anton Sushkevich * @see TunnelBag */ public final class ExecuteBag implements TransportableBag { private final ConcreteDecree CONCRETE_DECREE; private final SocketChannel CLIENT_SOCKET_CHANNEL; /** * Конструктор принимающий * наш this very k-nal и команду, * требующую выполнения * @param channel клиентский или серверный канал * @param decree конкретно передаваемая команда */ public ExecuteBag(SocketChannel clientChannel, ConcreteDecree decree) { CLIENT_SOCKET_CHANNEL = clientChannel; CONCRETE_DECREE = decree; } /** * Свойство взятия канал * пользователя * @return канал клиента */ public SocketChannel Channel() { return CLIENT_SOCKET_CHANNEL; } /** * Свойство взятия команды * на исполнение * @return конкретная команда */ public ConcreteDecree getConcreteDecree() { return CONCRETE_DECREE; } }
true
b8b436b75c9e18788738dbf2d89c3d36bcbd731c
Java
Xingchen1224/Java-Weather-Report
/GraphPanel.java
UTF-8
8,388
2.828125
3
[ "Apache-2.0" ]
permissive
/*********************************/ /* Author: Xingchen Wang */ /* Email: xwang95@sheffield.ac.uk*/ /* I declare this is my own work.*/ /* 02 / 01/ 2015 */ /*********************************/ import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Line2D; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import javax.swing.JPanel; public class GraphPanel extends JPanel { Double graphHight; Double graphWidth; Double[] X_line;// x coordinates for line graph Double[] Y_line;// y coordinates for line graph double[] X_dots;// x coordinates for dots graph double[] Y_dots;// y coordinates for dots graph Double yMax; // maximum value to display the graph Double yMin = 0.0;// minimum value to display the graph int flag; //flag to distinguish drawing temperature, pressure or wind graph Color graphColor; float shiftX; // the gap between graph and the left boundary float shiftY; // the gap between graph and the top boundary Double unitY; // the unit of grid in vertical direction Double unitX; // the unit of grid in horizontal direction //constructor of temperature and pressure graph public GraphPanel(ArrayList<Double> windspeed,ArrayList<Double> pTime, int pFlag) { flag = pFlag; graphHight = 500.0 / 4.0; graphWidth = 700.0; shiftX = 30.0f; shiftY = 10.0f; unitY = graphHight / 4.0; unitX = 700.0 / 24.0; switch (pFlag) { case 1: graphColor = Color.red;//temperature break; case 2: graphColor = Color.green; // pressure break; default: System.out.println("check error!"); break; } this.preProcess(flag, windspeed, null); this.geneCooridinateLine(windspeed, pTime); } //constructor of wind graph public GraphPanel(ArrayList<Double> windspeed,ArrayList<Double> gustspeed,ArrayList<Double> pTime,int pFlag) { flag = pFlag; graphHight = 500.0 / 4.0; graphWidth = 700.0; shiftX = 30.0f; shiftY = 10.0f; unitY = graphHight / 4.0; unitX = 700.0 / 24.0; this.preProcess(flag, windspeed, gustspeed); this.geneCooridinateLine(windspeed, pTime); this.geneCooridinateDots(gustspeed, pTime); graphColor = Color.orange; } //override the paintComponent methods to draw graphs, grid, label, icon etc. public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; this.drawGrid(g2); this.drawXAxis(g2); this.drawYAxis(g2); this.drawLabel(g2, flag); this.drawLineGrpah(g2); if(flag==3){ this.drawDotsGraph(g2); } } // pre-processing data, to get the maximum and minimum value of the graph private void preProcess(int flag,ArrayList<Double> windspeed,ArrayList<Double> gustspeed){ if(flag==3){//wind data @SuppressWarnings("unchecked") ArrayList<Double> tmpData = (ArrayList<Double>) gustspeed.clone(); while (tmpData.contains(-9999.0)) { int index = tmpData.indexOf(-9999.0); tmpData.remove(index); } yMax = Collections.max(windspeed); yMin = Collections.min(windspeed); Double tmpYMax = Collections.max(gustspeed); Double tmpYMin = Collections.min(gustspeed); if(tmpYMax > yMax){ yMax = tmpYMax; } if(tmpYMin < yMin){ yMin = tmpYMin; } }else{ @SuppressWarnings("unchecked") ArrayList<Double> tmpData = (ArrayList<Double>) windspeed.clone(); while (tmpData.contains(-9999.0)) { int index = tmpData.indexOf(-9999.0); tmpData.remove(index); } yMax = Collections.max(tmpData); yMin = Collections.min(tmpData); } } //generate coordinate data for line graph private void geneCooridinateLine(ArrayList<Double> pData1,ArrayList<Double> pTime){ X_line = new Double[pData1.size()]; Y_line = new Double[pData1.size()]; for (int i = 0; i < pData1.size(); i++) { X_line[i] = pTime.get(i)*graphWidth / 24.0 +shiftX; Y_line[i] = (yMax - pData1.get(i))*graphHight/(yMax - yMin) + shiftY; } } //generate coordinate data for gust wind speed private void geneCooridinateDots(ArrayList<Double> pData2,ArrayList<Double> pTime){ X_dots = new double[pData2.size()]; Y_dots = new double[pData2.size()]; for (int i = 0; i < pData2.size(); i++) { X_dots[i] = pTime.get(i)*graphWidth / 24.0 +shiftX; Y_dots[i] = (yMax - pData2.get(i))*graphHight/(yMax - yMin) + shiftY; } } //line graph: temperature, pressure, wind speed private void drawLineGrpah(Graphics2D g2){ g2.setPaint(graphColor); g2.setStroke(new BasicStroke(2)); Double startPointX = X_line[0]; Double startPointY = Y_line[0]; for (int i = 1; i < X_line.length; i++) { Double endPointX = X_line[i]; Double endPointY = Y_line[i]; if(Y_line[i]<150.0){ g2.draw(new Line2D.Double(startPointX, startPointY, endPointX,endPointY)); startPointX = endPointX; startPointY = endPointY; }else{ startPointX = endPointX; //startPointY = Y1[i+1]; } } } //dots graph: gust wind data graph private void drawDotsGraph(Graphics2D g2){ for (int i = 0; i < X_dots.length; i++) { if(Y_dots[i]!=135.0){// gust Windspeed not equals 0 g2.setPaint(Color.blue); g2.setStroke(new BasicStroke(4)); g2.drawOval((int)X_dots[i],(int)Y_dots[i], 4, 4); } } } // the grid private void drawGrid(Graphics2D g2) { g2.setColor(Color.lightGray); g2.setStroke(new BasicStroke(1)); for (int j = 0; j <= 4; j++) { g2.draw(new Line2D.Double(shiftX, shiftY + j * unitY, 700 + shiftX, shiftY + j * unitY)); } for (int i = 0; i < 25; i++) { g2.draw(new Line2D.Double(shiftX + i * unitX, shiftY, shiftX + i * unitX, shiftY + graphHight)); } } //information at the bottom of graph, i.e. the x axis private void drawXAxis(Graphics2D g2) { g2.setColor(Color.black); for (int i = 0; i <= 12; i++) { if (i == 0) { g2.drawString("midnight", (int) (i * unitX), 145); } else if (i == 12) { g2.drawString("noon", (int) (shiftX / 2.0 + i * unitX), 145); } else if (i < 10) { g2.drawString(Integer.toString(i), (int) (shiftX * 0.9 + i * unitX), 145); } else { g2.drawString(Integer.toString(i), (int) (shiftX * 0.8 + i * unitX), 145); } } for (int i = 13; i <= 23; i++) { if (i - 12 < 10) { g2.drawString(Integer.toString(i - 12), (int) (shiftX * 0.9 + i * unitX), 145); } else { g2.drawString(Integer.toString(i - 12), (int) (shiftX * 0.8 + i * unitX), 145); } } } //information at the right of graph, i.e. the y axis private void drawYAxis(Graphics2D g2) { for (int i = 0; i <= 4; i++) { double value = (yMax - yMin) * (double) (4 - i) / 4.0 + yMin; BigDecimal bg = new BigDecimal(value); value = bg.setScale(1,BigDecimal.ROUND_HALF_UP).doubleValue(); g2.drawString(Double.toString(value), 700 + shiftX + 2, (float) ((yMax - value)*graphHight/(yMax - yMin) + shiftY/*this.chartY(value)(int) (unitY * i + shiftY)*/)); } } //label information at the right-hand side of the graph private void drawLabel(Graphics2D g2, int flag) { int labelX = (int) shiftX + 735; int labelY = 10; int unitY = labelY + 15; int lineY = unitY + 15; switch (flag) { case 1: g2.drawString("Temeprature Graph", labelX, labelY); g2.drawString("Units: C", labelX, unitY); break; case 2: labelX = labelX + 10; g2.drawString("Pressure Graph", labelX, labelY); g2.drawString("Units: hPa", labelX, unitY); break; case 3: labelX = labelX + 5; g2.drawString("Windspeed Graph", labelX, labelY); g2.drawString("Units: km/h", labelX, unitY); g2.drawString("Gustspeed Graph", labelX, labelY+60); g2.drawString("Units: km/h", labelX, unitY+60); g2.drawString("Color:", labelX, unitY+75); g2.setColor(Color.blue); g2.setStroke(new BasicStroke(4)); g2.drawOval(labelX + 44, unitY+69, 4, 4); break; default: System.out.println("check error!"); break; } g2.setColor(Color.black); g2.drawString("Color:",labelX, lineY); g2.setColor(graphColor); g2.setStroke(new BasicStroke(3)); g2.drawLine(labelX + 42, lineY - 4, labelX + 80, lineY-4); } }
true
6ad9a7f8a913e9078cf91c51e6b58f4483dee831
Java
leekihyn/pol
/web2/src/com/test/servlet/BoardServlet.java
UTF-8
4,328
2.625
3
[]
no_license
package com.test.servlet; import java.io.IOException; import java.util.HashMap; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.test.services.BoardService; public class BoardServlet extends HttpServlet{ private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest req, HttpServletResponse resq) throws IOException, ServletException{ req.setCharacterEncoding("UTF-8"); BoardService bs = new BoardService(); String bititle = req.getParameter("bititle"); String bicontent = req.getParameter("bicontent"); String bipwd = req.getParameter("bipwd"); String creusr = req.getParameter("creusr"); String credat = req.getParameter("credat"); //System.out.println(name1+pwd1+a); String command = req.getParameter("command"); HashMap hm = new HashMap(); if(command.equals("UPDATE")) { hm.put("bititle", bititle); hm.put("bicontent", bicontent); hm.put("bipwd", bipwd); hm.put("creusr", creusr); hm.put("credat", credat); bs.updateBoard(hm); }else if(command.equals("DELETE")){ hm.put("bititle", bititle); hm.put("bicontent", bicontent); hm.put("bipwd", bipwd); hm.put("creusr", creusr); hm.put("credat", credat); bs.updateBoard(hm); }else if(command.equals("SELECT")){ hm.put("bititle", bititle); hm.put("bicontent", bicontent); hm.put("bipwd", bipwd); hm.put("creusr", creusr); hm.put("credat", credat); bs.updateBoard(hm); //bs.insertUser(hm); } } public void dePost(HttpServletRequest req, HttpServletResponse reqs) throws IOException{ } } //public class UserServlet extends HttpServlet{ // // // private static final long serialVersionUID = 1L; // // public void doGet(HttpServletRequest req, HttpServletResponse resq) throws IOException, ServletException{ // req.setCharacterEncoding("UTF-8"); // //html화면에서 던진 값을 각각 String 변수로 받기 시작 // String command = req.getParameter("command"); // UserService us = new UserService(); // // //UserService에 있는 insertUser(HashMap hm)이라는 함수를 호출하기 위해 // //UserService로 us 레퍼런스 변수를 생성 // if(command.equals("SIGNIN")){ // String id = req.getParameter("id"); // String pwd = req.getParameter("pwd"); // String name = req.getParameter("name"); // String class_num = req.getParameter("class_num"); // String age = req.getParameter("age"); // // //위에서 받은 String 변수를 출력해줌(Tomcat 콘솔창에) // System.out.println(id + "," + pwd + "," + name + "," + class_num + ", " + age); // // //해쉬맵 생성 // HashMap hm = new HashMap(); // //html화면에서 던진 id값을 "id"라는 키로 해쉬맵에 저장 // hm.put("id", id); // //html화면에서 던진 pwd값을 "pwd"라는 키로 해쉬맵에 저장 // hm.put("pwd", pwd); // //html화면에서 던진 name값을 "name"라는 키로 해쉬맵에 저장 // hm.put("name", name); // //html화면에서 던진 class_num값을 "class_num"라는 키로 해쉬맵에 저장 // hm.put("class_num", class_num); // //html화면에서 던진 age값을 "age"라는 키로 해쉬맵에 저장 // hm.put("age", age); // //위에서 생성한 us레퍼런스 변수를 사용해 insertUser함수를 호출하는데 파라메터값은 // //위에서 생성하고 값을 저장한 HashMap인 hm레퍼런스 변수를 같이 던짐 // if(us.insertUser(hm)){ // doProcess(resq, "저장 잘 됬꾸만!!!!"); // }else{ // doProcess(resq, "값 똑바로 입력 안하냐잉~"); // } // }else if(command.equals("DELETE")){ // String user_num = req.getParameter("user_num"); // System.out.println("삭제할 번호 : " + user_num); // } // // // } // // public void dePost(HttpServletRequest req, HttpServletResponse reqs) throws IOException{ // // } // // // public void doProcess(HttpServletResponse resq, String writeStr) throws IOException { // resq.setContentType("text/html; charset = UTF-8"); // PrintWriter out = resq.getWriter(); // out.print(writeStr); // // } //}
true
1504d25125dea1f7a346b992d187e680faf428d4
Java
Org-Dat/OrgDat
/src/main/java/Filters/TableFilter.java
UTF-8
2,193
2.359375
2
[]
no_license
package Filters; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class TableFilter extends HttpServlet implements Filter { protected DatabaseConnection dc; RoleChecker roleFinder ; @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; roleFinder = new RoleChecker(); PrintWriter out = response.getWriter(); try { Cookie[] cookies = request.getCookies(); long user_id = roleFinder.getUserId(cookies); if(user_id == -1) { throw new Exception(); } dc = new DatabaseConnection("Orgdat"); String org_name = request.getParameter("org_name"); String db_name = request.getParameter("db_name"); String table_name = request.getParameter("table_name"); if(org_name == null) { throw new Exception(); } String role = roleFinder.tableRole(org_name, db_name,table_name ,user_id); if(role == null) { role = roleFinder.dbRole(org_name, db_name,user_id); if(role == null) { role = roleFinder.orgRole(org_name,user_id); if(role.contains("owner")) { chain.doFilter(req, res); }else { throw new Exception(); } } else if(role.contains("owner") || role.equals("can/write")) { chain.doFilter(req, res); }else { throw new Exception(); } }else if(role.equals("can/write")) { if(request.getRequestURI().contains("/renameTable")) { chain.doFilter(req, res); }else { } }else { throw new Exception(); } }catch(Exception e) { out.write("403.forbidden"); } } }
true
7be719d447ef601c0828445ea2de80eb48d2bda1
Java
endimion/eidas-proxy
/src/main/java/gr/aegean/eidasproxy/utils/EidasUtils.java
UTF-8
3,758
2.203125
2
[]
no_license
/* * 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 gr.aegean.eidasproxy.utils; import eu.eidas.sp.SpAuthenticationResponseData; import eu.eidas.sp.SpEidasSamlTools; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author nikos */ public class EidasUtils { private final static Logger LOG = LoggerFactory.getLogger(EidasUtils.class); private final static Pattern namePattern = Pattern.compile("friendlyName='(.*?)'"); private final static Pattern valuePattern = Pattern.compile("=\\[(.*?)\\]"); public static Map<String, String> parseEidasResponse(String saml, String remoteHost) { Map<String, String> map = new HashMap(); try { SpAuthenticationResponseData data = SpEidasSamlTools.processResponse(saml, remoteHost); Optional<String> error = checkEidasResponseForErrorCode(data.getResponseXML()); if (error.isPresent()) { map.put("error", error.get()); return map; } return parse(data.getResponseXML()); } catch (Exception e) { LOG.error(e.getMessage()); } return map; } public static Map<String, String> parse(String eIDASResponse) throws IndexOutOfBoundsException { // LOG.info("got the eIDAS response:" + eIDASResponse); Map<String, String> result = new HashMap(); String attributePart = eIDASResponse.split("attributes='")[1]; String[] attributesStrings = attributePart.split("AttributeDefinition"); Arrays.stream(attributesStrings).filter(string -> { return string.indexOf("=") > 0; }).filter(string -> { return namePattern.matcher(string).find(); }).forEach(attrString -> { Matcher nameMatcher = namePattern.matcher(attrString); Matcher valueMatcher = valuePattern.matcher(attrString); if (valueMatcher.find() && nameMatcher.find()) { String name = nameMatcher.group(1); char c[] = name.toCharArray(); c[0] = Character.toLowerCase(c[0]); name = new String(c); String value = valueMatcher.group(1); result.put(name, value); if (name.equals("personIdentifier")) { result.put("eid", value); } } }); String loaPart = eIDASResponse.split("levelOfAssurance='")[1].split("',")[0]; result.put("loa", loaPart); return result; } public static Optional<String> checkEidasResponseForErrorCode(String eidasResponse) { if (eidasResponse.contains("202007") || eidasResponse.contains("202004") || eidasResponse.contains("202012") || eidasResponse.contains("202010") || eidasResponse.contains("003002")) { if (eidasResponse.contains("202007") || eidasResponse.contains("202012")) { LOG.debug("---------------202012!!!!!!!"); return Optional.of("Cancelled"); } if (eidasResponse.contains("202004")) { return Optional.of("Cancelled"); } if (eidasResponse.contains("202010")) { return Optional.of("Cancelled"); } if (eidasResponse.contains("003002")) { return Optional.of("ERROR"); } } return Optional.empty(); } }
true
27357ac0d9bdafbdbfe76b1b5fd3bdf58e16528a
Java
vidhis/PracticeQs
/src/com/vidhi/practice/SubClass.java
UTF-8
319
2.53125
3
[]
no_license
package com.vidhi.practice; public class SubClass extends InnerClass{ public void accOut(){ initnum(); super.initnum(); } public void initnum(){ System.out.println("This is subclass initnum"); } public static void main(String args[]){ SubClass c = new SubClass(); c.accOut(); } }
true
3e4a8488936b4fa247552d7df273e7e9e9e6ba98
Java
JCL27/AOW
/Age of war/src/ar/edu/itba/game/backend/upgrades/UnitUpgrade.java
UTF-8
698
2.703125
3
[]
no_license
package ar.edu.itba.game.backend.upgrades; import ar.edu.itba.game.backend.logic.GameStats; import ar.edu.itba.game.backend.logic.Player; import ar.edu.itba.game.backend.units.UnitType; import ar.edu.itba.game.backend.units.UnitsLevels; public class UnitUpgrade extends Upgrade { public UnitUpgrade(Player player) { super(player); this.available = true; this.cost = GameStats.UNIT_UPGRADE_COST; this.multiUpgradable = true; } /** * Upgrades the unit specified by "classType", adding 1 to the current level, afecting the * multiplier of its upgrade rate */ @Override public void applyUpgrade(UnitType type) { UnitsLevels.getInstance().levelUp(this.player, type); } }
true
939d99aa5484d0040f79a2257e2ecda0a4967795
Java
tubadu/Hotels.com
/src/main/java/com/qa/hotels/util/ElementUtil.java
UTF-8
2,543
2.390625
2
[]
no_license
package com.qa.hotels.util; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.Select; import com.qa.hotels.base.BasePage; public class ElementUtil extends BasePage { WebDriver driver; JavaSCripUtil javaScriptUtil; public ElementUtil(WebDriver driver) { this.driver=driver; } public String doGetPageTitle(String title){ try { WebDriverWait wait=new WebDriverWait(driver, 20); wait.until(ExpectedConditions.titleContains(title)); return driver.getTitle(); } catch (Exception e) { System.out.println("some exception got occured while getting the title..."); }return null; }public void SelectbyValue(WebElement element,String value){ Select select=new Select(element); select.selectByValue(value);; } public void waitForElementPresentBy(By locator) { WebDriverWait wait = new WebDriverWait(driver, 20); wait.until(ExpectedConditions.presenceOfElementLocated(locator)); } public WebElement getElement(By locator){ WebElement element=null; try { element=driver.findElement(locator); if (highlightElement.equals("yes")) { javaScriptUtil.flash(element, driver); } } catch (Exception e) { System.out.println("some exception got occured while creating the web element " + locator); }return element; }public void doClick(By locator){ try { getElement(locator).click(); } catch (Exception e) { System.out.println("some exception got occured while clicking the web element " + locator); } }public void doSendKeys(By locator,String value){ try { WebElement element=getElement(locator); element.clear(); element.sendKeys(value); } catch (Exception e) { System.out.println("some exception got occured while entering values in a field " + locator); } }public boolean doIsDisplayed(By locator){ try { return getElement(locator).isDisplayed(); } catch (Exception e) { System.out.println("some exception got occured isEnabled method"); }return false; }public boolean doIsSelected(By locator){ try { return getElement(locator).isSelected(); } catch (Exception e) { System.out.println("some exception got occured isSelected method"); }return false; }public String doGetText(By locator){ try { return getElement(locator).getText(); } catch (Exception e) { System.out.println("some exception got occured while getting text... " + locator); } return null; } }
true
407dfd00105fe922c3c2409ad2e3ee19d5667ed7
Java
zheng-xin/mytank
/src/com/zhengxin/tank/net/msg/MsgType.java
UTF-8
221
1.570313
2
[]
no_license
package com.zhengxin.tank.net.msg; /** * @Auther: zhengxin * @Date: 2020/6/22 - 06 - 22 - 20:50 * @Description: com.zhengxin.tank.net.tank * @version: 1.0 */ public enum MsgType { TankInit,BulletInit,TankMove }
true
4e541c21e4961283b78e4a23de1e74ef3e87784c
Java
aman09031999/tcs_project_banking_application
/src/main/java/com/tcs/project/sash/api/AccountAPI.java
UTF-8
4,478
2.28125
2
[]
no_license
package com.tcs.project.sash.api; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.tcs.project.sash.model.Account; import com.tcs.project.sash.model.AccountType; //import com.tcs.project.sash.model.Transaction; import com.tcs.project.sash.services.AccountService; @RestController @RequestMapping("sash/accounts") public class AccountAPI { @Autowired private AccountService services; @PostMapping("account/{customer_id}/current/{amount}/{message}") public ResponseEntity<String> addMoneyToCurrentAccount(@PathVariable("customer_id") String customer_id, @PathVariable("amount") double amount, @PathVariable("message") String message) { String obj = services.addNewAccount(services.getCustomerById(customer_id), AccountType.current, amount, message); if(obj != null) return new ResponseEntity<String> (obj, HttpStatus.OK); else return new ResponseEntity<String> ("ERROR", HttpStatus.NOT_FOUND); } @PostMapping("account/{customer_id}/saving/{amount}/{message}") public ResponseEntity<String> addMoneyToSavingAccount(@PathVariable("customer_id") String customer_id, @PathVariable("amount") double amount, @PathVariable("message") String message) { String obj = services.addNewAccount(services.getCustomerById(customer_id), AccountType.saving, amount, message); if(obj != null) return new ResponseEntity<String> (obj, HttpStatus.OK); else return new ResponseEntity<String> ("ERROR", HttpStatus.NOT_FOUND); } @GetMapping("account/{account_id}/all") public ResponseEntity<List<Account>> displayCustomerAccount(@PathVariable("account_id") String id) { List<Account> obj = services.getCustomersAllAccounts(id); if(obj != null) return new ResponseEntity<List<Account>> (obj, HttpStatus.OK); else return new ResponseEntity<List<Account>> (new ArrayList<Account>(), HttpStatus.NOT_FOUND); } @GetMapping("account") public ResponseEntity<List<Account>> displayAllAccounts() { List<Account> obj = services.getAllAccounts(); if(obj != null) return new ResponseEntity<List<Account>> (obj, HttpStatus.OK); else return new ResponseEntity<List<Account>> (new ArrayList<Account>(), HttpStatus.NOT_FOUND); } @GetMapping("account/saving") public ResponseEntity<List<Account>> displayAllSavingAccounts() { List<Account> obj = services.getAllSavingAccounts(); if(obj != null) return new ResponseEntity<List<Account>> (obj, HttpStatus.OK); else return new ResponseEntity<List<Account>> (new ArrayList<Account>(), HttpStatus.NOT_FOUND); } @GetMapping("account/current") public ResponseEntity<List<Account>> displayAllCurrentAccounts() { List<Account> obj = services.getAllCurrentAccounts(); if(obj != null) return new ResponseEntity<List<Account>> (obj, HttpStatus.OK); else return new ResponseEntity<List<Account>> (new ArrayList<Account>(), HttpStatus.NOT_FOUND); } @GetMapping("account/transaction/savings-to-current/{customer_id}/{amount}/{message}") public ResponseEntity<String> executeTransactionFromSavingToCurrent(@PathVariable("customer_id") String customer_id, @PathVariable("amount") double amount, @PathVariable("message") String message) { return new ResponseEntity<String> (services.transferMoney(customer_id, AccountType.saving, AccountType.current, amount, message), HttpStatus.OK); } @GetMapping("account/transaction/current-to-savings/{customer_id}/{amount}/{message}") public ResponseEntity<String> executeTransactionFromCurrentToSaving(@PathVariable("customer_id") String customer_id, @PathVariable("amount") double amount, @PathVariable("message") String message) { return new ResponseEntity<String> (services.transferMoney(customer_id, AccountType.current, AccountType.saving, amount, message), HttpStatus.OK); } }
true
e4d00b4859f909df7f9a698fc0278aa484ba08b6
Java
QKGood/watchWeb
/src/main/java/com/watch/controller/BrandController.java
UTF-8
3,108
2.40625
2
[]
no_license
package com.watch.controller; import com.watch.bean.Admin; import com.watch.bean.Brand; import com.watch.common.bean.ComboBox4EasyUI; import com.watch.common.bean.ControllerResult; import com.watch.common.bean.Pager4EasyUI; import com.watch.service.BrandService; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import javax.servlet.http.HttpSession; import java.util.ArrayList; import java.util.List; @Controller @RequestMapping("/brand") public class BrandController { @Resource private BrandService brandService; /*** * 进入品牌管理页面 */ @RequestMapping(value = "brand_page",method = RequestMethod.GET) public String showBrand(Model model, HttpSession session) { Admin ad = (Admin)session.getAttribute("admin"); if (ad != null) { return "admin-page/brand-page"; } else { return "admin-page/admin-login"; } } /*** * 显示所有品牌 */ @ResponseBody @RequestMapping(value="query_pager",method=RequestMethod.GET) public Pager4EasyUI<Brand> queryPager(@Param("page")String page, @Param("rows")String rows){ Pager4EasyUI<Brand> pager = new Pager4EasyUI<Brand>(); pager.setPageNo(Integer.valueOf(page)); pager.setPageSize(Integer.valueOf(rows)); Brand brand = new Brand(); pager = brandService.queryByPagerAndCriteria(pager,brand); return pager; } /*** * 添加品牌 */ @ResponseBody @RequestMapping(value="add_brand",method = RequestMethod.POST) public ControllerResult addBrand(Brand brand){ brandService.add(brand); return ControllerResult.getSuccessResult("添加成功"); } @ResponseBody @RequestMapping(value="update_brand",method = RequestMethod.POST) public ControllerResult updateWatch(Brand brand){ brandService.update(brand); return ControllerResult.getSuccessResult("更新成功"); } @ResponseBody @RequestMapping(value="deleteById",method = RequestMethod.GET) public ControllerResult deleteById(@Param("ids") String ids){ brandService.deleteByIds(ids); return ControllerResult.getSuccessResult("删除成功"); } /* * 下拉列表显示所有品牌 * */ @ResponseBody @RequestMapping(value = "query_brand",method = RequestMethod.GET) public List<ComboBox4EasyUI> brand(){ List<Brand> list = brandService.queryAll(); List<ComboBox4EasyUI> request = new ArrayList<ComboBox4EasyUI>(); for(Brand brand: list){ ComboBox4EasyUI combox = new ComboBox4EasyUI(); combox.setId(String.valueOf(brand.getId())); combox.setText(brand.getDes()); request.add(combox); } return request; } }
true
2ff465c07c3685467c0ca316f02ac3cefda7f64c
Java
jmack-87/SeleniumFramework
/src/test/java/com/ibm/ciclan/Enumerations/HeadSpin/HeadSpin.java
UTF-8
4,396
2.0625
2
[ "MIT" ]
permissive
package com.ibm.ciclan.Enumerations.HeadSpin; public enum HeadSpin { // GENERIC Generic_Text_SauceDemoUrl("Generic.Text.sauceDemoUrl"), // DESKTOP // Module: Login Login_Text_pageTitle("Login.Text.PageTitle"), Login_Locator_TextField_UserName("Login.Locator.TextField.UserName"), Login_Locator_TextField_Password("Login.Locator.TextField.Password"), Login_Locator_Button_Login("Login.Locator.Button.Login"), Login_Locator_Button_DismissError("Login.Locator.Button.DismissError"), Login_Locator_TextContainer_ErrorText("Login.Locator.TextContainer.ErrorText"), Login_Text_InvalidCredentialsError("Login.Text.InvalidCredentialsError"), Login_Text_LockedOutUser("Login.Text.LockedOutError"), Login_Text_UserNameRequired("Login.Text.UserNameRequired"), Login_Text_PasswordRequired("Login.Text.PasswordRequired"), // Module: Header Header_Locator_Button_Menu("Header.Locator.Button.Menu"), Header_Locator_Link_Cart("Header.Locator.Link.Cart"), Header_Locator_TextContainer_CartItemCounter("Header.Locator.TextContainer.CartItemCounter"), Header_Text_CartCount("Header.Text.CartCount"), // Module: Inventory Inventory_Locator_TextContainer_ProductLabel("Inventory.Locator.TextContainer.ProductLabel"), Inventory_Text_ProductLabel("Inventory.Text.ProductLabel"), Inventory_Locator_DropDown_Sort("Inventory.Locator.DropDown.Sort"), Inventory_MultiLocator_Container_InventoryItems("Inventory.MultiLocator.Container.InventoryItems"), Inventory_RelativeLocator_Link_InventoryItemLink("Inventory.RelativeLocator.Link.InventoryItemLink"), Inventory_RelativeLocator_TextContainer_Description("Inventory.RelativeLocator.TextContainer.Description"), Inventory_RelativeLocator_TextContainer_Price("Inventory.RelativeLocator.TextContainer.Price"), Inventory_RelativeLocator_Button_AddToCart("Inventory.RelativeLocator.Button.AddToCart"), // Module: Cart Cart_Locator_TextContainer_SubHeader("Cart.Locator.TextContainer.SubHeader"), Cart_Text_SubHeader("Cart.Text.SubHeader"), Cart_Locator_Button_ContinueShopping("Cart.Locator.Button.ContinueShopping"), Cart_Locator_Button_Checkout("Cart.Locator.Button.Checkout"), Cart_MultiLocator_Container_LineItems("Cart.MultiLocator.Container.LineItems"), Cart_RelativeLocator_TextField_Quantity("Cart.RelativeLocator.TextField.Quantity"), Cart_RelativeLocator_Link_InventoryItemLink("Cart.RelativeLocator.Link.InventoryItemLink"), Cart_RelativeLocator_TextContainer_Description("Cart.RelativeLocator.TextContainer.Description"), Cart_RelativeLocator_TextContainer_Price("Cart.RelativeLocator.TextContainer.Price"), Cart_RelativeLocator_Button_Remove("Cart.RelativeLocator.Button.Remove"), Cart_Text_ItemCount("Cart.Text.ItemCount"), // Module: Checkout, Your Info YourInfo_Locator_TextContainer_SubHeader("YourInfo.Locator.TextContainer.SubHeader"), YourInfo_Text_SubHeader("YourInfo.Text.SubHeader"), YourInfo_Locator_TextField_FirstName(""), YourInfo_Locator_TextField_LastName(""), YourInfo_Locator_TextField_ZipCode(""), YourInfo_Locator_Button_Cancel(""), YourInfo_Locator_Button_Continue(""), YourInfo_Locator_Button_DismissError(""), YourInfo_Locator_TextContainer_ErrorText(""), YourInfo_Text_FirstNameRequired(""), YourInfo_Text_LastNameRequired(""), YourInfo_Text_PostalCodeRequired(""), // Module: Checkout, Overview Overview_Locator_TextContainer_SubHeader("Overview.Locator.TextContainer.SubHeader"), Overview_Text_SubHeader("Overview.Text.SubHeader"), Overview_MultiLocator_Container_LineItems(""), Overview_RealtiveLocator_TextContainer_Quantity(""), Overview_RealtiveLocator_Link_InventoryItemLink(""), Overview_RealtiveLocator_TextContainer_Description(""), Overview_RealtiveLocator_TextContainer_Price(""), Overview_Locator_TextContainer_ItemTotal(""), Overview_Locator_TextContainer_Tax(""), Overview_Locator_TextContainer_Total(""), Overview_Locator_Button_Cancel(""), Overview_Locator_Button_Finish(""), // Module: Finish Finish_Locator_TextContainer_SubHeader(""), Finish_Text_SubHeader(""), Finish_Locator_TextContainer_ThankYou(""), Finish_Text_ThankYou(""), // MOBILE // Module: ??? ; private String str; HeadSpin(String value) { str = value; } @Override public String toString() { return str; } }
true
db192e1e423dc75d66978291a1295105fbc76524
Java
DaanRuiter/Bloody-Glory
/game/net/src/systems/RenderSystem.java
UTF-8
1,134
2.5625
3
[]
no_license
package net.src.systems; import java.util.ArrayList; import net.src.bloodyglory.Engine; import net.src.gameobjects.Entity; import net.src.particles.Particle; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.SlickException; public class RenderSystem extends GameSystem{ public void render(GameContainer container, Graphics g){ for(int i = 0; i < Engine.instant.entities.size(); i++){ Entity entity = Engine.instant.entities.get(i); if(entity.visable){ entity.render(container, g); } } for(int i = 0; i < Engine.instant.particles.size(); i++){ Particle particle = Engine.instant.particles.get(i); particle.render(container, g); if(Engine.renderHitboxes){ g.draw(particle.getHitbox()); } } for(int i = 0; i < Engine.instant.characters.size(); i++){ Entity entity = Engine.instant.characters.get(i); if(entity.visable){ entity.render(container, g); } } } @Override public void update(ArrayList<Entity> entities, GameContainer container, int delta) throws SlickException { // TODO Auto-generated method stub } }
true
7d03e79d3c08ef635e8dbbd52390d56903148f30
Java
sharmilamurali97/JavaOOPS
/ArraY/src/IndexOutOfBondException.java
UTF-8
337
3.046875
3
[]
no_license
public class IndexOutOfBondException { public static void main(String[] args) { System.out.println("Index Out Of Bond Exception"); int i=0; int a[]= {15,25}; // for(i=0;i<=a.length;i++) // { // System.out.println(a[i]); // } // System.out.println(a[5]);//don't have value at a[5] so it form index out of bond } }
true
bce5baedfdccdb58a8d5ff908d68613c7450fddd
Java
HelloWangXiangDong/goshopping
/rest/src/main/java/com/taotao/rest/controller/ItemController.java
UTF-8
1,530
1.9375
2
[]
no_license
package com.taotao.rest.controller; import com.taotao.common.pojo.TaotaoResult; import com.taotao.pojo.TbItem; import com.taotao.pojo.TbItemDesc; import com.taotao.pojo.TbItemParamItem; import com.taotao.rest.service.ItemService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * Created by XDStation on 2016/8/9 0009. */ @Controller public class ItemController { @Autowired private ItemService itemService; /** * 商品基本信息 * @param id * @return */ @RequestMapping("/item/getItem/{id}") @ResponseBody public TaotaoResult getItemById(@PathVariable Long id){ TbItem item = itemService.getItemById(id); return TaotaoResult.ok(item); } /** * 商品详情 * @param itemId * @return */ @RequestMapping("/item/getItemDesc/{itemId}") @ResponseBody public TaotaoResult getItemDesc(@PathVariable Long itemId){ TbItemDesc item = itemService.getItemDesc(itemId); return TaotaoResult.ok(item); } @RequestMapping("/item/getItemParam/{itemId}") @ResponseBody public TaotaoResult getItemParam(@PathVariable Long itemId){ TbItemParamItem itemParam = itemService.getItemParam(itemId); return TaotaoResult.ok(itemParam); } }
true
cc2b8f696134fcc84cd8dbdefcb33d42af41efa3
Java
toczeek/boczek
/app/src/main/java/com/example/toczek/wrumwrum/Utils/providers/Obd/ObdListener.java
UTF-8
114
1.6875
2
[]
no_license
package com.example.toczek.wrumwrum.Utils.providers.Obd; public interface ObdListener { void wasUpdate(); }
true
91ec806180fc878ef91b85af3f545144b0c5f741
Java
lhncbc/skr-semmed
/tags/SemMed_Version_1.0/src/gov/nih/nlm/semmed/rules/RuleParser.java
UTF-8
4,227
2.421875
2
[]
no_license
package gov.nih.nlm.semmed.rules; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RuleParser { private static Pattern setPattern = Pattern.compile("SET\\(\\s*([a-zA-Z0-9_\\.]+)\\s*\\):([^;]*);"); private static Pattern predicatePattern = Pattern.compile("(?:DOESNOT)?EXISTS\\(\\s*([a-zA-Z0-9_\\.]+)\\s*\\):([^;]*);"); private static Pattern rulePattern = Pattern.compile("RULE\\(\\s*([a-zA-Z0-9_\\.]+)\\s*\\):([^;]*);"); private static Pattern subjectPattern = Pattern.compile("subject\\(\\s*([a-zA-Z0-9_\\.]+)\\s*\\)"); private static Pattern objectPattern = Pattern.compile("object\\(\\s*([a-zA-Z0-9_\\.]+)\\s*\\)"); private static Pattern relationPattern = Pattern.compile("predicate\\(\\s*([a-zA-Z0-9_\\.]+)\\s*\\)"); public static Map<String,Predicate> parse(InputStream is) throws IOException{ StringBuffer sb = new StringBuffer(); BufferedReader bfs = new BufferedReader(new InputStreamReader(is)); String s = null; while((s=bfs.readLine())!=null) sb.append(s); Map<String,Set<String>> sets = new HashMap<String,Set<String>>(); Map<String,Predicate> predicates = new HashMap<String,Predicate>(); Map<String,Predicate> rules = new HashMap<String,Predicate>(); Matcher m = setPattern.matcher(sb); while(m.find()){ Set<String> newSet = new HashSet<String>(); String name = m.group(1); String[] elements = m.group(2).split("\\|"); for(String element:elements) //TODO[Alejandro] check for the MINUS thing if (sets.containsKey(element)) newSet.addAll(sets.get(element)); else newSet.add(element); sets.put(name,newSet); } m = predicatePattern.matcher(sb); while(m.find()){ //Set<String> newSet = new HashSet<String>(); String name = m.group(1); String[] elements = m.group(2).split(","); Set<String> subject = null; Set<String> object = null; Set<String> predicate = null; for(int i=0;i<elements.length;i++){ Matcher m1 = subjectPattern.matcher(elements[i]); if (m1.matches()){ subject = sets.get(m1.group(1)); continue; } m1 = objectPattern.matcher(elements[i]); if (m1.matches()){ object = sets.get(m1.group(1)); continue; } m1 = relationPattern.matcher(elements[i]); if (m1.matches()) predicate = sets.get(m1.group(1)); } Predicate p = new Exists(subject==null?new HashSet<String>():subject, predicate==null?new HashSet<String>():predicate, object==null?new HashSet<String>():object); if (m.group(0).startsWith("DOESNOT")){ List<Predicate> lp = new ArrayList<Predicate>(1); lp.add(p); p = new Not().eval(lp); } predicates.put(name,p); } m = rulePattern.matcher(sb); while(m.find()){ String name = m.group(1); String[] dis = m.group(2).split("\\|"); Predicate p = null; if (dis.length==0) throw new Error("Don't know how to handle rules with no antecentes");//p = predicates.get(dis[0]); //MAKES NO SENSE, but this rule has no antecedent anyway else{ List<Predicate> orOperands = new ArrayList<Predicate>(dis.length); for(int i=0;i<dis.length;i++){ String[] con = dis[i].split(","); if (con.length==1) if (predicates.get(con[0].trim())==null) throw new Error("Don't know predicate named '"+con[0]+"'"); else orOperands.add(predicates.get(con[0].trim())); else{ List<Predicate> andOperands = new ArrayList<Predicate>(con.length); for(int j=0;j<con.length;j++) if (predicates.get(con[j].trim())==null) throw new Error("Don't know predicate named '"+con[j]+"'"); else andOperands.add(predicates.get(con[j].trim())); orOperands.add(new And().eval(andOperands)); } } p = new Or().eval(orOperands); } rules.put(name,p); } return rules; } }
true
063bad1e19ac58bfd3e571f9f9a71b90e5835183
Java
Sunilpore/RxJava-Repo
/RxJava/app/src/main/java/com/rxjavaeg1/operators/RangeOperatorActivity.java
UTF-8
2,140
2.34375
2
[]
no_license
package com.rxjavaeg1.operators; import android.content.Context; import android.os.Bundle; import android.os.PersistableBundle; import android.util.AttributeSet; import android.util.Log; import android.view.View; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.rxjavaeg1.R; import com.rxjavaeg1.Task; import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Function; import io.reactivex.functions.Predicate; import io.reactivex.schedulers.Schedulers; public class RangeOperatorActivity extends AppCompatActivity { private String TAG = "RangeOptTag"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Observable <Task> observable = Observable .range(0,9) .subscribeOn(Schedulers.io()) .map(new Function<Integer,Task>() { @Override public Task apply(Integer integer) throws Exception { Log.d(TAG,"onNext: "+Thread.currentThread().getName()); return new Task("New task with priority"+integer,false,integer); } }) .takeWhile(new Predicate<Task>() { @Override public boolean test(Task task) throws Exception { return task.getPriority()<9; } }) .observeOn(AndroidSchedulers.mainThread()); observable.subscribe(new Observer<Task>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(Task task) { Log.d(TAG,"onNext: "+task.getDescription()); } @Override public void onError(Throwable e) { } @Override public void onComplete() { } }); } }
true
bc305f5b6433cf7a6b6027d368472e42d57b4739
Java
higorFischer/Seller
/app/src/main/java/com/team/seller/repositories/UserRepository.java
UTF-8
392
2.28125
2
[]
no_license
package com.team.seller.repositories; import android.util.Log; import com.google.firebase.database.DataSnapshot; import com.team.seller.models.User; public class UserRepository extends BaseRepository<User>{ public UserRepository() { super("User"); } @Override public User ReadSnapShots(DataSnapshot snapshot){ return snapshot.getValue(User.class); } }
true
c17a187a0a05c20272216275fb798d8e4d6eb931
Java
zy1234567/VGSales
/appdomain/src/main/java/com/ztstech/appdomain/user_case/DeleteAnwser.java
UTF-8
754
2.171875
2
[]
no_license
package com.ztstech.appdomain.user_case; import com.ztstech.appdomain.repository.UserRepository; import com.ztstech.appdomain.utils.RetrofitUtils; import com.ztstech.vgmate.data.api.QuestionApi; import com.ztstech.vgmate.data.beans.BaseRespBean; import io.reactivex.Observable; /** * Created by smm on 2017/11/23. * 删除答案 */ public class DeleteAnwser implements UserCase<Observable<BaseRespBean>>{ private QuestionApi api; private String ansid; public DeleteAnwser(String ansid){ this.ansid = ansid; api = RetrofitUtils.createService(QuestionApi.class); } @Override public Observable<BaseRespBean> run() { return api.deleteAnswer(ansid, UserRepository.getInstance().getAuthId()); } }
true
9b963db8ee5ebc6a45c48dee36fd158ae0b2f27f
Java
herskovi/AnagramAppliedMaterial
/src/main/java/com/amat/interfaces/IAnagram.java
UTF-8
169
1.734375
2
[]
no_license
package com.amat.interfaces; import com.amat.consts.Consts; public interface IAnagram { public String isWordExistsInLexicographicalDictionary(String fileName); }
true
77737e68290cd988e317f79d99842b3aadd36882
Java
ioannidis/knowledge-base-information-system
/vks-authentication-service/src/main/java/eu/ioannidis/vks/authenticationservice/models/entities/PasswordResetEntity.java
UTF-8
1,287
2.328125
2
[]
no_license
package eu.ioannidis.vks.authenticationservice.models.entities; import eu.ioannidis.vks.authenticationservice.models.entities.embeddablekeys.PasswordResetKey; import javax.persistence.*; import java.util.Date; @Entity @Table(name = "password_reset") public class PasswordResetEntity { @EmbeddedId private PasswordResetKey passwordResetKey; @Column(name = "active") private boolean active; @Temporal(TemporalType.TIMESTAMP) @Column(name = "expire_at") private Date expireAt; public PasswordResetEntity() { } public PasswordResetEntity(PasswordResetKey passwordResetKey, boolean active, Date expireAt) { this.passwordResetKey = passwordResetKey; this.active = active; this.expireAt = expireAt; } public PasswordResetKey getPasswordResetKey() { return passwordResetKey; } public void setPasswordResetKey(PasswordResetKey passwordResetKey) { this.passwordResetKey = passwordResetKey; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public Date getExpireAt() { return expireAt; } public void setExpireAt(Date expireAt) { this.expireAt = expireAt; } }
true
356d485ca57561a5cddd0ddae59a06ee5567de2e
Java
amanyslamaa/code
/java/ThinkInJava/Operators/src/exp/E03_Aliasing2.java
UTF-8
523
3.140625
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package exp; import java.util.*; import static net.mindview.util.Print.*; /** * * @author Administrator */ public class E03_Aliasing2 { static void fun(Integral a) { a.f = 2222.0f; } public static void main(String[] args) { Integral t = new Integral(); t.f = 0.0f; print("t.f = " + t.f); fun(t); print("t.f = " + t.f); } }
true
5b83ff68c0ee6d46be79c08592c6d67bf63e2da6
Java
Tushar515/TDD-Practice
/src/test/java/com/example/demo/utils/DemoApplicationTests.java
UTF-8
2,847
2.921875
3
[]
no_license
package com.example.demo.utils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.junit.jupiter.api.Assertions.*; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; @SpringBootTest class DemoApplicationTests { StringCalculator stringCalculator; @BeforeEach void setUp() { stringCalculator = new StringCalculator(); } @Test @DisplayName("Ignore An Value More Than 1000") void ignoreAnValueMoreThan1000(){ // Given String str = "2000"; // When int isValid = stringCalculator.Add(str); // Then assertThat(isValid).isEqualTo(0); } @Test @DisplayName("Ignore Values More Than 1000") void ignoreValueMoreThan1000(){ // Given String str = "1,2000,1111,7"; // When int isValid = stringCalculator.Add(str); // Then assertThat(isValid).isEqualTo(8); } @Test @DisplayName("Test Multiple Negative Values") void testMultipleNegativeValues(){ // Given String str = "-1,-2,-3"; try { stringCalculator.Add(str); fail("Should throw an exception if one or more values are negative"); } catch (Exception e){ assertThat(e).isInstanceOf(IllegalArgumentException.class) .hasMessage("Negative values not allowed "+str); } } @Test @DisplayName("Negative Numbers Exception Testing") void testException(){ // Given String str = "-1"; try { stringCalculator.Add(str); fail("Should throw an exception if one or more values are negative"); } catch (Exception e){ assertThat(e).isInstanceOf(IllegalArgumentException.class) .hasMessage("Negative values not allowed "+str); } } @Test @DisplayName("SupportDifferentDelimiters") void supportDifferentDelimiters(){ // Given String test = "//[*][%]\n1*2%3"; // When int isValid = stringCalculator.Add(test); // Then assertThat(isValid).isEqualTo(6); } @Test @DisplayName("RemoveDelimiters") void removeDelimiters(){ // Given String test = "1\n2,3"; // When int isValid = stringCalculator.Add(test); // Then assertThat(isValid).isEqualTo(6); } @Test @DisplayName("AddUnknownAmountOfNumbers") void addUnknownAmountOfNumbers(){ // Given String test = "1,2,3,4,5,6,7,8,9,10"; // When int isValid = stringCalculator.Add(test); // Then assertThat(isValid).isEqualTo(55); } @Test @DisplayName("returnOnlySingleNumber") void returnOnlySingleNumber(){ // Given String test = "1"; // When int isValid = stringCalculator.Add(test); // Then assertThat(isValid).isEqualTo(1); } @Test @DisplayName("returnZero") void returnZero(){ // Given String test = ""; // When int isValid = stringCalculator.Add(test); // Then assertThat(isValid).isEqualTo(0); } }
true
c39ec9b1c49374c89dd4ceefc5b02b8161b2ba26
Java
thiagomuller/make-magic
/src/main/java/com/thiagomuller/hpapi/exception/NoCharacterFoundException.java
UTF-8
186
2.125
2
[]
no_license
package com.thiagomuller.hpapi.exception; public class NoCharacterFoundException extends Exception{ public NoCharacterFoundException(String errorMessage) { super(errorMessage); } }
true
76fa86df865aeffbebfeb63f24f7a84daf1a59b3
Java
sebin-vincent/shopmate
/inventory/src/main/java/com/l7/shopmate/inventory/service/impl/IndexServiceImpl.java
UTF-8
1,127
2.328125
2
[]
no_license
package com.l7.shopmate.inventory.service.impl; import com.l7.shopmate.inventory.entity.Item; import com.l7.shopmate.inventory.model.SkuName; import com.l7.shopmate.inventory.repository.SkuNameIndexRepository; import com.l7.shopmate.inventory.repository.SkuNameSearchRepository; import com.l7.shopmate.inventory.service.IndexingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service public class IndexServiceImpl implements IndexingService { @Autowired SkuNameIndexRepository indexRepository; @Autowired SkuNameSearchRepository searchRepository; @Override public String indexInventoryDatabase() { List<Item> items = indexRepository.findAll(); List<SkuName> skuNames = new ArrayList<>(); for (Item item : items) { SkuName skuName = new SkuName(item.getItemId(), item.getItemName()); skuNames.add(skuName); } searchRepository.saveAll(skuNames); return skuNames.size() + " items indexed."; } }
true
0eb1bd83ef565655758b13a6002d575285ca2b08
Java
nieland22/BirthdayCake
/app/src/main/java/cs301/birthdaycake/CakeController.java
UTF-8
1,281
2.359375
2
[]
no_license
package cs301.birthdaycake; import android.util.Log; import android.view.View; import android.widget.CompoundButton; import android.widget.SeekBar; public class CakeController implements View.OnClickListener, CompoundButton.OnCheckedChangeListener, SeekBar.OnSeekBarChangeListener{ private CakeView myCakeView; private CakeModel diffCakeModel; public CakeController(CakeView diffCakeView) { this.myCakeView=diffCakeView; this.diffCakeModel=diffCakeView.getMyCakeModel(); } public void onClick(View v) { Log.d(null, "Blew Out"); diffCakeModel.isLit = false; myCakeView.invalidate(); } public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(diffCakeModel.hasCandles==true) { diffCakeModel.hasCandles = false; } else { diffCakeModel.hasCandles=true; } myCakeView.invalidate(); } public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { diffCakeModel.numCandles = progress; myCakeView.invalidate(); } public void onStartTrackingTouch(SeekBar seekBar) { } public void onStopTrackingTouch(SeekBar seekBar) { } }
true
2d82c2a1c1318e3e19db11ab4c9815668cfb912a
Java
mlires/IWVG
/doo/src/main/java/designPatterns/exercises/n2_tickets/v1/operations/TicketOperation.java
UTF-8
1,135
2.65625
3
[]
no_license
package designPatterns.exercises.n2_tickets.v1.operations; import designPatterns.exercises.n2_tickets.v1.ticket.CancellationLine; import designPatterns.exercises.n2_tickets.v1.ticket.Footer; import designPatterns.exercises.n2_tickets.v1.ticket.Header; import designPatterns.exercises.n2_tickets.v1.ticket.RepetitionLine; import designPatterns.exercises.n2_tickets.v1.ticket.ReturnLine; import designPatterns.exercises.n2_tickets.v1.ticket.SaleLine; import designPatterns.exercises.n2_tickets.v1.ticket.Ticket; import designPatterns.exercises.n2_tickets.v1.ticket.TicketVisitor; public abstract class TicketOperation implements TicketVisitor { protected Ticket ticket; public void set(Ticket ticket) { this.ticket = ticket; } @Override public void visit(Header head) { } @Override public void visit(SaleLine saleLine) { } @Override public void visit(RepetitionLine repetitionLine) { } @Override public void visit(CancellationLine cancellationLine) { } @Override public void visit(ReturnLine returnLine) { } @Override public void visit(Footer footer) { } }
true
431f95e57745589c5d14fe4cec915d1e54777587
Java
wonwoo/spring5-junit5
/src/test/java/me/wonwoo/spring/SpringTimingExtension.java
UTF-8
414
1.664063
2
[]
no_license
package me.wonwoo.spring; import java.lang.annotation.*; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.test.context.junit.jupiter.SpringExtension; import me.wonwoo.mockito.TimingExtension; @ExtendWith({SpringExtension.class, TimingExtension.class}) @Documented @Inherited @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface SpringTimingExtension { }
true
721320a1ef4b72e80df75b745a1a2eca60aed998
Java
mezeinikolett/Prog2H-zik
/4.f/src/Ital.java
UTF-8
2,063
2.796875
3
[]
no_license
import java.util.Objects; import java.util.Date; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Niki */ import java.util.Date; import java.util.Objects; public class Ital { protected String név; protected String kiszerelés; private static int ár=10; protected Date gyártásiDátum; public static int Euro=300; public Ital(String név, String kiszerelés) { this.név = név; this.kiszerelés = kiszerelés; this.gyártásiDátum=new Date(); } public String getNév() { return név; } public String getKiszerelés() { return kiszerelés; } public static int getÁr() { return ár; } public static int setÁr(){ return ár; } public Date getGyártásiDátum() { return gyártásiDátum; } @Override public String toString() { return getNév()+","+getKiszerelés()+","+getÁr()+"Ft"; } @Override public int hashCode() { int hash = 7; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Ital other = (Ital) obj; if (!Objects.equals(this.név, other.név)) { return false; } if (!Objects.equals(this.kiszerelés, other.kiszerelés)) { return false; } if (!Objects.equals(this.gyártásiDátum, other.gyártásiDátum)) { return false; } return true; } public void setÁr(int ár){ Ital.ár = ár; } public double getAktuálisÁr(){ return ár/Euro; } }
true
d8c568340648e1c8e5c7cd042b04108104ba3a0d
Java
google/guava
/android/guava-testlib/src/com/google/common/collect/testing/testers/ListGetTester.java
UTF-8
1,606
2.390625
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.google.common.collect.testing.testers; import com.google.common.annotations.GwtCompatible; import org.junit.Ignore; /** * A generic JUnit test which tests {@code get()} operations on a list. Can't be invoked directly; * please see {@link com.google.common.collect.testing.ListTestSuiteBuilder}. * * @author Chris Povirk */ @GwtCompatible @Ignore // Affects only Android test runner, which respects JUnit 4 annotations on JUnit 3 tests. public class ListGetTester<E> extends AbstractListTester<E> { public void testGet_valid() { // This calls get() on each index and checks the result: expectContents(createOrderedArray()); } public void testGet_negative() { try { getList().get(-1); fail("get(-1) should throw"); } catch (IndexOutOfBoundsException expected) { } } public void testGet_tooLarge() { try { getList().get(getNumElements()); fail("get(size) should throw"); } catch (IndexOutOfBoundsException expected) { } } }
true
f607f3422e0bce0362e873ef7143306ad70dc364
Java
chaxin/CHTAndroid3x
/app/src/main/java/com/damenghai/chahuitong/model/bean/Area.java
UTF-8
502
1.929688
2
[]
no_license
package com.damenghai.chahuitong.model.bean; /** * Copyright (c) 2015. LiaoPeiKun Inc. All rights reserved. */ public class Area { private String area_id; private String area_name; public String getArea_name() { return area_name; } public void setArea_name(String area_name) { this.area_name = area_name; } public String getArea_id() { return area_id; } public void setArea_id(String area_id) { this.area_id = area_id; } }
true
4278fc3280eba5c6d373dce02272097ed2bf50ec
Java
jonnywei/encrypt-lang
/src/test/java/JsonPTVistorTest.java
UTF-8
1,117
2.234375
2
[ "Apache-2.0" ]
permissive
import com.encryptlang.json.JsonLexer; import com.encryptlang.json.JsonPTVistor; import com.encryptlang.json.ParseTreeJsonParser; import org.junit.Test; public class JsonPTVistorTest { @Test public void testJsonArray(){ String input = "['aaa',444,'ddd']"; JsonLexer jsonLexer = new JsonLexer(input); ParseTreeJsonParser parser = new ParseTreeJsonParser(jsonLexer); ParseTreeJsonParser.ParseTree parseTree = parser.parse(); System.out.println(parseTree.toStringTree()); JsonPTVistor vistor = new JsonPTVistor(); System.out.println(vistor.visit(parseTree)); } @Test public void testJsonNestArray(){ String input = "['aaa',444,'ddd',[333,3432,true,false,null]]"; JsonLexer jsonLexer = new JsonLexer(input); ParseTreeJsonParser parser = new ParseTreeJsonParser(jsonLexer); ParseTreeJsonParser.ParseTree parseTree = parser.parse(); System.out.println(parseTree.toStringTree()); JsonPTVistor vistor = new JsonPTVistor(); System.out.println(vistor.visit(parseTree)); } }
true
dae24379bdd85c4c67f1610caa02f7e639ab15a5
Java
dieterjava/oddjob
/src/java/org/oddjob/logging/log4j/ArchiveAppender.java
UTF-8
1,545
2.5625
3
[ "BSD-2-Clause" ]
permissive
package org.oddjob.logging.log4j; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.Layout; import org.apache.log4j.spi.LoggingEvent; import org.oddjob.logging.LoggingConstants; import org.oddjob.logging.cache.LogArchiverCache; /** * A Log4j appender which logs to LogArchiver. */ public class ArchiveAppender extends AppenderSkeleton implements LoggingConstants { private final LogArchiverCache logArchiver; /** * Create an ArchiveAppender using the given logArchiver and layout. * * @param logArchiver The LogArchiver to archive to. * @param layout The layout to use. */ public ArchiveAppender(LogArchiverCache logArchiver, Layout layout) { this.logArchiver = logArchiver; this.layout = layout; } public void close() { } public void append(LoggingEvent event) { String archive = event.getLoggerName(); if (!logArchiver.hasArchive(archive)) { archive = (String) event.getMDC(MDC_LOGGER); if (!logArchiver.hasArchive(archive)) { return; } } StringBuffer text = new StringBuffer(); text.append(this.layout.format(event)); if (layout.ignoresThrowable()) { String[] s = event.getThrowableStrRep(); if (s != null) { int len = s.length; for (int i = 0; i < len; i++) { text.append(s[i]); text.append(Layout.LINE_SEP); } } } logArchiver.addEvent(archive, Log4jArchiver.convertLevel(event.getLevel()), text.toString()); } public boolean requiresLayout() { return false; } }
true
c5d3cae9df66c5eaa30bed5cc31b81aff9b7c7e7
Java
tarsissantiago/projeto-interdiciplinar
/calculadora/src/br/faccamp/domain/Menos.java
UTF-8
336
2.375
2
[]
no_license
package br.faccamp.domain; public class Menos extends Operacao{ public Menos(String primeiro) { super(primeiro); // TODO Auto-generated constructor stub } @Override public String calcula(String conteudo) { double segundo = new Double(conteudo); guardarValorFixo(segundo); return ((primeiro-getFixo())+""); } }
true
b4cdfc24b925f70be2eb76c0ec5b28cbf42df7d1
Java
sahunikash/Copy2
/Practice/src/ArrayPractice/EqualityOfTwoArray.java
UTF-8
1,218
3
3
[]
no_license
package ArrayPractice; import java.lang.reflect.Array; import java.util.Arrays; import java.util.Scanner; import org.omg.Messaging.SyncScopeHelper; public class EqualityOfTwoArray { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("num of element for 1st array is"); int a = sc.nextInt(); System.out.println("num of elements for second array is"); int b = sc.nextInt(); int A [] = new int[a]; int B [] = new int [b]; for(int i=0;i<a;i++) { A[i]=sc.nextInt(); } System.out.println("-----------"); for(int i =0;i<b;i++) { B[i]=sc.nextInt(); } System.out.println(Arrays.toString(A)); System.out.println(Arrays.toString(B)); Arrays.sort(A); Arrays.sort(B); System.out.println(Arrays.toString(A)); System.out.println(Arrays.toString(B)); System.out.println(Arrays.equals(A, B)); //boolean trueOrNot = true; //if(A==B) //{ // for(int i =0;i<A.length;i++) // { // if(A[i]!=B[i]) // { // trueOrNot =false; // } // // } // }else // { // trueOrNot =false; // } // if(trueOrNot) // { // System.out.println("2 arays are equal"); // } // else { // System.out.println("2 arrays are not equal"); // } // } }
true
8a9171cea6c6c769e72f3d3ab05dc9469b8a6a54
Java
rasebe/MyFirstSeleniumProject
/src/test/java/CompareTest.java
UTF-8
1,979
2.140625
2
[]
no_license
import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class CompareTest { private WebDriver driver; @Before public void initDriver(){ System.setProperty("webdriver.chrome.driver", "resources/chromedriver"); driver = new ChromeDriver(); } @Test public void addToCompare(){ driver.get("http://testfasttrackit.info/selenium-test/"); WebElement vipLink = driver.findElement(By.cssSelector("#nav > ol > li.level0.nav-6.last > a")); vipLink.click(); WebElement addToCompareLink = driver.findElement(By.cssSelector("body > div > div.page > div.main-container.col3-layout > div > div.col-wrapper > div.col-main > div.category-products > ul > li:nth-child(1) > div > div.actions > ul > li:nth-child(2) > a")); addToCompareLink.click(); WebElement addToCompareSecondLink = driver.findElement(By.cssSelector("body > div > div.page > div.main-container.col3-layout > div > div.col-wrapper > div.col-main > div.category-products > ul > li:nth-child(2) > div > div.actions > ul > li:nth-child(2) > a")); addToCompareSecondLink.click(); WebElement compareButton = driver.findElement(By.cssSelector("body > div > div.page > div.main-container.col3-layout > div > div.col-right.sidebar > div.block.block-list.block-compare > div.block-content > div > button > span > span")); Assert.assertTrue(compareButton.isDisplayed()); WebElement compareLink = driver.findElement(By.cssSelector("body > div > div.page > div.main-container.col3-layout > div > div.col-right.sidebar > div.block.block-list.block-compare > div.block-content > div > button > span > span")); compareLink.click(); } @After public void closeDriver(){ driver.quit(); } }
true
e3ff99f22de985f167c615f98f631fed35df2b69
Java
japper96/mybatis_demo
/src/main/java/com/test/mybatis/dao/UserMapper.java
UTF-8
2,236
2.390625
2
[]
no_license
package com.test.mybatis.dao; import com.test.mybatis.pojo.Order; import com.test.mybatis.pojo.OrderUser; import com.test.mybatis.pojo.User; import org.apache.ibatis.annotations.Param; import java.util.List; public interface UserMapper { /** * 登录(直接使用注解指定传入参数名称) * @param userName * @param password * @return */ public User login(@Param("userName") String userName, @Param("password") String password); /** * 根据表名查询用户信息(直接使用注解指定传入参数名称) * @param tableName * @return */ public List<User> queryUserByTableName(@Param("tableName") String tableName); /** * 查询所有用户,如果输入了姓名按照姓名进行模糊查询,如果输入年龄,按照年龄进行查询,如果两者都输入,两个条件都要成立 * @param name * @param age * @return */ List<User> queryUserListByNameAndAge(@Param("name") String name,@Param("age") Integer age); /** * 查询男性用户,如果输入了姓名,则按姓名查询 * @param name * @return */ List<User> queryUserList(@Param("name") String name); /** * 按多个Id查询 * @param ids * @return */ List<User> queryUserListByIds(@Param("ids") String[] ids); public interface OrderMapper { OrderUser queryOrderUserByOrderNumber(@Param("number") String number); } public User queryUserById(String id); public List<User> queryUserAll(); public void insertUser(User user); public void updateUser(User user); public void deleteUser(String id); /** * 根据id删除用户信息 * @param id */ public void deleteUserById(String id); /** * 根据订单号查询订单用户的信息及订单详情 * @param number * @return */ Order queryOrderWithUserAndDetailByOrderNumber(@Param("number") String number); /** * 根据订单号查询订单用户的信息及订单详情及订单详情对应的商品信息 * @param number * @return */ Order queryOrderWithUserAndDetailItemByOrderNumber(@Param("number") String number); }
true
a30e433feaf282305cd70f236b8b8b9f6d67c64e
Java
shanzhaikabi/DataBase
/src/main/java/com/ssh/entity/Shopdiscount.java
UTF-8
1,381
2.390625
2
[]
no_license
package com.ssh.entity; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import java.util.Objects; @Entity public class Shopdiscount { private int id; private int discountType; private String shopId; @Id @Column(name = "id", nullable = false) public int getId() { return id; } public void setId(int id) { this.id = id; } @Basic @Column(name = "discountType", nullable = true, length = 20) public int getDiscountType() { return discountType; } public void setDiscountType(int discountType) { this.discountType = discountType; } @Basic @Column(name = "shopId", nullable = true, length = 20) public String getShopId() { return shopId; } public void setShopId(String shopId) { this.shopId = shopId; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Shopdiscount that = (Shopdiscount) o; return id == that.id && Objects.equals(discountType, that.discountType) && Objects.equals(shopId, that.shopId); } @Override public int hashCode() { return Objects.hash(id, discountType, shopId); } }
true
cc0c13b0eb1f5d9914f3b9ddd53a85bf9445cb84
Java
BBK-PiJ-2015-00/Exercises
/Game of Life/GameOfLife.java
UTF-8
215
2.796875
3
[]
no_license
public class GameOfLife { public State getNextState (State current, int neighbourCount) { if(neighbourCount==2) return current; if(neighbourCount==3) return State.LIVE; return State.DEAD; } }
true
174f671f0f24a873130d240882e448d4069e120f
Java
AndriiStulii/TrustYourSoulGame
/app/src/main/java/com/test/andrewstulii/firstapp/top/PlayersDao.java
UTF-8
811
2.265625
2
[]
no_license
package com.test.andrewstulii.firstapp.top; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by andrewstulii. */ public class PlayersDao extends SQLiteOpenHelper { private static final String DATABASE_NAME = "TrustYourSoul.db"; private static final int DATABASE_VERSION = 1; PlayersDao(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(PlayerContract.PlayerEntry.SQL_CREATE_ENTRIES); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(PlayerContract.PlayerEntry.SQL_DELETE_ENTRIES); onCreate(db); } }
true
c98f75bb0ca70ccb982b6aa997bc30c0cf704628
Java
perlovdinger/gloria1
/Gloria/ProcureMaterialDomain/src/main/java/com/volvo/gloria/procurematerial/d/entities/MaterialHeader.java
UTF-8
6,109
1.828125
2
[]
no_license
package com.volvo.gloria.procurematerial.d.entities; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.PrePersist; import javax.persistence.Table; import javax.persistence.Transient; import javax.persistence.Version; import com.volvo.gloria.procurematerial.c.BuildType; import com.volvo.gloria.procurematerial.d.type.request.RequestType; import com.volvo.gloria.util.persistence.GenericEntity; /** * entity class for Request Header. */ @Entity @Table(name = "MATERIAL_HEADER") public class MaterialHeader implements GenericEntity<Long>, Serializable { private static final long serialVersionUID = -887328674251412783L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "MATERIAL_HEADER_OID") private long materialHeaderOid; @Version private long version; @Enumerated(EnumType.STRING) private RequestType requestType; private String mtrlRequestId; private String referenceId; private String companyCode; private String buildId; private String buildName; @Enumerated(EnumType.STRING) private BuildType buildType; private String materialControllerUserId; private String materialControllerName; private String materialControllerTeam; private boolean active; @Transient private String mcIdToBeAssigned; @OneToOne(cascade = CascadeType.ALL) private MaterialHeaderVersion accepted; private Long firstAssemblyIdSequence; @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "materialHeader") private List<MaterialHeaderVersion> materialHeaderVersions = new ArrayList<MaterialHeaderVersion>(); @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "materialHeader") private List<Material> materials = new ArrayList<Material>(); public long getMaterialHeaderOid() { return materialHeaderOid; } public void setMaterialHeaderOid(long requestHeaderOid) { this.materialHeaderOid = requestHeaderOid; } public long getVersion() { return version; } public void setVersion(long version) { this.version = version; } public String getMtrlRequestId() { return mtrlRequestId; } public void setMtrlRequestId(String mtrlRequestId) { this.mtrlRequestId = mtrlRequestId; } public String getReferenceId() { return referenceId; } public void setReferenceId(String referenceId) { this.referenceId = referenceId; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public String getBuildId() { return buildId; } public void setBuildId(String buildId) { this.buildId = buildId; } public String getCompanyCode() { return companyCode; } public void setCompanyCode(String companyCode) { this.companyCode = companyCode; } public RequestType getRequestType() { return requestType; } public void setRequestType(RequestType requestType) { this.requestType = requestType; } public List<MaterialHeaderVersion> getMaterialHeaderVersions() { return materialHeaderVersions; } public void setMaterialHeaderVersions(List<MaterialHeaderVersion> materialHeaderVersions) { this.materialHeaderVersions = materialHeaderVersions; } public MaterialHeaderVersion getAccepted() { return accepted; } public void setAccepted(MaterialHeaderVersion accepted) { this.accepted = accepted; } public BuildType getBuildType() { return buildType; } public void setBuildType(BuildType buildType) { this.buildType = buildType; } @Override public Long getId() { return materialHeaderOid; } /* * This is expensive to Use! */ public List<Material> getMaterials() { return materials; } public void setMaterials(List<Material> materials) { this.materials = materials; } public String getMaterialControllerUserId() { return materialControllerUserId; } public void setMaterialControllerUserId(String materialControllerUserId) { this.materialControllerUserId = materialControllerUserId; } public String getMaterialControllerName() { return materialControllerName; } public void setMaterialControllerName(String materialControllerName) { this.materialControllerName = materialControllerName; } public String getMaterialControllerTeam() { return materialControllerTeam; } public void setMaterialControllerTeam(String materialControllerTeam) { this.materialControllerTeam = materialControllerTeam; } public String getBuildName() { return buildName; } public void setBuildName(String buildName) { this.buildName = buildName; } public Long getFirstAssemblyIdSequence() { return firstAssemblyIdSequence; } public void setFirstAssemblyIdSequence(Long firstAssemblyIdSequence) { this.firstAssemblyIdSequence = firstAssemblyIdSequence; } public void setMcIdToBeAssigned(String mcIdToBeAssigned) { this.mcIdToBeAssigned = mcIdToBeAssigned; } public String getMcIdToBeAssigned() { return mcIdToBeAssigned; } @PrePersist protected void prePersist() { if (this.getBuildType() != BuildType.FIRSTASSEMBLY) { this.setFirstAssemblyIdSequence(null); } } }
true
263fd3c91bcad77b93da2517598868a261e5515d
Java
igniterealtime/Smack
/smack-extensions/src/main/java/org/jivesoftware/smackx/xdata/provider/DataFormProvider.java
UTF-8
19,513
1.65625
2
[ "Apache-2.0" ]
permissive
/** * * Copyright 2003-2007 Jive Software 2020-2022 Florian Schmaus. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.smackx.xdata.provider; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import java.util.logging.Logger; import javax.xml.namespace.QName; import org.jivesoftware.smack.packet.XmlEnvironment; import org.jivesoftware.smack.parsing.SmackParsingException; import org.jivesoftware.smack.provider.ExtensionElementProvider; import org.jivesoftware.smack.roster.packet.RosterPacket; import org.jivesoftware.smack.roster.provider.RosterPacketProvider; import org.jivesoftware.smack.util.EqualsUtil; import org.jivesoftware.smack.util.HashCode; import org.jivesoftware.smack.xml.XmlPullParser; import org.jivesoftware.smack.xml.XmlPullParserException; import org.jivesoftware.smackx.formtypes.FormFieldRegistry; import org.jivesoftware.smackx.xdata.AbstractMultiFormField; import org.jivesoftware.smackx.xdata.AbstractSingleStringValueFormField; import org.jivesoftware.smackx.xdata.BooleanFormField; import org.jivesoftware.smackx.xdata.FormField; import org.jivesoftware.smackx.xdata.FormFieldChildElement; import org.jivesoftware.smackx.xdata.FormFieldWithOptions; import org.jivesoftware.smackx.xdata.JidMultiFormField; import org.jivesoftware.smackx.xdata.JidSingleFormField; import org.jivesoftware.smackx.xdata.ListMultiFormField; import org.jivesoftware.smackx.xdata.ListSingleFormField; import org.jivesoftware.smackx.xdata.TextSingleFormField; import org.jivesoftware.smackx.xdata.packet.DataForm; import org.jivesoftware.smackx.xdatalayout.packet.DataLayout; import org.jivesoftware.smackx.xdatalayout.provider.DataLayoutProvider; /** * The DataFormProvider parses DataForm packets. * * @author Gaston Dombiak */ public class DataFormProvider extends ExtensionElementProvider<DataForm> { private static final Logger LOGGER = Logger.getLogger(DataFormProvider.class.getName()); public static final DataFormProvider INSTANCE = new DataFormProvider(); @Override public DataForm parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) throws XmlPullParserException, IOException, SmackParsingException { DataForm.Type dataFormType = DataForm.Type.fromString(parser.getAttributeValue("", "type")); DataForm.Builder dataForm = DataForm.builder(dataFormType); String formType = null; DataForm.ReportedData reportedData = null; outerloop: while (true) { XmlPullParser.Event eventType = parser.next(); switch (eventType) { case START_ELEMENT: String name = parser.getName(); String namespace = parser.getNamespace(); XmlEnvironment elementXmlEnvironment = XmlEnvironment.from(parser, xmlEnvironment); switch (name) { case "instructions": dataForm.addInstruction(parser.nextText()); break; case "title": dataForm.setTitle(parser.nextText()); break; case "field": // Note that we parse this form field without any potential reportedData. We only use reportedData // to lookup form field types of fields under <item/>. FormField formField = parseField(parser, elementXmlEnvironment, formType); TextSingleFormField hiddenFormTypeField = formField.asHiddenFormTypeFieldIfPossible(); if (hiddenFormTypeField != null) { if (formType != null) { throw new SmackParsingException("Multiple hidden form type fields"); } formType = hiddenFormTypeField.getValue(); } dataForm.addField(formField); break; case "item": DataForm.Item item = parseItem(parser, elementXmlEnvironment, formType, reportedData); dataForm.addItem(item); break; case "reported": if (reportedData != null) { throw new SmackParsingException("Data form with multiple <reported/> elements"); } reportedData = parseReported(parser, elementXmlEnvironment, formType); dataForm.setReportedData(reportedData); break; // See XEP-133 Example 32 for a corner case where the data form contains this extension. case RosterPacket.ELEMENT: if (namespace.equals(RosterPacket.NAMESPACE)) { dataForm.addExtensionElement(RosterPacketProvider.INSTANCE.parse(parser, null)); } break; // See XEP-141 Data Forms Layout case DataLayout.ELEMENT: if (namespace.equals(DataLayout.NAMESPACE)) { dataForm.addExtensionElement(DataLayoutProvider.parse(parser)); } break; } break; case END_ELEMENT: if (parser.getDepth() == initialDepth) { break outerloop; } break; default: // Catch all for incomplete switch (MissingCasesInEnumSwitch) statement. break; } } return dataForm.build(); } private static FormField parseField(XmlPullParser parser, XmlEnvironment xmlEnvironment, String formType) throws XmlPullParserException, IOException, SmackParsingException { return parseField(parser, xmlEnvironment, formType, null); } private static final class FieldNameAndFormType { private final String fieldName; private final String formType; private FieldNameAndFormType(String fieldName, String formType) { this.fieldName = fieldName; this.formType = formType; } private final HashCode.Cache hashCodeCache = new HashCode.Cache(); @Override public int hashCode() { return hashCodeCache.getHashCode(b -> b.append(fieldName) .append(formType) .build() ); } @Override public boolean equals(Object other) { return EqualsUtil.equals(this, other, (e, o) -> e.append(fieldName, o.fieldName) .append(formType, o.formType) ); } } private static final Set<FieldNameAndFormType> UNKNOWN_FIELDS = new CopyOnWriteArraySet<>(); private static FormField parseField(XmlPullParser parser, XmlEnvironment xmlEnvironment, String formType, DataForm.ReportedData reportedData) throws XmlPullParserException, IOException, SmackParsingException { final int initialDepth = parser.getDepth(); final String fieldName = parser.getAttributeValue("var"); final String label = parser.getAttributeValue("", "label"); FormField.Type type = null; { String fieldTypeString = parser.getAttributeValue("type"); if (fieldTypeString != null) { type = FormField.Type.fromString(fieldTypeString); } } List<FormField.Value> values = new ArrayList<>(); List<FormField.Option> options = new ArrayList<>(); List<FormFieldChildElement> childElements = new ArrayList<>(); boolean required = false; outerloop: while (true) { XmlPullParser.TagEvent eventType = parser.nextTag(); switch (eventType) { case START_ELEMENT: QName qname = parser.getQName(); if (qname.equals(FormField.Value.QNAME)) { FormField.Value value = parseValue(parser); values.add(value); } else if (qname.equals(FormField.Option.QNAME)) { FormField.Option option = parseOption(parser); options.add(option); } else if (qname.equals(FormField.Required.QNAME)) { required = true; } else { FormFieldChildElementProvider<?> provider = FormFieldChildElementProviderManager.getFormFieldChildElementProvider( qname); if (provider == null) { LOGGER.warning("Unknown form field child element " + qname + " ignored"); continue; } FormFieldChildElement formFieldChildElement = provider.parse(parser, XmlEnvironment.from(parser, xmlEnvironment)); childElements.add(formFieldChildElement); } break; case END_ELEMENT: if (parser.getDepth() == initialDepth) { break outerloop; } break; } } // Data forms of type 'result' may contain <reported/> and <item/> elements. If this is the case, then the type // of the <field/>s within the <item/> elements is determined by the information found in <reported/>. See // XEP-0004 § 3.4 and SMACK-902 if (type == null && reportedData != null) { FormField reportedFormField = reportedData.getField(fieldName); if (reportedFormField != null) { type = reportedFormField.getType(); } } if (type == null) { // The field name 'FORM_TYPE' is magic. if (fieldName.equals(FormField.FORM_TYPE)) { type = FormField.Type.hidden; } else { // If no field type was explicitly provided, then we need to lookup the // field's type in the registry. type = FormFieldRegistry.lookup(formType, fieldName); if (type == null) { FieldNameAndFormType fieldNameAndFormType = new FieldNameAndFormType(fieldName, formType); if (!UNKNOWN_FIELDS.contains(fieldNameAndFormType)) { LOGGER.warning("The Field '" + fieldName + "' from FORM_TYPE '" + formType + "' is not registered. Field type is unknown, assuming text-single."); UNKNOWN_FIELDS.add(fieldNameAndFormType); } // As per XEP-0004, text-single is the default form field type, which we use as emergency fallback here. type = FormField.Type.text_single; } } } FormField.Builder<?, ?> builder; switch (type) { case bool: builder = parseBooleanFormField(fieldName, values); break; case fixed: builder = parseSingleKindFormField(FormField.fixedBuilder(fieldName), values); break; case hidden: builder = parseSingleKindFormField(FormField.hiddenBuilder(fieldName), values); break; case jid_multi: JidMultiFormField.Builder jidMultiBuilder = FormField.jidMultiBuilder(fieldName); for (FormField.Value value : values) { jidMultiBuilder.addValue(value); } builder = jidMultiBuilder; break; case jid_single: ensureAtMostSingleValue(type, values); JidSingleFormField.Builder jidSingleBuilder = FormField.jidSingleBuilder(fieldName); if (!values.isEmpty()) { FormField.Value value = values.get(0); jidSingleBuilder.setValue(value); } builder = jidSingleBuilder; break; case list_multi: ListMultiFormField.Builder listMultiBuilder = FormField.listMultiBuilder(fieldName); addOptionsToBuilder(options, listMultiBuilder); builder = parseMultiKindFormField(listMultiBuilder, values); break; case list_single: ListSingleFormField.Builder listSingleBuilder = FormField.listSingleBuilder(fieldName); addOptionsToBuilder(options, listSingleBuilder); builder = parseSingleKindFormField(listSingleBuilder, values); break; case text_multi: builder = parseMultiKindFormField(FormField.textMultiBuilder(fieldName), values); break; case text_private: builder = parseSingleKindFormField(FormField.textPrivateBuilder(fieldName), values); break; case text_single: builder = parseSingleKindFormField(FormField.textSingleBuilder(fieldName), values); break; default: // Should never happen, as we cover all types in the switch/case. throw new AssertionError("Unknown type " + type); } switch (type) { case list_multi: case list_single: break; default: if (!options.isEmpty()) { throw new SmackParsingException("Form fields of type " + type + " must not have options. This one had " + options.size()); } break; } if (label != null) { builder.setLabel(label); } builder.setRequired(required); builder.addFormFieldChildElements(childElements); return builder.build(); } private static FormField.Builder<?, ?> parseBooleanFormField(String fieldName, List<FormField.Value> values) throws SmackParsingException { BooleanFormField.Builder builder = FormField.booleanBuilder(fieldName); ensureAtMostSingleValue(builder.getType(), values); if (values.size() == 1) { FormField.Value value = values.get(0); builder.setValue(value); } return builder; } private static AbstractSingleStringValueFormField.Builder<?, ?> parseSingleKindFormField( AbstractSingleStringValueFormField.Builder<?, ?> builder, List<FormField.Value> values) throws SmackParsingException { ensureAtMostSingleValue(builder.getType(), values); if (values.size() == 1) { String value = values.get(0).getValue().toString(); builder.setValue(value); } return builder; } private static AbstractMultiFormField.Builder<?, ?> parseMultiKindFormField(AbstractMultiFormField.Builder<?, ?> builder, List<FormField.Value> values) { for (FormField.Value value : values) { String rawValue = value.getValue().toString(); builder.addValue(rawValue); } return builder; } private static DataForm.Item parseItem(XmlPullParser parser, XmlEnvironment xmlEnvironment, String formType, DataForm.ReportedData reportedData) throws XmlPullParserException, IOException, SmackParsingException { final int initialDepth = parser.getDepth(); List<FormField> fields = new ArrayList<>(); outerloop: while (true) { XmlPullParser.TagEvent eventType = parser.nextTag(); switch (eventType) { case START_ELEMENT: String name = parser.getName(); switch (name) { case "field": FormField field = parseField(parser, XmlEnvironment.from(parser, xmlEnvironment), formType, reportedData); fields.add(field); break; } break; case END_ELEMENT: if (parser.getDepth() == initialDepth) { break outerloop; } break; } } return new DataForm.Item(fields); } private static DataForm.ReportedData parseReported(XmlPullParser parser, XmlEnvironment xmlEnvironment, String formType) throws XmlPullParserException, IOException, SmackParsingException { final int initialDepth = parser.getDepth(); List<FormField> fields = new ArrayList<>(); outerloop: while (true) { XmlPullParser.TagEvent eventType = parser.nextTag(); switch (eventType) { case START_ELEMENT: String name = parser.getName(); switch (name) { case "field": FormField field = parseField(parser, XmlEnvironment.from(parser, xmlEnvironment), formType); fields.add(field); break; } break; case END_ELEMENT: if (parser.getDepth() == initialDepth) { break outerloop; } break; } } return new DataForm.ReportedData(fields); } public static FormField.Value parseValue(XmlPullParser parser) throws IOException, XmlPullParserException { String value = parser.nextText(); return new FormField.Value(value); } public static FormField.Option parseOption(XmlPullParser parser) throws IOException, XmlPullParserException { int initialDepth = parser.getDepth(); FormField.Option option = null; String label = parser.getAttributeValue("", "label"); outerloop: while (true) { XmlPullParser.TagEvent eventType = parser.nextTag(); switch (eventType) { case START_ELEMENT: String name = parser.getName(); switch (name) { case "value": option = new FormField.Option(label, parser.nextText()); break; } break; case END_ELEMENT: if (parser.getDepth() == initialDepth) { break outerloop; } break; } } return option; } private static void ensureAtMostSingleValue(FormField.Type type, List<FormField.Value> values) throws SmackParsingException { if (values.size() > 1) { throw new SmackParsingException(type + " fields can have at most one value, this one had " + values.size()); } } private static void addOptionsToBuilder(Collection<FormField.Option> options, FormFieldWithOptions.Builder<?> builder) { for (FormField.Option option : options) { builder.addOption(option); } } }
true
559f65bcf362af36fc42b1ce68fade7efc0a7fa3
Java
Salim-Alsaeh/HorizonApp
/app/src/main/java/com/androguro/usb/horizon/app/ValuePairs.java
UTF-8
1,193
2.125
2
[]
no_license
package com.androguro.usb.horizon.app; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; /** * Created by mohamed on 1/7/18. */ public class ValuePairs { public static String getUserLAT(Context context) { SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context); return pref.getString("user_LAT", "0"); } public static void setUserLAT(String key, Context context) { SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor edit = pref.edit(); edit.putString("user_lat", key); edit.apply(); } public static String getUserLNG(Context context) { SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context); return pref.getString("user_lng", null); } public static void setUserLNG(String key, Context context) { SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor edit = pref.edit(); edit.putString("user_lng", key); edit.apply(); } }
true
b9aee9ccb8757b3104ebc82112657224d54612b6
Java
ctec105/Proyecto_JPA-Struts
/src/proyecto/struts/dao/jpa/JPAUtilDAO.java
UTF-8
4,769
2.171875
2
[]
no_license
package proyecto.struts.dao.jpa; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; import proyecto.struts.bean.Area; import proyecto.struts.bean.ClaseEquipo; import proyecto.struts.bean.Especialidad; import proyecto.struts.bean.Estado; import proyecto.struts.bean.Marca; import proyecto.struts.bean.Modelo; import proyecto.struts.bean.Paquetesactividades; import proyecto.struts.bean.Paquetesherramientas; import proyecto.struts.bean.Paquetesmateriales; import proyecto.struts.bean.UtilBean; import proyecto.struts.dao.UtilDAO; public class JPAUtilDAO extends GenericDAOJpa<Long, UtilBean> implements UtilDAO { // EntityManager em = getEntityManager(); @Override public UtilBean getUtil(String table, String id) throws Exception { // TODO Auto-generated method stub return null; } @Override public List<Marca> listMarca() throws Exception { try { Query q = getEntityManager().createQuery("SELECT m FROM Marca m"); return q.getResultList(); } catch (Exception e) { // TODO: handle exception return null; } } @Override public List lista(String table) throws Exception { // TODO Auto-generated method stub return null; } @Override public List<Modelo> listModelo() throws Exception { try { Query q = getEntityManager().createQuery("SELECT m FROM Modelo m"); return q.getResultList(); } catch (Exception e) { // TODO: handle exception return null; } } @Override public List<Modelo> listModelo(String marca) throws Exception { try { System.out.println("idMarca: " + marca); Query q = getEntityManager().createQuery( "SELECT m FROM Modelo m WHERE m.idMarca =?1"); q.setParameter(1, Integer.parseInt(marca)); return q.getResultList(); } catch (Exception e) { // TODO: handle exception return null; } } @Override public Paquetesactividades getActividad(int buscAct) throws Exception { // TODO Auto-generated method stub try { return getEntityManager().find(Paquetesactividades.class, buscAct); } catch (Exception e) { return null; } } @Override public Paquetesherramientas getHerramienta(int buscHer) throws Exception { try { return getEntityManager().find(Paquetesherramientas.class, buscHer); } catch (Exception e) { return null; } } @Override public Paquetesmateriales getMaterial(int buscMat) throws Exception { try { return getEntityManager().find(Paquetesmateriales.class, buscMat); } catch (Exception e) { return null; } } @Override public List<ClaseEquipo> getClasesEquipos() throws Exception { // TODO Auto-generated method stub try { System.out.println("Ingreso a listado de equipos"); Query q = getEntityManager().createQuery( "SELECT m FROM ClaseEquipo m"); return q.getResultList(); } catch (Exception e) { // TODO: handle exception return null; } } @Override public List<Estado> getEstados() throws Exception { try { Query q = getEntityManager().createQuery("SELECT m FROM Estado m"); return q.getResultList(); } catch (Exception e) { // TODO: handle exception return null; } } @Override public List<Especialidad> listEspecialidad() throws Exception { try { Query q = getEntityManager().createQuery( "SELECT m FROM Especialidad m"); return q.getResultList(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); return null; } } @Override public List<Paquetesherramientas> popBucarHerramienta(Paquetesherramientas h) throws Exception { try { Query q = getEntityManager() .createQuery( "SELECT m FROM Paquetesherramientas m WHERE m.descripcion like ?1"); q.setParameter(1, "%" + h.getDescripcion() + "%"); return q.getResultList(); } catch (Exception e) { return null; } } @Override public List<Paquetesactividades> popBuscarActividad(Paquetesactividades a) throws Exception { try { Query q = getEntityManager() .createQuery( "SELECT m FROM Paquetesactividades m WHERE m.descripcion like ?1"); q.setParameter(1, "%" + a.getDescripcion() + "%"); return q.getResultList(); } catch (Exception e) { return null; } } @Override public List<Paquetesmateriales> popBuscarMaterial(Paquetesmateriales m) throws Exception { try { Query q = getEntityManager() .createQuery( "SELECT m FROM Paquetesmateriales m WHERE m.descripcion like ?1"); q.setParameter(1, "%" + m.getDescripcion() + "%"); return q.getResultList(); } catch (Exception e) { return null; } } @Override public Area getArea(int codArea) throws Exception { // TODO Auto-generated method stub try { return getEntityManager().find(Area.class, codArea); } catch (Exception e) { return null; } } }
true
a2926938b6a814e914a3090888a760f5e296c5e1
Java
wtuiawitfk/javaweb
/src/smis/servlet/updateStudentServlet.java
UTF-8
1,122
2.515625
3
[]
no_license
package smis.servlet; import smis.dao.IStudentDao; import smis.dao.impl.StudentDaoImpl; import smis.domain.Student; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/update") public class updateStudentServlet extends HttpServlet { private IStudentDao dao; @Override public void init() throws ServletException { this.dao = new StudentDaoImpl(); } @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=utf-8"); String name = req.getParameter("name"); int age = Integer.parseInt(req.getParameter("age")); Long id = Long.valueOf(req.getParameter("id")); Student stu = new Student(name, age); dao.update(id, stu); req.getRequestDispatcher("/list").forward(req, resp); } }
true
e51b092b4827854669ae3c7a8c13b8e42fafbbd7
Java
LluisAguilar/GCTextToSpeech
/app/src/main/java/com/luis/test/gcspeech/RequestMethods.java
UTF-8
7,416
2.15625
2
[]
no_license
package com.luis.test.gcspeech; import android.content.Context; import android.media.MediaPlayer; import android.util.Log; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.luis.test.gcspeech.gcp.AudioConfig; import com.luis.test.gcspeech.gcp.GCPVoice; import com.luis.test.gcspeech.gcp.Input; import com.luis.test.gcspeech.gcp.VoiceMessage; import com.squareup.okhttp.Callback; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.RequestBody; import java.io.IOException; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class RequestMethods { Context context; private static LanguageListener languageListener; private VoiceMessage mVoiceMessage; private MediaPlayer mMediaPlayer; private int mVoiceLength = -1; public RequestMethods(){} public RequestMethods(Context context){ this.context=context; } public void getLanguages() { new Thread(new Runnable() { @Override public void run() { OkHttpClient okHttpClient = new OkHttpClient(); Request request = new Request.Builder() .url(Config.VOICES_ENDPOINT) .addHeader(Config.API_KEY_HEADER, Config.API_KEY) .build(); try { Response response = okHttpClient.newCall(request).execute(); if (response.isSuccessful()) { languageListener.onLanguageResponse(response.body().string()); } else { throw new IOException(String.valueOf(response.code())); } } catch (IOException IoEx) { IoEx.printStackTrace(); Log.e("response","Error"); } } }).start(); } public void responseToJson(String text) { JsonElement jsonElement = new JsonParser().parse(text); if (jsonElement == null || jsonElement.getAsJsonObject() == null || jsonElement.getAsJsonObject().get("voices").getAsJsonArray() == null) { Log.e("response", "get error json"); return; } JsonObject jsonObject = jsonElement.getAsJsonObject(); JsonArray jsonArray = jsonObject.get("voices").getAsJsonArray(); for (int i = 0; i < jsonArray.size(); i++) { JsonArray jsonArrayLanguage = jsonArray.get(i) .getAsJsonObject().get("languageCodes") .getAsJsonArray(); if (jsonArrayLanguage.get(0) != null) { String language = jsonArrayLanguage.get(0).toString().replace("\"", ""); String name = jsonArray.get(i).getAsJsonObject().get("name").toString().replace("\"", ""); String ssmlGender = jsonArray.get(i).getAsJsonObject().get("ssmlGender").toString().replace("\"", ""); //ESSMLlVoiceGender essmLlVoiceGender = ESSMLlVoiceGender.convert(ssmlGender); int naturalSampleRateHertz = jsonArray.get(i).getAsJsonObject().get("naturalSampleRateHertz").getAsInt(); Log.e("response l", language); Log.e("response n", name); Log.e("response s", ssmlGender); Log.e("response nat", String.valueOf(naturalSampleRateHertz)); } } } public void sendTextForAudio(AudioConfig audioConfig, GCPVoice gcpVoice, String text) { if (audioConfig != null && gcpVoice != null){ mVoiceMessage = new VoiceMessage.Builder() .addParameter(new Input(text)) .addParameter(gcpVoice) .addParameter(audioConfig) .build(); new Thread(runnableSend).start(); }else { Log.e("error","ERROR ocurred"); } } private Runnable runnableSend = new Runnable() { @Override public void run() { Log.d("response", "Message: " + mVoiceMessage.toString()); com.squareup.okhttp.OkHttpClient okHttpClient = new com.squareup.okhttp.OkHttpClient(); RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), mVoiceMessage.toString()); Log.e("responsee",mVoiceMessage.toString()); com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder() .url(Config.SYNTHESIZE_ENDPOINT) .addHeader(Config.API_KEY_HEADER, Config.API_KEY) .addHeader("Content-Type", "application/json; charset=utf-8") .post(body) .build(); okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(com.squareup.okhttp.Request request, IOException e) { Log.e("Error",e.getMessage()); } @Override public void onResponse(com.squareup.okhttp.Response response) throws IOException { if (response != null) { Log.i("response", "onResponse code = " + response.code()); if (response.code() == 200) { String text = response.body().string(); JsonElement jsonElement = new JsonParser().parse(text); JsonObject jsonObject = jsonElement.getAsJsonObject(); if (jsonObject != null) { String json = jsonObject.get("audioContent").toString(); json = json.replace("\"", ""); playAudio(json); return; } } } Log.e("Error","get response fail"); } }); } }; private void playAudio(String base64EncodedString) { try { stopAudio(); String url = "data:audio/mp3;base64," + base64EncodedString; mMediaPlayer = new MediaPlayer(); mMediaPlayer.setDataSource(url); mMediaPlayer.prepare(); mMediaPlayer.start(); } catch (IOException IoEx) { Log.e("response",IoEx.toString()); } } public void stopAudio() { if (mMediaPlayer != null && mMediaPlayer.isPlaying()) { mMediaPlayer.stop(); mMediaPlayer.reset(); mVoiceLength = -1; } } public void resumeAudio() { if (mMediaPlayer != null && !mMediaPlayer.isPlaying() && mVoiceLength != -1) { mMediaPlayer.seekTo(mVoiceLength); mMediaPlayer.start(); } } public void pauseAudio() { if (mMediaPlayer != null && mMediaPlayer.isPlaying()) { mMediaPlayer.pause(); mVoiceLength = mMediaPlayer.getCurrentPosition(); } } public interface LanguageListener{ void onLanguageResponse(String text); } public void getLanguagesResponse(LanguageListener languageListener){ this.languageListener=languageListener; } }
true
a27603c71022e98b57c0e68bae39b06b8d2f25dc
Java
cash2one/fmps
/trunk/fmps-web/src/main/java/cn/com/fubon/fo/repairplatform/entity/WeixinRepairPlatform.java
UTF-8
1,786
1.828125
2
[]
no_license
package cn.com.fubon.fo.repairplatform.entity; import java.sql.Timestamp; import javax.persistence.Entity; import javax.persistence.Table; import org.jeecgframework.core.common.entity.IdEntity; @Entity @Table(name = "weixin_repair_platform") public class WeixinRepairPlatform extends IdEntity { private String province; // 省份 private String city; // 市 private String county; // 区县 private Timestamp createDate; // 创建时间 private String name; // 维修厂名称 private String address; // 维修厂地址 private String Telephone; // 联系电话 private String longitude; // 经度 private String latitude; // 纬度 public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getCounty() { return county; } public void setCounty(String county) { this.county = county; } public Timestamp getCreateDate() { return createDate; } public void setCreateDate(Timestamp createDate) { this.createDate = createDate; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getTelephone() { return Telephone; } public void setTelephone(String telephone) { Telephone = telephone; } public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } }
true
066b117e1308793ec5e9d02d9fd5806e932cd2e9
Java
dheeraj9198/DVideoConverter
/src/main/java/VideoConverter/App.java
UTF-8
1,476
2.3125
2
[]
no_license
//mvn com.zenjava:javafx-maven-plugin:2.0:fix-classpath package VideoConverter; import javafx.application.Application; import javafx.stage.Stage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import np.dheeraj.sachan.transcoder.*; public class App extends Application { private static final Logger logger = LoggerFactory.getLogger(App.class); private TranscoderController transcoderController; @Override public void start(Stage primaryStage) throws Exception { logger.info("---------------------------------------------------------------------"); logger.info("-------------------- App started ------------------------------------"); logger.info("---------------------------------------------------------------------"); primaryStage.resizableProperty().setValue(Boolean.FALSE); transcoderController = new TranscoderController(); transcoderController.redirectHome(primaryStage); } @Override public void stop() { logger.info("Window Closed ,stopping running session"); transcoderController.onWindowClosed(); logger.info("---------------------------------------------------------------------"); logger.info("-------------------- App stopped ------------------------------------"); logger.info("---------------------------------------------------------------------"); } public static void main(String[] args) { launch(args); } }
true
992280b18a6a67db155f5328821447566e02ea9d
Java
eabyshev/base
/management/server/core/strategy-manager/strategy-manager-impl/src/main/java/io/subutai/core/strategy/impl/StrategyManagerImpl.java
UTF-8
2,684
2.515625
3
[ "Apache-2.0" ]
permissive
package io.subutai.core.strategy.impl; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Strings; import io.subutai.core.strategy.api.ContainerPlacementStrategy; import io.subutai.core.strategy.api.StrategyManager; import io.subutai.core.strategy.api.StrategyNotFoundException; /** * Strategy Manager implementation */ public class StrategyManagerImpl implements StrategyManager { private static final Logger LOG = LoggerFactory.getLogger( StrategyManagerImpl.class ); List<ContainerPlacementStrategy> placementStrategies = Collections.synchronizedList( new ArrayList<ContainerPlacementStrategy>() ); public void destroy() { placementStrategies.clear(); } public synchronized void registerStrategy( ContainerPlacementStrategy containerPlacementStrategy ) { LOG.info( String.format( "Registering container placement strategy: %s", containerPlacementStrategy.getId() ) ); placementStrategies.add( containerPlacementStrategy ); } public synchronized void unregisterStrategy( ContainerPlacementStrategy containerPlacementStrategy ) { if ( containerPlacementStrategy != null ) { LOG.info( String.format( "Unregistering container placement strategy: %s", containerPlacementStrategy.getId() ) ); placementStrategies.remove( containerPlacementStrategy ); } } public List<ContainerPlacementStrategy> getPlacementStrategies() { return placementStrategies; } @Override public ContainerPlacementStrategy findStrategyById( String strategyId ) throws StrategyNotFoundException { ContainerPlacementStrategy placementStrategy = null; for ( int i = 0; i < placementStrategies.size() && placementStrategy == null; i++ ) { if ( strategyId.equals( placementStrategies.get( i ).getId() ) ) { placementStrategy = placementStrategies.get( i ); } } if ( placementStrategy == null ) { throw new StrategyNotFoundException( String.format( "Container placement strategy [%s] not available.", strategyId ) ); } return placementStrategy; } public List<String> getPlacementStrategyTitles() { return this.getPlacementStrategies().stream().filter( n -> !Strings.isNullOrEmpty( n.getId() ) ) .map( ContainerPlacementStrategy::getId ).collect( Collectors.toList() ); } }
true
6677e7fb761793e6ae6e36e0a5fd0f63210568a1
Java
FRCTeamRobohawk3373/FRC_3373_2016
/3373Robohawks2016/src/org/usfirst/frc/team3373/robot/HawkDrive.java
UTF-8
6,156
2.703125
3
[]
no_license
package org.usfirst.frc.team3373.robot; import com.kauailabs.navx.frc.AHRS; import edu.wpi.first.wpilibj.SPI; import edu.wpi.first.wpilibj.smartdashboard.*; public class HawkDrive { AHRS ahrs = new AHRS(SPI.Port.kMXP); static boolean motorDone1 = false; //unused currently for goToDistance static boolean motorDone2 = false; boolean obstacleStraight = false; HawkSuperMotor leftDriveMotorFront = new HawkSuperMotor(1,0,0,0,0,0,.1, -1,-1,-1); HawkSuperMotor leftDriveMotorBack = new HawkSuperMotor(2,0,0,0,0,0,.1, -1,-1,-1); HawkSuperMotor rightDriveMotorFront = new HawkSuperMotor(3,0,0,0,0,0,.1, 1,-1,-1); HawkSuperMotor rightDriveMotorBack= new HawkSuperMotor(4,0,0,0,0,0,.1, 1,-1,-1); public void wheelControl(double leftY, double rightY, boolean turboEnabled, boolean SniperEnabled){ // Acceleration and speed calculation if(leftY >-0.1 && leftY<0.1){ leftY = 0; } if(rightY >-0.1 && rightY<0.1){ rightY = 0; } // System.out.println("rightY: " + rightY); // System.out.println("leftY: " + leftY); leftY = leftY * leftY * leftY; rightY = rightY * rightY * rightY; System.out.println("Regular drive control."); if(SniperEnabled){ leftDriveMotorFront.set((leftY)/4); leftDriveMotorBack.set(leftY/4); // Sets motor speed to the calculated value rightDriveMotorFront.set(rightY/4); rightDriveMotorBack.set(rightY/4); }else if(turboEnabled){ leftDriveMotorFront.set(leftY); leftDriveMotorBack.set(leftY); rightDriveMotorFront.set(rightY); rightDriveMotorBack.set(rightY); }else{ leftDriveMotorFront.set(leftY*.75); leftDriveMotorBack.set(leftY*.75); rightDriveMotorFront.set(rightY*.75); rightDriveMotorBack.set(rightY*.75); } } public void moveStraight(double speed, double standardAngle){ double angle = (ahrs.getAngle())% 360; if(angle <0){ angle+=360; } //adding 360 to the angle to insure a positive value System.out.println("Angle:" + angle); SmartDashboard.putNumber("Given Angle", ahrs.getAngle()); System.out.println(ahrs.getAngle()); SmartDashboard.putNumber("Angle", angle); //if(speed >= 0){ if(angle > standardAngle +.2 && angle < 180){ System.out.println("compensating right"); // wheelControl(-(speed-.2),-(speed),false,false); wheelControl(-(speed-.2),-(speed),false,false); } else if(angle > 180){ System.out.println("compensating left"); //wheelControl(-(speed),-(speed-.2),false,false); wheelControl(-(speed),-(speed-.2),false,false); } else { wheelControl(-speed, -speed, false, false); System.out.println("going straight"); } //} /* else if(speed < 0){ if(angle < standardAngle +2 && angle < -180){ System.out.println("Stopping left"); wheelControl(-(speed+.02) ,-(speed),false,false); } else if(angle < standardAngle - 2 && angle > -180){ System.out.println("Stopping right"); wheelControl(-(speed) ,-(speed+.02),false,false); } else { wheelControl(-speed, -speed, false, false); System.out.println("going straight"); } */ ahrs.free(); } public void turnToXDegrees(double targetAngle){ //45 degrees is 45 to the right, 315 degrees is 45 to the left double currentAngle = Math.abs(ahrs.getAngle() % 360); if(currentAngle <0){ currentAngle+=360; } if(currentAngle < targetAngle-.2 && targetAngle<=180){ wheelControl(-.5,0, false, false); }else if(currentAngle >targetAngle +.2 && targetAngle <180){ wheelControl(0,-.5, false,false); }else if(targetAngle >= 180 && targetAngle+.2 < currentAngle){ wheelControl(0, -.5, false, false); }else if(targetAngle > 180 && targetAngle-.2 >currentAngle){ wheelControl(-.5,0, false,false); }else{ wheelControl(0,0,false, false); } ahrs.free(); } public double getRoll() { double roll = ahrs.getRoll(); return roll; } public double getPitch() { double pitch = ahrs.getPitch(); return pitch; } /* if(targetAngle<180){ if(currentAngle < targetAngle-3){ wheelControl(0, -.5, false, false); } currentAngle < targetAngle-.5 && ((targetAngle >180 && currentAngle <180) || (currentAngle > targetAngle+.5 && targetAngle >180) else if(currentAngle > targetAngle+3){ wheelControl(-.5, 0, false, false); } else{ wheelControl(0,0,false,false); } }else{ double newTargetAngle = Math.abs(targetAngle -360); double newCurrentAngle = Math.abs(currentAngle -360); if(newCurrentAngle < newTargetAngle-3){ wheelControl(-.5, 0, false, false); }else if(newCurrentAngle >newTargetAngle+3){ wheelControl(0, -.5, false, false); }else{ wheelControl(0,0,false,false); } } */ /* public static void goDoubleDistance(double distance){ //@param distance = distance to drive... because distance isn't clear enough, apparently if(Robot.motor1.getEncPosition()<Robot.motor1.targetEncoderPos+500 && Robot.motor1.getEncPosition()>Robot.motor1.targetEncoderPos-500){ motorDone1 = true; Robot.motor1.set(0); }else{ Robot.motor1.goDistance(distance); } if(Robot.motor2.getEncPosition()<Robot.motor2.targetEncoderPos+500 && Robot.motor2.getEncPosition()>Robot.motor2.targetEncoderPos-500){ motorDone2 = true; Robot.motor2.set(0); }else{ Robot.motor2.goDistance(distance); } if(motorDone1 && motorDone2){ Robot.goingDistance = false; } } */ }
true
00a2bc27da4745669decfcf23c7d964a319852a7
Java
idanci/fcm_android_test
/app/src/main/java/com/idanci/test/MyService.java
UTF-8
415
1.984375
2
[]
no_license
package com.idanci.test; import android.util.Log; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; public class MyService extends FirebaseMessagingService { public MyService() { } @Override public void onMessageReceived(RemoteMessage remoteMessage) { Log.d("MainActivity", "Message: " + remoteMessage.getFrom()); } }
true
78ffc02ebf182ad84c46bf0926124f676c2fccbb
Java
Hovspian/Calendar
/calendar/src/CalendarModel.java
UTF-8
7,364
3.53125
4
[]
no_license
import java.io.*; import java.util.*; import javax.swing.event.*; /** * Creates a calendar that holds scheduled events. * Model aspect of MVC. */ public class CalendarModel { private DailyEvent selectedDay; private TreeMap<GregorianCalendar, TreeSet<Event>> events; private ArrayList<ChangeListener> listeners; /** * Creates a calendar with events. This * @throws IOException * @throws ClassNotFoundException */ public CalendarModel() throws ClassNotFoundException, IOException { GregorianCalendar calendar = new GregorianCalendar(); listeners = new ArrayList<ChangeListener>(); load(); GregorianCalendar day = new GregorianCalendar(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE)); if (events.get(day) == null) events.put(day, new TreeSet<Event>()); selectedDay = new DailyEvent(day, events.get(day)); } /** * Attaches a listener to this calendar * @param l the ChangeListener to be attached */ public void attach(ChangeListener l) { listeners.add(l); } /** * Notifies all listeners that a change has been made */ private void notifyListeners() { for (ChangeListener c : listeners) c.stateChanged(new ChangeEvent(this)); } /** * Returns the selected day * @return the selected day */ public DailyEvent getSelectedDay() { return selectedDay; } /** * Returns the events loaded in the calendar * @return the events loaded in the calendar */ public TreeMap<GregorianCalendar, TreeSet<Event>> getAllEvents() { return events; } /** * Adds the specified event to the calendar if no conflict exists * @return true if there are no conflicting events and the event is added to the calendar */ public boolean createEvent(Event e) { GregorianCalendar cal = e.getDay(); if (events.keySet().contains(cal)) { TreeSet<Event> tree = events.get(cal); if (!conflictExists(e, tree)) tree.add(e); else return false; } else { events.put(cal, new TreeSet<Event>()); events.get(cal).add(e); } if (selectedDay.getDay().equals(cal)) { this.selectedDay = new DailyEvent(cal, events.get(cal)); notifyListeners(); } return true; } /** * Checks if two events have conflicting times. * @param newEvent The event to be checked * @param scheduledEvents The events already scheduled for that day * @return True if a conflict exists and false otherwise */ private boolean conflictExists(Event newEvent, TreeSet<Event> scheduledEvents) { for (Event scheduledEvent : scheduledEvents) { if (newEvent.getStartTimeCal().compareTo(scheduledEvent.getStartTimeCal()) < 0 && newEvent.getEndTimeCal().compareTo(scheduledEvent.getStartTimeCal()) > 0) return true; else if (newEvent.getStartTimeCal().compareTo(scheduledEvent.getEndTimeCal()) < 0 && newEvent.getEndTimeCal().compareTo(scheduledEvent.getStartTimeCal()) > 0) return true; } return false; } /** * Goes to a specified day on the Gregorian calendar * @param cal the day to go to */ public void goTo(GregorianCalendar cal) { selectedDay = new DailyEvent(cal, events.get(cal)); notifyListeners(); } /** * Goes to the next day on the calendar */ public void nextDay() { GregorianCalendar nextDay = selectedDay.getDay(); nextDay.add(Calendar.DATE, 1); selectedDay = new DailyEvent(nextDay, events.get(nextDay)); notifyListeners(); } /** * Goes to the previous day on the calendar */ public void prevDay() { GregorianCalendar prevDay = selectedDay.getDay(); prevDay.add(Calendar.DATE, -1); selectedDay = new DailyEvent(prevDay, events.get(prevDay)); notifyListeners(); } /** * Goes forward one month on the calendar */ public void nextMonth() { GregorianCalendar nextMonth = selectedDay.getDay(); nextMonth.add(Calendar.MONTH, 1); selectedDay = new DailyEvent(nextMonth, events.get(nextMonth)); notifyListeners(); } /** * Goes backward one month on the calendar */ public void prevMonth() { GregorianCalendar prevMonth = selectedDay.getDay(); prevMonth.add(Calendar.MONTH, -1); selectedDay = new DailyEvent(prevMonth, events.get(prevMonth)); notifyListeners(); } /** * Deletes all scheduled events */ public void deleteAllEvents() { this.events = new TreeMap<GregorianCalendar, TreeSet<Event>>(); selectedDay = new DailyEvent(selectedDay.getDay(), events.get(selectedDay.getDay())); notifyListeners(); } /** * Deletes all scheduled events on a particular day * @param c the day to delete events on */ public void deleteDayEvents(GregorianCalendar c) { events.remove(c); if (selectedDay.getDay().equals(c)) { selectedDay = new DailyEvent(c, events.get(c)); } notifyListeners(); } /** * Deletes a single scheduled event * @param c the day of the event * @param e the event to be deleted */ public void deleteSingleEvent(GregorianCalendar c, Event e) { this.events.get(c).remove(e); notifyListeners(); } /** * Loads a text file events.txt with events from previous uses of MyCalendar. * @throws IOException * @throws ClassNotFoundException */ private void load() throws IOException, ClassNotFoundException { try { ObjectInputStream in = new ObjectInputStream(new FileInputStream("events.txt")); this.events = (TreeMap<GregorianCalendar, TreeSet<Event>>) in.readObject(); in.close(); } catch (FileNotFoundException e) { events = new TreeMap<GregorianCalendar, TreeSet<Event>>(); } } /** * Saves the events on the calendar to a file called events.txt. If such a file does not exist within the directory, it is created. * @throws IOException */ public void save() throws IOException { File theFile = new File("events.txt"); theFile.createNewFile(); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("events.txt", false)); out.writeObject(this.events); out.close(); } /** * A class that holds a day (represented as a GregorianCalendar) and the events scheduled for that day */ static class DailyEvent { private GregorianCalendar day; private TreeSet<Event> events; /** * Creates a day with events * @param day the day, represented by a GregorianCalendar * @param events the events scheduled for the day */ public DailyEvent(GregorianCalendar day, TreeSet<Event> events) { this.day = day; this.events = events; } /** * Returns the day for the DailyEvent * @return the day for the DailyEvent */ public GregorianCalendar getDay() { return day; } /** * Returns the events for this day * @return the events for this day */ public TreeSet<Event> getEvents() { return events; } /** * Returns the date as a String * @return the date as a String */ public String getDate() { String year = ((Integer)day.get(Calendar.YEAR)).toString(); String month = ((Integer)(day.get(Calendar.MONTH) + 1)).toString(); String date = ((Integer)day.get(Calendar.DATE)).toString(); return month + '/' + date + '/' + year; } } }
true
88b43d82968382532ef2bfbe6b97b90a83b51aa1
Java
minsik940908/SimpleJava
/Chapter04/src/chap04/ex04/overload/Main.java
UTF-8
791
3.5
4
[]
no_license
package chap04.ex04.overload; public class Main { public static void main(String[] args) { //overload는 사용자 입장으로 봐야 한다. //overload가 없으면 메서드의 인자값의 갯수나 타입만 변해도 새로운 네이밍이 필요해 진다. //오버로드는 같은 이름의 함수를 여러개 만들 수 있다.(매개변수의 갯수와 데이터타입은 달라야 한다.) //자바는 쓰는 사람 입장에서 쓰기좋게 //모델, 가격, 색상 NoteBook nb1 = new NoteBook("gram",1500000,"흰색"); //모델, 색상 NoteBook nb2 = new NoteBook("gram+","검정"); //모델, 가격 NoteBook nb3 = new NoteBook("ion",1600000); //가격, 색상 //NoteBook nb4 = new NoteBook(1700000,"메탈"); nb1.prin(); nb3.prin(); } }
true
ca2d5f5ed77bdd063b9f7dd065e2741895ea124a
Java
adharmad/java-examples
/src/main/java/com/example/javaexamples/reflection/TryClsLoad.java
UTF-8
1,141
3.4375
3
[]
no_license
package com.example.javaexamples.reflection; import java.lang.reflect.Constructor; import java.lang.reflect.Method; public class TryClsLoad { public static void main(String[] args) { try { String var1 = "true1"; Object objCons = null; Class targetCls = Class.forName("lambda.clsload.TestClass"); System.out.println("Target Class = " + targetCls.getName()); // Initialize method Class[] methodParamTypes = new Class[] { String.class }; Object[] methodParams = new Object[] { var1 }; Method method = targetCls.getMethod("method1", methodParamTypes); // Initialize constructor Object[] constArgs = new Object[] {}; Class[] consParamTypes = new Class[] {}; Constructor cons = targetCls.getConstructor(consParamTypes); objCons = cons.newInstance(constArgs); // Invoke method Object retVal = method.invoke(objCons, methodParams); System.out.println(retVal); //TestClass tc = new TestClass(); //tc.method1("true1"); } catch (Exception e) { e.printStackTrace(); System.out.println("Message = " + e.getMessage()); System.out.println("Cause = " + e.getCause()); } } }
true
605e58f4a44b164086ef6581fa2b29d06f6f76d4
Java
lins4tech/sysautos-api
/src/main/java/com/lins4tech/sysautos/api/entities/Loja.java
UTF-8
2,543
2.1875
2
[ "MIT" ]
permissive
package com.lins4tech.sysautos.api.entities; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Table; @Entity @Table(name = "loja") public class Loja implements Serializable{ private static final long serialVersionUID = -4672634619115171066L; private Long id; private String razaoSocial; private String cnpj; private String endereco; private String estado; private String cidade; private String contato; private Date dataCadastro; private Date dataAtualizacao; @Id @GeneratedValue(strategy=GenerationType.AUTO) public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Column(name = "razao_social", nullable = false) public String getRazaoSocial() { return razaoSocial; } public void setRazaoSocial(String razaoSocial) { this.razaoSocial = razaoSocial; } @Column(name = "cnpj", nullable = false) public String getCnpj() { return cnpj; } public void setCnpj(String cnpj) { this.cnpj = cnpj; } @Column(name = "endereco", nullable = false) public String getEndereco() { return endereco; } public void setEndereco(String endereco) { this.endereco = endereco; } @Column(name = "estado", nullable = false) public String getEstado() { return estado; } public void setEstado(String estado) { this.estado = estado; } @Column(name = "cidade", nullable = false) public String getCidade() { return cidade; } public void setCidade(String cidade) { this.cidade = cidade; } @Column(name = "contato") public String getContato() { return contato; } public void setContato(String contato) { this.contato = contato; } @Column(name = "data_cadastro", nullable = false) public Date getDataCadastro() { return dataCadastro; } public void setDataCadastro(Date dataCadastro) { this.dataCadastro = dataCadastro; } @Column(name = "data_atualizacao", nullable = false) public Date getDataAtualizacao() { return dataAtualizacao; } public void setDataAtualizacao(Date dataAtualizacao) { this.dataAtualizacao = dataAtualizacao; } @PreUpdate public void preUpdate() { dataAtualizacao = new Date(); } @PrePersist public void prePersist() { final Date actualDate = new Date(); dataCadastro = actualDate; dataAtualizacao = actualDate; } }
true
64ff6efe6bce7fb3b805da0c07bdd5520b126934
Java
Pratik1007/Homework
/homework_21_09_2019_pratik/src/GenerateRandomInteger.java
UTF-8
467
3.625
4
[]
no_license
public class GenerateRandomInteger { // 24. Write a Java program to generate random integers in a specific range. public static void main(String[] args) { generate(); } public static void generate(){ System.out.println("Genrating Random Integer Between 1 to 50: \n "); double randomdouble = Math.random(); randomdouble = randomdouble*50+1; int randomInt = (int) randomdouble; System.out.println(randomInt); } }
true
696c0d57e35faf084b4cc73f371a5d5e7b633687
Java
Vladislav-Kisliy/justforfun
/reactor/src/test/java/vladislav/kisliy/jff/reactor/basic/FlatMapTest.java
UTF-8
3,075
2.8125
3
[]
no_license
package vladislav.kisliy.jff.reactor.basic; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import java.time.Duration; import java.util.Set; import java.util.stream.Collectors; @Slf4j public class FlatMapTest { @Test public void flatMap() { Flux<Integer> data = Flux .just(new Pair(1, 300), new Pair(2, 200), new Pair(3, 100)) .flatMap(id -> delayReplyFor(id.id, id.delay)); StepVerifier .create(data) .expectNext(3, 2, 1) .verifyComplete(); } @Test public void flatMap01() { Flux<String> data = Flux .just(new Pair(1, 300), new Pair(2, 200), new Pair(3, 100)) // .flatMap(id -> Flux.just("1", "2", "3", id.toString())); .flatMap(id -> replyWithString(id.id, id.delay)); StepVerifier .create(data) .expectNext("1", "300", "2", "200", "3", "100") .verifyComplete(); } @Test public void concatMap() { Flux<Integer> data = Flux .just(new Pair(1, 300), new Pair(2, 200), new Pair(3, 100)) .concatMap(id -> delayReplyFor(id.id, id.delay)); StepVerifier .create(data) .expectNext(1, 2, 3) .verifyComplete(); } @Test public void switchMapWithLookaheads() { Flux<String> source = Flux .just("re", "rea", "reac", "react", "reactive") .delayElements(Duration.ofMillis(100)) .switchMap(this::lookup); StepVerifier.create(source).expectNext("reactive -> reactive").verifyComplete(); } @Test public void monoAndFlux() { Flux<String> success = Flux.just("Orange", "Apple", "Banana", "Grape", "Strawberry"); Flux<String> erroneous = Flux.just("Banana", "Grape").doOnEach(System.out::println).delayElements(Duration.ofMillis(1000)); Mono<Set<String>> erroneousSet = erroneous.collect(Collectors.toSet()); // Mono<Set<String>> erroneousSet = erroneous.collect(Collectors.toSet()).cache(); Flux<String> filtered = success.filterWhen(v -> erroneousSet.map(s -> !s.contains(v))); StepVerifier.create(filtered).expectNext("Orange", "Apple", "Strawberry").verifyComplete(); } private Flux<Integer> delayReplyFor(Integer i, long delay) { return Flux.just(i) .delayElements(Duration.ofMillis(delay)); } private Flux<String> replyWithString(Integer i, long delay) { return Flux.just(i.toString(), String.valueOf(delay)); } private Flux<String> lookup(String word) { return Flux.just(word + " -> reactive")// .delayElements(Duration.ofMillis(500)); } @AllArgsConstructor static class Pair { private int id; private long delay; } }
true
70433e2a5df7be2d25379737f1a2c73a54b17825
Java
meantg/Java_ToDoNote
/DT To Do/src/DTO/TinhTrangDTO.java
UTF-8
531
2.953125
3
[]
no_license
package DTO; public class TinhTrangDTO implements Comparable<TinhTrangDTO> { private Integer stateID; private String stateName; public TinhTrangDTO(Integer stateID, String stateName) { this.stateID = stateID; this.stateName = stateName; } public Integer getStateID() { return stateID; } public String getStateName() { return stateName; } @Override public int compareTo(TinhTrangDTO o) { return this.getStateID().compareTo(o.getStateID()); } }
true
d2c1560d5b2557ee5f239e163ee64843b32e712e
Java
EsionMa/SFT
/src/main/java/com/wangzhixuan/commons/result/RespResult.java
UTF-8
1,850
2.53125
3
[]
no_license
package com.wangzhixuan.commons.result; public class RespResult<T> { private long st; private long et; private long taking; private String code; private String msg; private T data; public RespResult(){ this.st=System.currentTimeMillis(); } public void getSuccess(T data,String msg){ this.data=data; this.code=ErrorCode.Success.getCode(); this.msg=msg; this.et=System.currentTimeMillis(); } public void getSuccess(T data){ this.data=data; this.code=ErrorCode.Success.getCode(); this.msg=ErrorCode.Success.getMsg(); this.et=System.currentTimeMillis(); } public void getSuccess(){ this.code=ErrorCode.Success.getCode(); this.msg=ErrorCode.Success.getMsg(); this.et=System.currentTimeMillis(); } public static void main(String[] args) { new RespResult<Integer>().getSuccess(); } public void getFail(ErrorCode errorCode){ this.data=null; this.code=errorCode.getCode(); this.msg=errorCode.getMsg(); this.et=System.currentTimeMillis(); } public void getFail(String code,String msg){ this.data=null; this.code=code; this.msg=msg; this.et=System.currentTimeMillis(); } public void getFail(String msg){ this.data=null; this.code="SF7777"; this.msg=msg; this.et=System.currentTimeMillis(); } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getData() { return data; } public void setData(T data) { this.data = data; } public long getSt() { return st; } public void setSt(long st) { this.st = st; } public long getEt() { return et; } public void setEt(long et) { this.et = et; } public long getTaking() { this.taking=this.et-this.st; if(this.taking<0){ taking=0l; } return this.taking; } }
true