text
stringlengths
10
2.72M
package com.hillel.javaElementary.classes.Lesson_4; import com.hillel.javaElementary.classes.Lesson_4.People.Position; import com.hillel.javaElementary.classes.Lesson_4.People.Student; import com.hillel.javaElementary.classes.Lesson_4.NotPeople.*; import com.hillel.javaElementary.classes.Lesson_4.People.Teacher; import java.util.ArrayList; import java.util.GregorianCalendar; public class Main { public static void main(String[] args) { Student student1 = new Student("Oleg","Dolotin", 19, "6.04.051.010.17.02", 2); Student student2 = new Student("Jack","Polo", 21, "6.04.186.010.18.01", 4); Student student3 = new Student("Tom","Kat", 20, "6.04.051.010.17.03", 3); Student student4 = new Student("Kate","Whats", 18, "6.04.051.010.19.01", 1); Student student5 = new Student("Pitter","Parker", 22, "6.04.051.012.17.02", 5); ArrayList<Group> groups = new ArrayList<>(); ArrayList<Student> students = new ArrayList<>(); students.add(student1); students.add(student2); students.add(student3); students.add(student4); students.add(student5); Group group1 = new Group(EDepartment.CSaIT, EFaculty.EI, students, "6.04.051.010.17.02"); Group group2 = new Group(EDepartment.CSaIT, EFaculty.F, students, "6.04.186.010.18.01"); Group group3 = new Group(EDepartment.CSaIT, EFaculty.IER, students, "6.04.051.010.17.03"); Group group4 = new Group(EDepartment.CSaIT, EFaculty.ToFC, students, "6.04.051.010.19.01"); Group group5 = new Group(EDepartment.CSaIT, EFaculty.CaIB, students, "6.04.051.012.17.02"); groups.add(group1); groups.add(group2); groups.add(group3); groups.add(group4); groups.add(group5); ArrayList<Teacher> teachers = new ArrayList<>(); Teacher teacher1 = new Teacher("Bill", "Gates ", 53, 21, Position.phd); Teacher teacher2 = new Teacher("Ilon", "Mask ", 40, 18, Position.headOfDepartment); Teacher teacher3 = new Teacher("Mark", "Tsukerberg", 45, 22, Position.professor); Teacher teacher4 = new Teacher("Nill", "Armstrong", 77, 42, Position.assistantProfessor); Teacher teacher5 = new Teacher("Tom", "Kruz", 50, 25, Position.phd); teachers.add(teacher1); teachers.add(teacher2); teachers.add(teacher3); teachers.add(teacher4); teachers.add(teacher5); Department department1 = new Department(students, groups, EFaculty.EI, EDepartment.CSaIT, teachers); ArrayList<Department> departments = new ArrayList<>(); departments.add(department1); Faculty faculty1 = new Faculty(departments, EFaculty.EI); Room room1 = new Room(320, EDepartment.CSaIT, EFaculty.EI); Room room2 = new Room(418, EDepartment.CSaIT, EFaculty.EI); Room room3 = new Room(115, EDepartment.CSaIT, EFaculty.EI); Room room4 = new Room(410, EDepartment.CSaIT, EFaculty.EI); Room room5 = new Room(223, EDepartment.CSaIT, EFaculty.EI); Lesson lesson1 = new Lesson(group1, teacher1, new GregorianCalendar(2020, 3,2,10,15), "Web", room1); Lesson lesson2 = new Lesson(group2, teacher2, new GregorianCalendar(2020,3,2,12,10), "CMS", room2); Lesson lesson3 = new Lesson(group3, teacher3, new GregorianCalendar(2020,3,2,12,10), "PHP", room2); Lesson lesson4 = new Lesson(group4, teacher4, new GregorianCalendar(2020,3,2,13,55), "CSS", room4); Lesson lesson5 = new Lesson(group5, teacher5, new GregorianCalendar(2020, 3,2,10,15), "JS", room1); Schedule schedule = new Schedule(); schedule.add(lesson1); schedule.add(lesson2); schedule.add(lesson3); schedule.add(lesson4); schedule.add(lesson5); schedule.sortByDateTime(); System.out.println(schedule.printSchedule()); } }
package com.huangg.admin.web.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class HomeController { @RequestMapping(value = "/",method = RequestMethod.GET) public String index(){ return "index"; } @RequestMapping(value = "/validate",method = RequestMethod.GET) public String validate(){ return "validate"; } }
package Menu; import Modele.Firma; import java.util.Scanner; public class MenuZwolnijPracownika { public static class MenuZwolnijPracownikaMetodu { public static Scanner sc = new Scanner(System.in); public static int indeks; public static void Wybierz(int wartosc, Firma firma) { switch (wartosc) { case 1: ZwolnijPodwykonawce(firma); break; case 2: ZwolnijPracownika(firma); break; default: System.out.println("Bledne dane"); break; } } public static void ZwolnijPodwykonawce(Firma firma) { try { String wynik = "Zwolnij: "; for (int i = 0; i < firma.Podwykonawcy.size(); i++) { wynik += "|" + i + "|" + firma.Podwykonawcy.get(i).Wypisz() + "\n"; } MenuWypisz.MenuWypiszMetody.Szablon(wynik); indeks = sc.nextInt(); firma.Podwykonawcy.remove(indeks); firma.IloscPieniedzy -= firma.Podwykonawcy.get(indeks).StawkaMiesieczna; System.out.println("Zwolniles podwykonawce pomyslnie"); } catch (Exception ex) { } } public static void ZwolnijPracownika(Firma firma) { try { String wynik = "Zwolnij: "; for (int i = 0; i < firma.Pracownicy.size(); i++) { wynik += "|" + i + "|" + firma.Pracownicy.get(i).Wypisz() + "\n"; } MenuWypisz.MenuWypiszMetody.Szablon(wynik); indeks = sc.nextInt(); firma.Pracownicy.remove(indeks); firma.IloscPieniedzy -= firma.Pracownicy.get(indeks).StawkaMiesieczna; System.out.println("Zwolniles pracownika pomyslnie"); } catch (Exception ex) { } } } }
package algorithms.strings.compression; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Map; import edu.princeton.cs.algs4.BinaryIn; import edu.princeton.cs.algs4.BinaryOut; import org.junit.Test; /** * Created by Chen Li on 2018/6/18. */ public class CharNodeTest { private HuffmanCompression huffmanCompression = new HuffmanCompression(); @Test public void prefixFreeTrieConstructionTest() throws Exception { String text = "it was the best of times it was the worst of times\n"; CharNode root = huffmanCompression.buildTrie(new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8))); System.out.println(huffmanCompression.compressedBits(root)); } @Test public void name() throws Exception { String text = "AAAEEFG"; InputStream in = new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)); CharNode root = huffmanCompression.buildTrie(in); System.out.println("ok"); } @Test public void builMaptest() throws Exception { String text = "AAAEEFG"; InputStream in = new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)); CharNode root = huffmanCompression.buildTrie(in); Map<Character, String> map = huffmanCompression.buildCharacterMap(root); for (Map.Entry<Character, String> entry : map.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); } } @Test public void compressAndExpandTest() throws Exception { String text = "it was the best of times it was the worst of times\n"; InputStream in1 = new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)); CharNode trie = huffmanCompression.buildTrie(in1); //can not read the same InputStream twice, so create another instance InputStream in = new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)); ByteArrayOutputStream bos = new ByteArrayOutputStream(); huffmanCompression.compress(in, bos, trie); ByteArrayInputStream byteIn = new ByteArrayInputStream(bos.toByteArray()); ByteArrayOutputStream expanded = new ByteArrayOutputStream(); huffmanCompression.expand(byteIn, expanded); System.out.println(expanded.toString(StandardCharsets.UTF_8.name())); } @Test public void codeTest() throws Exception { String text = "AAAEEFG"; InputStream in = new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)); CharNode root = huffmanCompression.buildTrie(in); // ByteArrayOutputStream bos = new ByteArrayOutputStream(); BinaryOut bo = new BinaryOut(bos); huffmanCompression.writeTrie(root, bo); bo.close(); // ByteArrayInputStream byteIn = new ByteArrayInputStream(bos.toByteArray()); BinaryIn bin = new BinaryIn(byteIn); CharNode node = huffmanCompression.readTrie(bin); // System.out.println("ok"); } }
package dev.liambloom.softwareEngineering.chapter16.rotate; import dev.liambloom.softwareEngineering.chapter4.Ask; public abstract class AbstractCircularLL<N extends AbstractCircularLL<N>.Node> { N head; N tail; int size; public static <N extends AbstractCircularLL<N>.Node> void main(AbstractCircularLL<N> list) { Ask.seperator = '?'; //final AbstractCircularLL list = new CircularDoubleLL(Ask.forInt("How long is the list", 0, Integer.MAX_VALUE)); System.out.println(); System.out.println("The numbers are: " + list); char choice = 'a'; do { if (choice == 'a') { System.out.println("(a) Care to rotate"); System.out.println("(b) Quit"); } Ask.seperator = ' '; switch (choice = Character.toLowerCase(Ask.forChar(" Enter a choice:"))) { case 'a': Ask.seperator = '?'; list.rotate(Ask.forInt("What is the rotate value")); System.out.println(" The list is now: " + list); System.out.println(); case 'b': break; default: System.out.println("Please enter either 'a' or 'b'."); } } while (choice != 'b'); } public AbstractCircularLL(final int length) { for (int i = 1; i <= length; i++) add(i); close(); size = length; } protected abstract class Node { protected Integer data; protected N next = null; public Node(Integer data) { this.data = data; } } /** * This adds a new node to the end of this list. It does NOT grantee that * it will remain circular, the new node's {@code next} is not set to * {@code head}. To do this, call {@link #close()}. It also does not change * {@code size}. The size is set in the constructor, and this method should * not be called after the object is initialized. * * @param data the data in the new node */ protected abstract void add(Integer data); /** * This sets {@code tail.next = head}, and anything else necessary to make * this linked list circular */ protected void close() { tail.next = head; } public void rotate(int n) { n = n % size; if (n < 0) n += size * (n / size + 1); N current = tail; for (int i = 0; i < n; i++) current = current.next; tail = current; head = current.next; } @Override public String toString() { StringBuilder builder = new StringBuilder(); N current = head; for (int i = 0; i < size; i++, current = current.next) { if (current != head) builder.append(", "); builder.append(current.data); } return builder.toString(); } }
package baseline; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import static org.junit.jupiter.api.Assertions.*; class Solution40Test { @Test void test_CanDisplay() { List<Solution40> employeeList = new ArrayList<>(); employeeList.add(new Solution40("John", "Johnson ", "Manager ", "2016-12-31")); employeeList.add(new Solution40("Tou", "Xiong ", "Software Engineer ", "2016-10-05")); employeeList.add(new Solution40("Michaela", "Michaelson ", "District Manager ", "2015-12-19")); employeeList.add(new Solution40("Jake", "Jacobson ", "Programmer ", "")); employeeList.add(new Solution40("Jacquelyn", "Jackson ", "DBA ", "")); employeeList.add(new Solution40("Sally", "Weber ", "Web Developer ", "2015-12-18")); assertTrue(employeeList.size() == 6); } }
package cdp.pessoa; import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import cdp.exception.CadastroException; import cdp.exception.ValidacaoException; import cdp.participacao.AlunoGraduando; import cdp.participacao.Participacao; import cdp.participacao.Profissional; /** * * Classe que representa uma Pessoa no sistema. * * @author Yuri Silva * @author Tiberio Gadelha * @author Matheus Henrique * @author Gustavo Victor * */ public class Pessoa implements Serializable{ private String nome; private String cpf; private String email; private List<Participacao> projetosParticipados; public Pessoa(String nome, String cpf, String email) { this.nome = nome; this.cpf = cpf; this.email = email; this.projetosParticipados = new ArrayList<>(); } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getCpf() { return cpf; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } /** * * @param participacao */ public void setParticipacao(Participacao participacao) { this.projetosParticipados.add(participacao); } /** * O metodo ira mostrar todas as participacoes da pessoa. * @return Retorna atraves de string as participacoes. */ public String mostraParticipacoes() { String participacoes = ""; int contador = 0; for(Participacao participacao: projetosParticipados) { if(contador >= 1) { participacoes += ", " + participacao.mostraProjeto(); }else { participacoes += participacao.mostraProjeto(); } contador ++; } return participacoes; } /** * Remove determinada participacao dos projetosParticipados da pessoa. * @param participacaoASerRemovida A participacao que sera removida * @throws CadastroException Lanca excecao se a partipacao nao existir nos projetosParticipados; */ public void removeParticipacao(Participacao participacaoASerRemovida) throws CadastroException { boolean removeu = this.projetosParticipados.remove(participacaoASerRemovida); if(!removeu) { throw new CadastroException("Participacao nao encontrada"); } } /** * Retorna a pontuacao obtida nas participacoes. * Cada pessoa sabe calcular seus pontos de participacao no projeto. * @return A pontuacao obtida nas participacoes efetuadas. */ public double calculaPontuacaoPorParticipacao() { double pontuacao = 0; for(Participacao participacao: this.projetosParticipados) { pontuacao += participacao.geraPontuacaoParticipacao(); } AlunoGraduando.controlePontosPED = 0; AlunoGraduando.controlePontosMonitoria = 0; return pontuacao; } /** * Calcula o total da bolsa de uma pessoa atraves das participacoes. * @return Retorna um double que representa a bolsa. */ public double getValorBolsa() { double bolsa = 0; for(Participacao participacao: this.projetosParticipados) { bolsa += participacao.geraGanhos(); } return bolsa; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.getCpf() == null) ? 0 : this.getCpf().hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pessoa other = (Pessoa) obj; if (this.getCpf() == null) { if (other.getCpf() != null) return false; } else if (!this.getCpf().equals(other.getCpf())) return false; return true; } @Override public String toString() { return this.getNome(); } }
package com.zl.service; import com.zl.pojo.ContractDO; import com.zl.pojo.ContractDTO; import com.zl.pojo.ContractVO; import com.zl.pojo.GardenStuffVO; import com.zl.util.AjaxPutPage; import com.zl.util.AjaxResultPage; import com.zl.util.MessageException; import java.math.BigDecimal; import java.util.List; /** * @program: FruitSales * @classname: ContractService * @description: * @author: 朱林 * @create: 2019-02-05 15:39 **/ public interface ContractService { /** * @Description: 返回所有合同信息 * @Param: [ajaxPutPage] * @return: java.util.List<com.zl.pojo.ContractDO> * @date: 2019/2/5 15:40 */ AjaxResultPage<ContractDTO> listContract(AjaxPutPage<ContractDTO> ajaxPutPage); /** * @Description: 返回合同总数量 * @Param: [] * @return: java.lang.Integer * @Author: ZhuLin * @Date: 2019/2/13 */ Integer getContractCount(); /** * @Description: 返回合同详情 * @Param: [contractId] * @return: com.zl.pojo.ContractVO * @date: 2019/2/8 11:43 */ ContractVO getContractInfo(String contractId); /** * @Description: 返回单个合同的果蔬详情 * @Param: [contractId] * @return: java.util.List<com.zl.pojo.GardenStuffVO> * @Author: ZhuLin * @Date: 2019/2/12 */ List<GardenStuffVO> listGardenStuffInfoByContractID(String contractId); /** * @Description: 删除合同[级联删除合同中间表] * @Param: [id] * @return: void * @Author: ZhuLin * @Date: 2019/2/13 */ void deleteContractByKey(String id) throws MessageException; /** * @Description: 确认签约合同 * @Param: [id] * @return: void * @date: 2019/5/16 15:30 */ void updateContractByCheck(String id,Integer check) throws MessageException; /** * @Description: 返回零售商对应的合同数 * @Param: [dealerid] * @return: java.lang.Integer * @Author: ZhuLin * @Date: 2019/2/15 */ Integer contractCountByDealerID(String dealerid); /** * @Description: 插入合同 * @Param: [contractDO, TCdataId] * @return: void * @date: 2019/5/14 15:57 */ void insertContractAndMiddle(ContractDO contractDO,List<String> TCdataId,List<BigDecimal> TCNumber)throws MessageException; }
package br.com.sergio.app.model.repository.jpa; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import br.com.sergio.app.model.jpa.OperacaoBancaria; @Repository public interface OperacaoBancariaRepository extends JpaRepository<OperacaoBancaria, Integer> { }
package com.expriceit.maserven.entities; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; /** * Created by stalyn on 14/12/2017. */ public interface ConsultaCliente { @GET("MisClientesWS") Call<getCliente> consumeDatosClienteWS(@Query("usuario") String usuario, @Query("identificacion") String identificacion); Call<getCliente> consumeDatosClienteWS(); public class getCliente{ private String codigo; private String identificacion; private String razon_social; private String mensaje; private String codigo_error; public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public String getIdentificacion() { return identificacion; } public void setIdentificacion(String identificacion) { this.identificacion = identificacion; } public String getRazon_social() { return razon_social; } public void setRazon_social(String razon_social) { this.razon_social = razon_social; } public String getMensaje() { return mensaje; } public void setMensaje(String mensaje) { this.mensaje = mensaje; } public String getCodigo_error() { return codigo_error; } public void setCodigo_error(String codigo_error) { this.codigo_error = codigo_error; } } }
/* * 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 analizador; import java.awt.Color; import java.awt.MouseInfo; import java.awt.Point; import java.awt.Toolkit; /** * * @author Cesar */ public class GPDialog extends javax.swing.JDialog { boolean dispo; int x, y, op, puntero; int val; /** * Creates new form ErrorMasm */ public GPDialog(java.awt.Frame parent, boolean modal,boolean disp,boolean cancel) { super(parent, modal); this.setUndecorated(true); initComponents(); dispo = disp; if(cancel){ this.jButton1.setText("Cancel"); this.jButton2.setText("OK"); }else{ this.jButton2.setVisible(false); } this.setLocation(Toolkit.getDefaultToolkit().getScreenSize().width/2-248,Toolkit.getDefaultToolkit().getScreenSize().height/2-81); } public void cambiarColores(Color color1, Color color2){ jPanel3.setBackground(color1); jPanel1.setBackground(color2); } public void codigo(String c,String l){ jTextArea2.setText(c); jLabel1.setText(l); } public void posicionInicial(){ jTextArea2.setCaretPosition(0); } public void cambiarForeground(Color c){ jTextArea2.setForeground(c); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel3 = new javax.swing.JPanel(); jLabel15 = new javax.swing.JLabel(); jLabel14 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea2 = new javax.swing.JTextArea(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jPanel3.setBackground(new java.awt.Color(41, 85, 72)); jPanel3.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseDragged(java.awt.event.MouseEvent evt) { jPanel3MouseDragged(evt); } }); jPanel3.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { jPanel3MousePressed(evt); } }); jLabel15.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/brillabrillacomodiamantenelcielo.png"))); // NOI18N jLabel14.setFont(new java.awt.Font("Caviar Dreams", 0, 14)); // NOI18N jLabel14.setForeground(new java.awt.Color(236, 236, 236)); jLabel14.setText("GPlus Compiler"); jLabel14.setToolTipText(""); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel15, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel14, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel15, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel14, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(3, 3, 3)) ); jPanel1.setBackground(new java.awt.Color(58, 121, 104)); jLabel1.setFont(new java.awt.Font("Caviar Dreams", 0, 18)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("¡Error!"); jTextArea2.setEditable(false); jTextArea2.setColumns(20); jTextArea2.setFont(new java.awt.Font("Lucida Sans", 0, 12)); // NOI18N jTextArea2.setRows(5); jTextArea2.setText("Una o más librerias de Masm32 no están instaladas o se han\nmovido de lugar.\nVerifique la instalación y que exista el directorio C:\\MASM32."); jTextArea2.setFocusable(false); jScrollPane1.setViewportView(jTextArea2); jButton1.setText("OK"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("OK"); jButton2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton2MouseClicked(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 382, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(27, 27, 27)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(48, 48, 48) .addComponent(jLabel1))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jButton2)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(30, 30, 30) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed if(dispo){ this.dispose(); val = 0; }else{ System.exit(0); } }//GEN-LAST:event_jButton1ActionPerformed private void jPanel3MouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel3MouseDragged Point p = MouseInfo.getPointerInfo().getLocation(); this.setLocation(p.x - x, p.y - y); }//GEN-LAST:event_jPanel3MouseDragged private void jPanel3MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel3MousePressed x = evt.getX(); y = evt.getY(); }//GEN-LAST:event_jPanel3MousePressed private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked val = 1; this.dispose(); }//GEN-LAST:event_jButton2MouseClicked /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(GPDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(GPDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(GPDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(GPDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { GPDialog dialog = new GPDialog(new javax.swing.JFrame(), true, false,false); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextArea2; // End of variables declaration//GEN-END:variables }
package Chapter1; /** * Created by Anmol Mago on 05-07-2016. */ public class RotateMatrix_7 { //Question only specifies 90 degrees and not which direction private enum Direction{ left, right } //NxN, N=4 static int[][] image = { {1,0,0,0}, {0,1,0,0}, {0,0,1,0}, {0,0,0,1} }; private static void printImg(int[][] img){ if (img != null){ for(int i = 0; i < img.length;i++){ for (int j = 0; j < img[i].length;j++){ System.out.print(img[i][j]); } System.out.println(); } System.out.println(); } } /* * int top = img[inner][i]; * int left = img[outer-offset][inner]; * int bottom = img[outer][outer-offset]; * int right = img[i][outer]; * */ private static int[][] rotate(int[][] img, Direction direction){ if (img == null || img[0] == null){ return null; } int n = img[0].length; if (direction == Direction.left){ for (int layer = 0; layer < n/2; layer++){ int inner = layer; int outer = n-1-layer; for (int i = inner; i < outer; i++){ int offset = i - inner; int top = img[inner][i]; img[inner][i] = img[i][outer]; img[i][outer] = img[outer][outer-offset]; img[outer][outer-offset] = img[outer-offset][inner]; img[outer-offset][inner] = top; } } }else{ for (int layer = 0; layer < n/2; layer++){ int inner = layer; int outer = n-1-layer; for (int i = inner; i < outer; i++){ int offset = i - inner; int top = img[inner][i]; img[inner][i] = img[outer-offset][inner]; img[outer-offset][inner] = img[outer][outer-offset]; img[outer][outer-offset] = img[i][outer]; img[i][outer] = top; } } } return img; } public static void main(String[] args){ printImg(image); printImg(rotate(image, Direction.right)); printImg(rotate(image, Direction.left)); } }
/* * Copyright 2002-2012 Drew Noakes * * 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. * * More information about this project is available at: * * http://drewnoakes.com/code/exif/ * http://code.google.com/p/metadata-extractor/ */ package com.drew.metadata.icc; import com.drew.lang.ByteArrayReader; import com.drew.metadata.ExtractAppSegmentBytesToFileUtility; import com.drew.metadata.Metadata; import junit.framework.TestCase; import java.io.File; public class IccReaderTest extends TestCase { public void testExtract() throws Exception { String iccSegmentFile = "Tests/com/drew/metadata/icc/iccDataInvalid1.app2bytes"; byte[] app2Bytes = ExtractAppSegmentBytesToFileUtility.read(new File(iccSegmentFile)); // skip first 14 bytes byte[] icc = new byte[app2Bytes.length-14]; System.arraycopy(app2Bytes, 14, icc, 0, app2Bytes.length-14); Metadata metadata = new Metadata(); new IccReader().extract(new ByteArrayReader(icc), metadata); } }
package com.rsmartin.arquitecturamvvm.utils; import android.os.SystemClock; import android.util.ArrayMap; import java.util.concurrent.TimeUnit; /** * Nos permite decidir si podemos solicitar datos del webServices * o nos debemos quedar con los datos de Room. * * Dependemos de Key, si ha pasado más tiempo de ese solicitamos los datos de webservice. * * @param <KEY> clave de tiempo */ public class RateLimiter<KEY> { private ArrayMap<KEY, Long> timestamps = new ArrayMap<>(); private final long timeout; public RateLimiter(int timeout, TimeUnit timeUnit){ this.timeout = timeUnit.toMillis(timeout); } public synchronized boolean shouldFetch(KEY key){ Long lastFetched = timestamps.get(key); //Guardamos por ultima vez cuando solicitamos datos long now = now(); if(lastFetched == null){ //Si nunsca se habia solicitado se guarda timestamps.put(key, now); return true; } if(now - lastFetched > timeout){ //Si hemos sobrepasado el tiempo solicitamos el servicio timestamps.put(key, now); return true; } return false; // si no pasa por los otros return, no neceitamos solicitar al servicio y usamos Room } private long now() { return SystemClock.uptimeMillis();//El tiempo actual } public synchronized void reset(KEY key){ timestamps.remove(key); } }
/* * 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 poo.estacionamiento.ui; import java.math.BigDecimal; import java.util.Calendar; import poo.estacionamiento.AbonoPropietario; import poo.estacionamiento.Propietario; import poo.estacionamiento.dao.AbonosPropietarioDao; import poo.estacionamiento.dao.AbonosPropietarioDaoImpl; import poo.estacionamiento.dao.PropietariosDao; import poo.estacionamiento.dao.PropietariosDaoImpl; /** * * @author joaquinleonelrobles */ public class Main { public static void main (String[] args) { Calendar cal = Calendar.getInstance(); PropietariosDao propietariosDao = new PropietariosDaoImpl(); AbonosPropietarioDao abonosPropietarioDao = new AbonosPropietarioDaoImpl(); // insertamos algunos valores iniciales de propietarios Propietario joaquin = new Propietario("Robles", 34315671, "Mario"); Propietario mario = new Propietario("Luiggi", 34315672, "Mario"); propietariosDao.guardar(mario); propietariosDao.guardar(joaquin); // y de abonos AbonoPropietario abonoJoaquin1 = new AbonoPropietario(cal.getTime(), new BigDecimal(123), 1, new BigDecimal(123), joaquin); AbonoPropietario abonoMario1 = new AbonoPropietario(cal.getTime(), new BigDecimal(321), 2, new BigDecimal(321), joaquin); abonosPropietarioDao.guardar(abonoMario1); abonosPropietarioDao.guardar(abonoJoaquin1); new GestorCobroAbono(propietariosDao, abonosPropietarioDao).run(); } }
/* $Id$ */ package djudge.dservice; import java.util.HashMap; public class DServiceTask { int id; String contestId; String problemId; String languageId; String source; String clientData; String params; public DServiceTask() { params = clientData = contestId = problemId = languageId = source = ""; } public int getID() { return id; } public String getContest() { return contestId; } public String getProblem() { return problemId; } public String getLanguage() { return languageId; } public String getSource() { return source; } public String getClientData() { return clientData; } public DServiceTask(HashMap<String, String> map) { id = Integer.parseInt(map.get("id")); contestId = map.get("contest"); problemId = map.get("problem"); languageId = map.get("language"); source = map.get("source"); clientData = map.get("clientData"); params = map.get("param"); } public HashMap<String, String> toHashMap() { HashMap<String, String> res = new HashMap<String, String>(); res.put("id", "" + id); res.put("contest", contestId); res.put("problem", problemId); res.put("language", languageId); res.put("source", source); res.put("clientData", clientData); res.put("param", params); return res; } public String getParams() { return params; } }
package com.Nine; import static org.junit.Assert.assertEquals; import org.json.JSONException; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import static com.Nine.Const.file;; @RunWith(SpringRunner.class) @SpringBootTest(classes = NineApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class MiscTests { @LocalServerPort private int port; TestRestTemplate restTemplate = new TestRestTemplate(); HttpHeaders headers = new HttpHeaders(); //headers.setContentType(MediaType.APPLICATION_JSON_UTF8); @Test public void testRetrieve() throws JSONException { headers.setContentType(MediaType.APPLICATION_JSON_UTF8); HttpEntity<String> entity = new HttpEntity<String>(file, headers); ResponseEntity<String> response = restTemplate.exchange( createURLWithPort("/"), HttpMethod.POST, entity, String.class); String expected = "{\"response\":[{\"image\":\"http://mybeautifulcatchupservice.com/img/shows/16KidsandCounting1280.jpg\",\"slug\":\"show/16kidsandcounting\",\"title\":\"16 Kids and Counting\"}]}"; assertEquals(expected, response.getBody()); } private String createURLWithPort(String uri) { return "http://localhost:" + port + uri; } }
package br.com.metrocamp.example.sergio.tempo.model; /** * Created by Sergio on 3/5/18. */ public class Clima { //Attributes private String nome; private TipoClima tipoClima; private int temperatura; //Properties public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public TipoClima getTipoClima() { return tipoClima; } public void setTipoClima(TipoClima tipoClima) { this.tipoClima = tipoClima; } public int getTemperatura() { return temperatura; } public void setTemperatura(int temperatura) { this.temperatura = temperatura; } }
package BinaryTree; /* Objective is to print top view of binary tree. * Example: * Current tree: * 1 / \ 2 3 / \ / \ 4 5 6 7 / / 8 9 Top view of tree is : 8 4 2 1 3 7 * * */ import java.util.Stack; class Node { int data; Node left, right; Node(int key) { data = key; left = right = null; } } public class BinaryTreeTopView { Node root; BinaryTreeTopView() { root = null; } BinaryTreeTopView(int key) { root = new Node(key); } void top_view() { top_view(root); } void top_view(Node root) { if(root==null) return; Node temp = root; Stack<Node> stack = new Stack<Node>(); while(temp.left!=null) { stack.push(temp.left); temp = temp.left; } while(!stack.isEmpty()) { temp = stack.pop(); System.out.print(temp.data+" "); } while(root!=null) { System.out.print(root.data+" "); root = root.right; } } public static void main(String[] args) { BinaryTreeTopView binaryTreeTopView = new BinaryTreeTopView(); binaryTreeTopView.root = new Node(1); binaryTreeTopView.root.left = new Node(2); binaryTreeTopView.root.right = new Node(3); binaryTreeTopView.root.left.left = new Node(4); binaryTreeTopView.root.left.right = new Node(5); binaryTreeTopView.root.right.left = new Node(6); binaryTreeTopView.root.right.right = new Node(7); binaryTreeTopView.root.left.left.left = new Node(8); binaryTreeTopView.root.right.right.left= new Node(9); System.out.println("Top view of tree is : "); binaryTreeTopView.top_view(); } }
package com.example.kimnamgil.testapplication.widget; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.example.kimnamgil.testapplication.R; import com.example.kimnamgil.testapplication.data.Person; /** * Created by kimnamgil on 2016. 7. 16.. */ public class PersonViewHolder extends RecyclerView.ViewHolder{ ImageView photoView; TextView nameText,emailText; Person person; public void setPerson(Person person) { this.person = person; photoView.setImageDrawable(person.getPhoto()); nameText.setText(person.getName()); emailText.setText(person.getEmail()); } public Person getPerson() { return person; } public PersonViewHolder(final View itemView) { super(itemView); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(mLisner != null) { mLisner.onClickimage(person,itemView,getAdapterPosition()); } } }); photoView = (ImageView)itemView.findViewById(R.id.person_photo); nameText = (TextView)itemView.findViewById(R.id.name_text); emailText = (TextView)itemView.findViewById(R.id.email_text); } public interface OnphotoClickLisner { public void onClickimage(Person p, View view,int position); } OnphotoClickLisner mLisner; public void setonPhotoClickLisner(OnphotoClickLisner lisner) { mLisner = lisner; } }
/* * 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 m2cci.pi01.cybertheatremodel; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Ltifi */ public class UtilisateurTest { public UtilisateurTest() { } /** * Test of getLogin method, of class Utilisateur. */ @Test public void testGetLogin() { Utilisateur utilisateur1=new Utilisateur("inconnu1", "inconnu_in2", "inconnu", "inconnu", "inconnu@domaine.com"); assertEquals(utilisateur1.getLogin(),"inconnu1"); } /** * Test of getMotDePasse method, of class Utilisateur. */ @Test public void testGetMotDePasse() { Utilisateur utilisateur1=new Utilisateur("inconnu1", "inconnu_in2", "inconnu", "inconnu", "inconnu@domaine.com"); assertEquals(utilisateur1.getMotDePasse(),"inconnu_in2"); } /** * Test of getNom method, of class Utilisateur. */ @Test public void testGetNom() { Utilisateur utilisateur1=new Utilisateur("inconnu1", "inconnu_in2", "inconnu", "inconnu", "inconnu@domaine.com"); assertEquals(utilisateur1.getNom(),"inconnu"); } /** * Test of getPrenom method, of class Utilisateur. */ @Test public void testGetPrenom() { Utilisateur utilisateur1=new Utilisateur("inconnu1", "inconnu_in2", "inconnu", "inconnu", "inconnu@domaine.com"); assertEquals(utilisateur1.getPrenom(),"inconnu"); } /** * Test of getEmail method, of class Utilisateur. */ @Test public void testGetEmail() { Utilisateur utilisateur1=new Utilisateur("inconnu1", "inconnu_in2", "inconnu", "inconnu", "inconnu@domaine.com"); assertEquals(utilisateur1.getEmail(),"inconnu@domaine.com"); } /** * Test of setLogin method, of class Utilisateur. */ @Test public void testSetLogin() { Utilisateur utilisateur1=new Utilisateur("inconnu1", "inconnu_in2", "inconnu", "inconnu", "inconnu@domaine.com"); utilisateur1.setLogin("Philemon2"); assertEquals(utilisateur1.getLogin(),"Philemon2"); } /** * Test of setMotDePasse method, of class Utilisateur. */ @Test public void testSetMotDePasse() { Utilisateur utilisateur1=new Utilisateur("inconnu1", "inconnu_in2", "inconnu", "inconnu", "inconnu@domaine.com"); utilisateur1.setMotDePasse("Philemon123"); assertEquals(utilisateur1.getMotDePasse(),"Philemon123"); } /** * Test of setNom method, of class Utilisateur. */ @Test public void testSetNom() { Utilisateur utilisateur1=new Utilisateur("inconnu1", "inconnu_in2", "inconnu", "inconnu", "inconnu@domaine.com"); utilisateur1.setNom("Giraud"); assertEquals(utilisateur1.getNom(),"Giraud"); } /** * Test of setPrenom method, of class Utilisateur. */ @Test public void testSetPrenom() { Utilisateur utilisateur1=new Utilisateur("inconnu1", "inconnu_in2", "inconnu", "inconnu", "inconnu@domaine.com"); utilisateur1.setPrenom("Philemon"); assertEquals(utilisateur1.getPrenom(),"Philemon"); } /** * Test of setEmail method, of class Utilisateur. */ @Test public void testSetEmail() { Utilisateur utilisateur1=new Utilisateur("inconnu1", "inconnu_in2", "inconnu", "inconnu", "inconnu@domaine.com"); utilisateur1.setEmail("philemon.giraud@gmail.com"); assertEquals(utilisateur1.getEmail(),"philemon.giraud@gmail.com"); } }
package io.quarkus.narayana.interceptor; import io.quarkus.narayana.jta.Rollback; // force a rollback to counter the default @Rollback public class AnnotatedTestException extends Exception { }
package org.netpreserve.urlcanon; import org.junit.Test; import static org.junit.Assert.assertEquals; public class ParserUrlTest { @Test public void testReverseHost() { assertEquals(",", ParsedUrl.reverseHost(new String("")).toString()); assertEquals("x,", ParsedUrl.reverseHost(new String("x")).toString()); assertEquals("z,y,x,", ParsedUrl.reverseHost(new String("x.y.z")).toString()); assertEquals(",z,y,x,", ParsedUrl.reverseHost(new String("x.y.z.")).toString()); assertEquals(",z,y,a.b,", ParsedUrl.reverseHost(new String("a,b.y.z.")).toString()); } @Test public void testSsurtHost() { assertEquals("1.2.3.4", ParsedUrl.ssurtHost(new String("1.2.3.4")).toString()); assertEquals("0x80", ParsedUrl.ssurtHost(new String("0x80")).toString()); assertEquals("z,y,x,", ParsedUrl.ssurtHost(new String("x.y.z")).toString()); } @Test public void testSsurt() { assertEquals("org,example,foo,//81:http@user:pass:/path?query#frag", ParsedUrl.parseUrl("http://user:pass@foo.example.org:81/path?query#frag").ssurt().toString()); } }
package com.huruilei.designpattern.strategy; /** * @author: huruilei * @date: 2019/10/31 * @description: * @return */ public interface QuackBehavior { void quack(); }
package com.company.Net; import com.company.Devices.Device; import java.io.*; import java.net.Socket; import java.nio.charset.Charset; public class TCPConnection { private final Socket socket; private final Thread thread; private final BufferedReader in; private final BufferedWriter out; private final TCPConnectionListener eventListener; private final Device sender; public TCPConnection(TCPConnectionListener eventListener, String ip, int port, Device device) throws IOException { this.eventListener = eventListener; this.socket = new Socket(ip, port); this.sender = device; in = new BufferedReader(new InputStreamReader(socket.getInputStream(), Charset.forName("UTF-8"))); out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), Charset.forName("UTF-8"))); thread = new Thread(new Runnable() { @Override public void run() { try { eventListener.onConnectionReady(TCPConnection.this); while (!thread.isInterrupted()) { String msg = in.readLine(); eventListener.onReceiveString(TCPConnection.this, msg); } } catch (IOException e) { eventListener.onException(TCPConnection.this, e); } finally { eventListener.onDisconnect(TCPConnection.this); } } }); thread.start(); } public TCPConnection(TCPConnectionListener eventListener, Socket socket, Device device) throws IOException { this.eventListener = eventListener; this.socket = socket; this.sender = device; in = new BufferedReader(new InputStreamReader(socket.getInputStream(), Charset.forName("UTF-8"))); out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), Charset.forName("UTF-8"))); thread = new Thread(new Runnable() { @Override public void run() { try { eventListener.onConnectionReady(TCPConnection.this); while (!thread.isInterrupted()) { char[] buffer = new char[4096]; String msg = null; /*int size; while (true) { size = in.read(buffer); msg = new String(buffer, 0, size); if (size == -1) break; }*/ int size = in.read(buffer); msg = new String(buffer, 0, size); eventListener.onReceiveString(TCPConnection.this, msg); /*String msg = in.readLine(); eventListener.onReceiveString(TCPConnection.this, msg);*/ } } catch (IOException e) { eventListener.onException(TCPConnection.this, e); } finally { eventListener.onDisconnect(TCPConnection.this); } } }); thread.start(); } public synchronized void sendString(String value) { try { out.write(value); out.flush(); } catch (IOException e) { eventListener.onException(TCPConnection.this, e); disconnect(); } } public synchronized void disconnect() { thread.interrupt(); try { socket.close(); } catch (IOException e) { eventListener.onException(TCPConnection.this, e); } } public Device getSender() { return sender; } @Override public String toString() { return "TCPConnection: " + socket.getInetAddress() + ": " + socket.getPort(); } }
package com.example.demo.controller; import com.example.demo.model.SysUser; import com.example.demo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Created by HuangYanfei on 2018/8/16. */ @RestController @RequestMapping("/user") public class UserController { @Autowired UserService userService; @RequestMapping("/get") public SysUser getOne() { return userService.getOne(); } }
package com.jgw.supercodeplatform.trace.pojo.certificate; import io.swagger.annotations.ApiModelProperty; import java.util.Date; public class CertificateTemplateField { private Long id; private String templateId; private Integer fieldType; private String fieldText; private Integer fontSize; private String fontWeight; private String textDecoration; private Integer marginLeft; private Integer marginTop; private Integer width; private Integer height; private Integer fieldIndex; private String createId; private Date createTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTemplateId() { return templateId; } public void setTemplateId(String templateId) { this.templateId = templateId == null ? null : templateId.trim(); } public Integer getFieldType() { return fieldType; } public void setFieldType(Integer fieldType) { this.fieldType = fieldType; } public String getFieldText() { return fieldText; } public void setFieldText(String fieldText) { this.fieldText = fieldText == null ? null : fieldText.trim(); } public Integer getFontSize() { return fontSize; } public void setFontSize(Integer fontSize) { this.fontSize = fontSize; } public String getFontWeight() { return fontWeight; } public void setFontWeight(String fontWeight) { this.fontWeight = fontWeight; } public String getTextDecoration() { return textDecoration; } public void setTextDecoration(String textDecoration) { this.textDecoration = textDecoration; } public Integer getMarginLeft() { return marginLeft; } public void setMarginLeft(Integer marginLeft) { this.marginLeft = marginLeft; } public Integer getMarginTop() { return marginTop; } public void setMarginTop(Integer marginTop) { this.marginTop = marginTop; } public Integer getWidth() { return width; } public void setWidth(Integer width) { this.width = width; } public Integer getHeight() { return height; } public void setHeight(Integer height) { this.height = height; } public Integer getFieldIndex() { return fieldIndex; } public void setFieldIndex(Integer fieldIndex) { this.fieldIndex = fieldIndex; } public String getCreateId() { return createId; } public void setCreateId(String createId) { this.createId = createId == null ? null : createId.trim(); } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } }
package dk.jrpe.monitor.db.httpaccess.to; /** * Immutable TO object for HTTP access data. * @author Jörgen Persson */ public class HTTPAccessTO { private final String httpStatus; private final String ipAddress; private final String action; private final String url; private final String date; private final String dateToMinute; private final String dateTime; private final Long requests; public String getHttpStatus() { return httpStatus; } public String getIpAddress() { return ipAddress; } public String getAction() { return action; } public String getUrl() { return url; } public String getDate() { return date; } public String getDateToMinute() { return dateToMinute; } public String getDateTime() { return dateTime; } public Long getRequests() { return requests; } private HTTPAccessTO(Builder builder) { this.httpStatus = builder.httpStatus; this.ipAddress = builder.ipAddress; this.date = builder.date; this.dateToMinute = builder.dateToMinute; this.dateTime = builder.dateTime; this.action = builder.action; this.url = builder.url; this.requests = builder.requests; } public static class Builder{ private String httpStatus; private String ipAddress; private String date; private String dateTime; private String dateToMinute; private Long requests = new Long("0"); private String action = "GET"; private String url = "/"; public Builder setHttpStatus(String httpStatus) { this.httpStatus = httpStatus; return this; } public Builder setIPAdress(String ipAddress) { this.ipAddress = ipAddress; return this; } public Builder setDate(String date) { this.date = date; return this; } public Builder setDateTime(String dateTime) { this.dateTime = dateTime; return this; } public Builder setDateToMinute(String dateToMinute) { this.dateToMinute = dateToMinute; return this; } public Builder setAction(String action) { this.action = action; return this; } public Builder setUrl(String url) { this.url = url; return this; } public Builder setRequests(Long requests) { this.requests = requests; return this; } public HTTPAccessTO build() { return new HTTPAccessTO(this); } } @Override public String toString() { return "HTTPAccessTO{" + "httpStatus=" + httpStatus + ", ipAddress=" + ipAddress + ", action=" + action + ", url=" + url + ", date=" + date + ", dateToMinute=" + dateToMinute + ", dateTime=" + dateTime + ", requests=" + requests + '}'; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((action == null) ? 0 : action.hashCode()); result = prime * result + ((date == null) ? 0 : date.hashCode()); result = prime * result + ((dateTime == null) ? 0 : dateTime.hashCode()); result = prime * result + ((dateToMinute == null) ? 0 : dateToMinute.hashCode()); result = prime * result + ((httpStatus == null) ? 0 : httpStatus.hashCode()); result = prime * result + ((ipAddress == null) ? 0 : ipAddress.hashCode()); result = prime * result + ((requests == null) ? 0 : requests.hashCode()); result = prime * result + ((url == null) ? 0 : url.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; HTTPAccessTO other = (HTTPAccessTO) obj; if (action == null) { if (other.action != null) return false; } else if (!action.equals(other.action)) return false; if (date == null) { if (other.date != null) return false; } else if (!date.equals(other.date)) return false; if (dateTime == null) { if (other.dateTime != null) return false; } else if (!dateTime.equals(other.dateTime)) return false; if (dateToMinute == null) { if (other.dateToMinute != null) return false; } else if (!dateToMinute.equals(other.dateToMinute)) return false; if (httpStatus == null) { if (other.httpStatus != null) return false; } else if (!httpStatus.equals(other.httpStatus)) return false; if (ipAddress == null) { if (other.ipAddress != null) return false; } else if (!ipAddress.equals(other.ipAddress)) return false; if (requests == null) { if (other.requests != null) return false; } else if (!requests.equals(other.requests)) return false; if (url == null) { if (other.url != null) return false; } else if (!url.equals(other.url)) return false; return true; } }
package com.youthlin.example.compiler.linscript.semantic; import lombok.Getter; import lombok.Setter; import java.util.List; import java.util.Objects; /** * 结构体的方法 * 是符号、作用域 * * @author : youthlin.chen @ 2019-09-01 10:04 */ @Getter @Setter public class Method extends AbstractScopedSymbol { private boolean isNative; private IType returnType; private List<IType> parameterType; public Method(String name, IScope parent) { super(name, parent); } public void done() { FunctionType functionType = new FunctionType(); functionType.setReturnType(Objects.requireNonNull(returnType)); functionType.setParameterType(Objects.requireNonNull(parameterType)); setType(functionType); } @Override public Kind getKind() { return Kind.Method; } @Override public String toString() { return "Method " + getSymbolName(); } }
package chribb.mactrac.ui.add; import android.app.Application; import androidx.lifecycle.AndroidViewModel; import java.util.List; import java.util.concurrent.Executors; import chribb.mactrac.data.Favorite; import chribb.mactrac.data.FavoriteDao; import chribb.mactrac.data.FavoriteTrie; import chribb.mactrac.data.Macro; import chribb.mactrac.data.MacroRepository; public class AddViewModel extends AndroidViewModel { private MacroRepository repo; private FavoriteTrie fTrie; private Favorite favorite; private int day; private int count; private String name; private Integer calories; private Integer protein; private Integer fat; private Integer carbs; public AddViewModel(Application application) { super(application); repo = new MacroRepository(application); } /* * * Repo Methods * * */ void insertMacro(Integer day, String food, Integer calories, Integer protein, Integer fat, Integer carbs, int count) { repo.insert(new Macro(day, food, calories, protein, fat, carbs, count)); } void insertFavorite(Favorite favorite) { addToTrie(favorite); repo.insertFavorite(favorite); } void deleteFavorite(Favorite deleteFavorite) { deleteFromTrie(deleteFavorite); repo.deleteFavorite(deleteFavorite.getName()); } private int countFood(int day) { return repo.countFood(day); } void findCount() { //Queries Room for the number of macros already on this day, to use as position. Executors.newSingleThreadExecutor().execute(() -> count = countFood(day)); } void getFavorite() { assert(name != null); if (fTrie.contains(name)) { Executors.newSingleThreadExecutor().execute(() -> favorite = repo.getFavorite(name)); } else { favorite = null; } } boolean alreadyFavorite() { return favorite != null; } //TODO what is this? Is it trying to add a Macro or Favorite? public void addFood() { insertMacro(day, name, calories, protein, fat, carbs, count); } public void addFavorite(boolean checked) { //TODO reconsider whether it increments if you dont overwrite... or what it does // maybe only increment when you clicked on the suggestion before? not sure if (alreadyFavorite()) { if (checked) { Favorite toAdd = new Favorite(name, calories, protein, fat, carbs, favorite.getCount() + 1); insertFavorite(toAdd); } else { Favorite toAdd = new Favorite(favorite.getName(), favorite.getCalories(), favorite.getProtein(), favorite.getFat(), favorite.getCarbs(), favorite.getCount() + 1); insertFavorite(toAdd); } } else if (checked) { Favorite toAdd = new Favorite(name, calories, protein, fat, carbs,1); insertFavorite(toAdd); } } //TODO doc string public void setNumbers(String calories, String protein, String fat, String carbs) { if (calories.isEmpty()) { setCalories(0); } else { setCalories(Integer.parseInt(calories)); } if (protein.isEmpty()) { setProtein(0); } else { setProtein(Integer.parseInt(protein)); } if (fat.isEmpty()) { setFat(0); } else { setFat(Integer.parseInt(fat)); } if (carbs.isEmpty()) { setCarbs(0); } else { setCarbs(Integer.parseInt(carbs)); } } public void setNumbers(Favorite favorite) { setCalories(favorite.getCalories()); setProtein(favorite.getProtein()); setFat(favorite.getFat()); setCarbs(favorite.getCarbs()); } /** * Only runs once on mainActivity being created. //TODO might have to move to mainActivity resume */ public void loadFavoriteTrie() { Executors.newSingleThreadExecutor().execute(() -> fTrie = new FavoriteTrie(repo.loadFavorites())); } private void addToTrie(Favorite favorite) { fTrie.add(favorite); } public void deleteFromTrie(Favorite favorite) { //TODO go through code and find every time you need to call this fTrie.delete(favorite); } public List<Favorite> getSortedFavoritesWithPrefix(String prefix) { return fTrie.sortedFavoritesWithPrefix(prefix); } //TODO the number setters could maybe be private /* * * Getters/Setters * * */ public int getDay() { return day; } public void setDay(int day) { this.day = day; } int getCount() { return count; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getCalories() { return calories; } public void setCalories(Integer calories) { this.calories = calories; } public Integer getProtein() { return protein; } public void setProtein(Integer protein) { this.protein = protein; } public Integer getFat() { return fat; } public void setFat(Integer fat) { this.fat = fat; } public Integer getCarbs() { return carbs; } public void setCarbs(Integer carbs) { this.carbs = carbs; } }
package Controle; import Modelo.Gasto; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * * @author Daniel Castro */ //classe de constrole dos gastos public class ContGast { ConBD cbm = new ConBD(); //Insere um novo gasto recebe o codigo do onibus um a descrição e o valor public boolean insGast(int codo, String desc, double val) throws ClassNotFoundException, SQLException { Connection con = cbm.abrirConexao(); Gasto gas = new Gasto(codo, desc, val); String sql = "insert into gasto (codo, decr, val) values (?,?,?)"; try { PreparedStatement ps = con.prepareStatement(sql); ps.setInt(1, gas.getCodbus()); ps.setString(2, gas.getDesc()); ps.setDouble(3, gas.getVal()); ps.execute(); return true; } catch (Exception e) { System.out.println(e); } return false; } //Retorna o total de registros na tabela de gastos public int totalReg() throws ClassNotFoundException, SQLException { String SQL = "select count(cod) from gasto"; Connection con = cbm.abrirConexao(); try { PreparedStatement ps = con.prepareStatement(SQL); ResultSet rs = ps.executeQuery(); rs.next(); return rs.getInt(1); } catch (Exception e) { System.out.println(e); } return 0; } // public boolean insCli(String nome, String cpf) throws ClassNotFoundException { // Connection con = cbm.abrirConexao(); // String sql = "insert into cliente (nome, cpf) values (?,?)"; // try { // PreparedStatement ps = con.prepareStatement(sql); // ps.setString(1, nome); // ps.setString(2, cpf); // ps.execute(); // return true; // // } catch (Exception e) { // System.out.println(e); // } // return false; // } // //Deleta um gasto apenas para fins de correção public boolean delGas(int cod) throws ClassNotFoundException, SQLException { Connection con = cbm.abrirConexao(); String sql = "delete from gasto where cod = (?)"; try { PreparedStatement ps = con.prepareStatement(sql); ps.setInt(1, cod); ps.execute(); return true; } catch (Exception e) { System.out.println(e); } return false; } // // public boolean updCli(int cod, String nome, String cpf, double sal) throws ClassNotFoundException { // Connection con = cbm.abrirConexao(); // Gasto gas = new Gasto(cod, nome, cpf, sal); // String sql = "update cliente set nome = (?), cpf = (?), divd = (?) where cod = (?)"; // try { // PreparedStatement ps = con.prepareStatement(sql); // ps.setString(1, gas.getNome()); // ps.setString(2, gas.getCpf()); // ps.setDouble(3, gas.getDiv()); // ps.setInt(4, cod); // ps.execute(); // return true; // // } catch (Exception e) { // System.out.println(e); // } // return false; // } // // public boolean updCli(Gasto gas) throws ClassNotFoundException { // Connection con = cbm.abrirConexao(); // String sql = "update cliente set nome = (?), cpf = (?), divd = (?) where cod = (?)"; // try { // PreparedStatement ps = con.prepareStatement(sql); // ps.setString(1, gas.getNome()); // ps.setString(2, gas.getCpf()); // ps.setDouble(3, gas.getDiv()); // ps.setInt(4, gas.getCod()); // ps.execute(); // return true; // // } catch (Exception e) { // System.out.println(e); // } // return false; // } // // public Gasto selecCli(String s) throws ClassNotFoundException { // Connection con = cbm.abrirConexao(); // String SQL = "select * from cliente where nome like (?) order by nome"; // ResultSet rs = null; // Gasto cli = new Gasto(); // try { // PreparedStatement ps = con.prepareStatement(SQL); // ps.setString(1, s); // rs = ps.executeQuery(); // rs.next(); // System.out.println("aaa"); // cli.setCod(rs.getInt(1)); // cli.setNome(rs.getString(2)); // cli.setCpf(rs.getString(3)); // cli.setDiv(rs.getDouble(4)); // return cli; // // } catch (Exception e) { // System.out.println(e); // } // return cli; // } // // public Gasto selecCli(int s) throws ClassNotFoundException { // Connection con = cbm.abrirConexao(); // String SQL = "select * from cliente where cod =(?) order by nome"; // ResultSet rs = null; // Gasto cli = new Gasto(); // try { // PreparedStatement ps = con.prepareStatement(SQL); // ps.setInt(1, s); // rs = ps.executeQuery(); // // if (rs != null) { // while (rs.next()) { // // cli.setCod(rs.getInt(1)); // cli.setNome(rs.getString(2)); // cli.setCpf(rs.getString(3)); // cli.setDiv(rs.getDouble(4)); // // return cli; // } // } // } catch (Exception e) { // System.out.println(e); // } // return cli; // } // // //Retorna uma lista de todos os gastos na forma de uma List<> public List<Gasto> selecGas() throws ClassNotFoundException, SQLException { Connection con = cbm.abrirConexao(); List lista = new ArrayList<Gasto>(); String SQL = "select * from gasto"; ResultSet rs = null; try { PreparedStatement ps = con.prepareStatement(SQL); rs = ps.executeQuery(); if (rs != null) { while (rs.next()) { Gasto gas = new Gasto(); gas.setCod(rs.getInt(1)); gas.setCodbus(rs.getInt(2)); gas.setDesc(rs.getString(3)); gas.setVal(rs.getDouble(4)); lista.add(gas); } } } catch (Exception e) { System.out.println(e); } return lista; } // // public void regPagto(int cod, double parseInt) throws ClassNotFoundException { // Connection con = cbm.abrirConexao(); // String sql = "update cliente set divd = divd-(?) where cod = (?)"; // try{ // PreparedStatement ps = con.prepareStatement(sql); // ps.setDouble(1, parseInt); // ps.setInt(2, cod); // ps.execute(); // } catch (SQLException ex) { // Logger.getLogger(ContCli.class.getName()).log(Level.SEVERE, null, ex); // } // } }
package cn.fuyoushuo.fqbb.view.flagment; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.CardView; import android.text.Html; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.alibaba.fastjson.JSONObject; import com.jakewharton.rxbinding.view.RxView; import com.trello.rxlifecycle.FragmentEvent; import com.umeng.analytics.MobclickAgent; import java.util.concurrent.TimeUnit; import butterknife.Bind; import cn.fuyoushuo.fqbb.MyApplication; import cn.fuyoushuo.fqbb.R; import cn.fuyoushuo.fqbb.commonlib.utils.EventIdConstants; import cn.fuyoushuo.fqbb.commonlib.utils.LocalStatisticConstants; import cn.fuyoushuo.fqbb.commonlib.utils.PageSession; import cn.fuyoushuo.fqbb.commonlib.utils.RxBus; import cn.fuyoushuo.fqbb.ext.LocalStatisticInfo; import cn.fuyoushuo.fqbb.presenter.impl.UserCenterPresenter; import cn.fuyoushuo.fqbb.view.activity.ConfigActivity; import cn.fuyoushuo.fqbb.view.activity.HelpActivity; import cn.fuyoushuo.fqbb.view.activity.PointMallActivity; import cn.fuyoushuo.fqbb.view.activity.UserLoginActivity; import cn.fuyoushuo.fqbb.view.flagment.zhifubao.BindZfbDialogFragment; import cn.fuyoushuo.fqbb.view.flagment.zhifubao.UpdateZfbDialogFragment; import cn.fuyoushuo.fqbb.view.view.UserCenterView; import rx.functions.Action1; /** * Created by QA on 2016/10/27. */ public class UserCenterFragment extends BaseFragment implements UserCenterView{ private UserCenterPresenter userCenterPresenter; @Bind(R.id.user_center_account) TextView accountView; @Bind(R.id.userinfo_currentpoints_value) TextView currentPoints; @Bind(R.id.userinfo_freezepoints_value) TextView freezePoints; @Bind(R.id.userinfo_useablepoints_value) TextView useablePoints; @Bind(R.id.userinfo_month_20day_value) TextView thisMonth20Count; @Bind(R.id.userinfo_nextmonth_20day_value) TextView nextMonth20Count; @Bind(R.id.userinfo_useable_money_value) TextView useableCount; @Bind(R.id.user_center_alimama_login) View alimamaLogin; @Bind(R.id.alimama_login_icon) TextView loginText; @Bind(R.id.user_center_refreshview) SwipeRefreshLayout userCenterRefreshView; @Bind(R.id.user_center_points_icon) RelativeLayout pointsIcon; @Bind(R.id.user_center_help_icon) RelativeLayout helpIcon; @Bind(R.id.user_center_balance_icon) RelativeLayout tixianIcon; @Bind(R.id.logout_area) CardView logoutArea; @Bind(R.id.bind_email) TextView bindEmailView; @Bind(R.id.bind_zfb) TextView bindAlipay; @Bind(R.id.update_password) TextView updatePasswordView; @Bind(R.id.user_set) TextView userSetView; boolean isEmailBind = false; boolean isAlipayBind = false; private String phoneNum = ""; private String email = ""; private String alipayNo = ""; private boolean isDataInit = false; private boolean isAccountClickable = false; private boolean isAliPayClickable = false; private boolean isLocalLogin = false; private PageSession pageSession; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return super.onCreateView(inflater,container,savedInstanceState); } @Override protected String getPageName() { return "userCenterPage"; } @Override protected int getRootLayoutId() { return R.layout.fragment_user_center; } @Override protected void initView() { RxView.clicks(alimamaLogin).compose(this.<Void>bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .throttleFirst(1000, TimeUnit.MILLISECONDS) .subscribe(new Action1<Void>() { @Override public void call(Void aVoid) { AlimamaLoginDialogFragment.newInstance(AlimamaLoginDialogFragment.FROM_USER_CENTER) .show(getFragmentManager(),"AlimamaLoginDialogFragment"); } }); userCenterRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { userCenterRefreshView.setRefreshing(true); refreshUserInfo(); } }); //积分商城 RxView.clicks(pointsIcon).compose(this.<Void>bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .throttleFirst(1000, TimeUnit.MILLISECONDS) .subscribe(new Action1<Void>() { @Override public void call(Void aVoid) { LocalStatisticInfo.getIntance().onClickPage(LocalStatisticConstants.POINT_MALL); if(isLocalLogin){ Intent intent = new Intent(mactivity, PointMallActivity.class); startActivity(intent); }else{ showLocalLoginDialog(); } } }); //帮助中心 RxView.clicks(helpIcon).compose(this.<Void>bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .throttleFirst(1000, TimeUnit.MILLISECONDS) .subscribe(new Action1<Void>() { @Override public void call(Void aVoid) { LocalStatisticInfo.getIntance().onClickPage(LocalStatisticConstants.HELP_CENTER); Intent intent = new Intent(mactivity,HelpActivity.class); startActivity(intent); } }); //余额提现 RxView.clicks(tixianIcon).compose(this.<Void>bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .throttleFirst(1000, TimeUnit.MILLISECONDS) .subscribe(new Action1<Void>() { @Override public void call(Void aVoid) { //提现页面 MobclickAgent.onEvent(MyApplication.getContext(), EventIdConstants.USER_TIXIAN_BTN); TixianFlagment.newInstance().show(getFragmentManager(),"TixianFlagment"); } }); RxView.clicks(logoutArea).compose(this.<Void>bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .throttleFirst(1000, TimeUnit.MILLISECONDS) .subscribe(new Action1<Void>() { @Override public void call(Void aVoid) { userCenterPresenter.logout(); } }); bindEmailView.setText(Html.fromHtml("绑定邮箱<font color=\"#ff0000\">(强烈建议,方便找回账号)</font>")); RxView.clicks(bindEmailView).compose(this.<Void>bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .throttleFirst(1000, TimeUnit.MILLISECONDS) .subscribe(new Action1<Void>() { @Override public void call(Void aVoid) { if(!isLocalLogin){ showLocalLoginDialog(); return; } // TODO: 2016/11/9 绑定邮箱逻辑 if(!isEmailBind){ BindEmailDialogFragment.newInstance().show(getFragmentManager(),"BindEmailDialogFragment"); }else{ UnbindEmailDialogFragment.newInstance(phoneNum,email).show(getFragmentManager(),"UnbindEmailDialogFragment"); } } }); RxView.clicks(bindAlipay).compose(this.<Void>bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .throttleFirst(1000, TimeUnit.MILLISECONDS) .subscribe(new Action1<Void>() { @Override public void call(Void aVoid) { if(!isLocalLogin){ showLocalLoginDialog(); return; } // TODO: 2016/11/9 绑定邮箱逻辑 if(!isAlipayBind){ BindZfbDialogFragment.newInstance().show(getFragmentManager(),"BindZfbDialogFragment"); }else{ UpdateZfbDialogFragment.newInstance(alipayNo).show(getFragmentManager(),"UpdateZfbDialogFragment"); } } }); RxView.clicks(updatePasswordView).compose(this.<Void>bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .throttleFirst(1000, TimeUnit.MILLISECONDS) .subscribe(new Action1<Void>() { @Override public void call(Void aVoid) { if(!isLocalLogin){ showLocalLoginDialog(); return; } // TODO: 2016/11/9 修改密码逻辑 UpdatePasswordDialogFragment.newInstance().show(getFragmentManager(),"UpdatePasswordDialogFragment"); } }); RxView.clicks(userSetView).compose(this.<Void>bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .throttleFirst(1000, TimeUnit.MILLISECONDS) .subscribe(new Action1<Void>() { @Override public void call(Void aVoid) { // TODO: 2016/11/9 用户设置逻辑 Intent intent = new Intent(getActivity(), ConfigActivity.class); startActivity(intent); } }); RxView.clicks(accountView).compose(this.<Void>bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .throttleFirst(1000, TimeUnit.MILLISECONDS) .subscribe(new Action1<Void>() { @Override public void call(Void aVoid) { if(!isAccountClickable) return; // TODO: 2016/11/9 账号点击功能 Intent intent = new Intent(getActivity(), UserLoginActivity.class); intent.putExtra("biz","MainToUc"); startActivity(intent); } }); RxView.clicks(useableCount).compose(this.<Void>bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .throttleFirst(1000, TimeUnit.MILLISECONDS) .subscribe(new Action1<Void>() { @Override public void call(Void aVoid) { if(!isAliPayClickable) return; // TODO: 2016/11/9 阿里妈妈点击登录 AlimamaLoginDialogFragment.newInstance(AlimamaLoginDialogFragment.FROM_USER_CENTER) .show(getFragmentManager(),"AlimamaLoginDialogFragment"); } }); } @Override protected void initData() { pageSession = new PageSession(LocalStatisticConstants.USER_CENTER); userCenterPresenter = new UserCenterPresenter(this); } public static UserCenterFragment newInstance() { UserCenterFragment fragment = new UserCenterFragment(); return fragment; } @Override public void onStart() { super.onStart(); refreshUserInfo(); } @Override public void onDestroy() { super.onDestroy(); userCenterPresenter.onDestroy(); } //----------------------------------用于外部调用-------------------------------------------------- public void refreshUserInfo(){ if(!isDetched && userCenterPresenter != null){ userCenterPresenter.getUserInfo(); userCenterPresenter.getAlimamaInfo(); } } //初始化字体图标 private void initIconFront() { Typeface iconfont = Typeface.createFromAsset(getActivity().getAssets(), "iconfront/iconfont_alimamalogin.ttf"); loginText.setTypeface(iconfont); } //--------------------------------------------统计相关----------------------------------------------------- @Override public void onHiddenChanged(boolean hidden) { super.onHiddenChanged(hidden); if(!hidden){ LocalStatisticInfo.getIntance().onPageStart(pageSession); }else{ LocalStatisticInfo.getIntance().onPageEnd(pageSession); } } @Override public void onResume() { super.onResume(); if(!this.isHidden()){ LocalStatisticInfo.getIntance().onPageStart(pageSession); } } @Override public void onPause() { super.onPause(); if(!this.isHidden()){ LocalStatisticInfo.getIntance().onPageEnd(pageSession); } } private void showLocalLoginDialog() { final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage("需要登录才能进行操作!"); builder.setCancelable(true); builder.setPositiveButton("去登录", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(getActivity(), UserLoginActivity.class); intent.putExtra("biz", "MainToUc"); startActivity(intent); dialog.dismiss(); } }); builder.create().show(); } //------------------------------------view 层回调-------------------------------------------------- @Override public void onUserInfoGetError() { currentPoints.setText("--"); freezePoints.setText("--"); useablePoints.setText("--"); accountView.setText("登录/注册"); accountView.setTextColor(getResources().getColor(R.color.module_11)); isAccountClickable = true; isLocalLogin = false; logoutArea.setVisibility(View.GONE); userCenterRefreshView.setRefreshing(false); } @Override public void onUserInfoGetSucc(JSONObject result) { if(result == null || result.isEmpty()) return; Integer validPoint = 0; Integer orderFreezePoint = 0; Integer convertFreezePoint = 0; String account = ""; String email = ""; String alipayNo = ""; if(result.containsKey("validPoint")){ validPoint = result.getIntValue("validPoint"); } if(result.containsKey("orderFreezePoint")){ orderFreezePoint =result.getIntValue("orderFreezePoint"); } if(result.containsKey("convertFreezePoint")){ convertFreezePoint = result.getIntValue("convertFreezePoint"); } if(result.containsKey("account")){ account = result.getString("account"); } if(result.containsKey("email")){ email = result.getString("email"); } if(result.containsKey("alipay")){ alipayNo = result.getString("alipay"); } if(!TextUtils.isEmpty(email)){ bindEmailView.setText("解绑邮箱"); this.email = email; isEmailBind = true; }else{ bindEmailView.setText(Html.fromHtml("绑定邮箱<font color=\"#ff0000\">(强烈建议,方便找回账号)</font>")); isEmailBind = false; this.email = ""; } if(!TextUtils.isEmpty(alipayNo)){ bindAlipay.setText("换绑支付宝"); this.alipayNo = alipayNo; this.isAlipayBind = true; }else{ bindAlipay.setText(Html.fromHtml("绑定支付宝<font color=\"#ff0000\">(强烈建议,方便积分提现)</font>")); isAlipayBind = false; this.alipayNo = ""; } this.phoneNum = account; currentPoints.setText(String.valueOf(validPoint+orderFreezePoint+convertFreezePoint)); freezePoints.setText(String.valueOf(orderFreezePoint+convertFreezePoint)); useablePoints.setText(String.valueOf(validPoint)); //账号信息的处理 logoutArea.setVisibility(View.VISIBLE); accountView.setText(account); accountView.setTextColor(currentPoints.getCurrentTextColor()); isAccountClickable = false; isLocalLogin = true; userCenterRefreshView.setRefreshing(false); isDataInit = true; } // @Override // public void onLoginFail() { // Intent intent = new Intent(mactivity, UserLoginActivity.class); // intent.putExtra("fromWhere","UserCenter"); // startActivity(intent); // } @Override public void onAlimamaLoginFail() { //Toast.makeText(MyApplication.getContext(),"请稍后重新登录阿里妈妈",Toast.LENGTH_SHORT).show(); //alimamaLogin.setVisibility(View.VISIBLE); thisMonth20Count.setText("--"); nextMonth20Count.setText("--"); useableCount.setText("登录查看"); useableCount.setTextSize(15); useableCount.setTextColor(getResources().getColor(R.color.module_11)); isAliPayClickable = true; userCenterRefreshView.setRefreshing(false); } @Override public void onAlimamaLoginSuccess(JSONObject result) { if(result != null && !result.isEmpty()){ if(result.containsKey("lastMonthMoney")){ thisMonth20Count.setText(result.getString("lastMonthMoney")); } if(result.containsKey("thisMonthMoney")){ nextMonth20Count.setText(result.getString("thisMonthMoney")); } if(result.containsKey("currentMoney")){ useableCount.setText(result.getString("currentMoney")); useableCount.setTextColor(nextMonth20Count.getCurrentTextColor()); useableCount.setTextSize(20); isAliPayClickable = false; } } alimamaLogin.setVisibility(View.GONE); userCenterRefreshView.setRefreshing(false); } @Override public void onAlimamaLoginError() { Toast.makeText(MyApplication.getContext(),"请重新下拉刷新数据",Toast.LENGTH_SHORT).show(); thisMonth20Count.setText("--"); nextMonth20Count.setText("--"); useableCount.setText("--"); userCenterRefreshView.setRefreshing(false); } @Override public void onLogoutSuccess() { Toast.makeText(MyApplication.getContext(),"退出登录成功",Toast.LENGTH_SHORT).show(); RxBus.getInstance().send(new LogoutToMainEvent()); } @Override public void onLogoutFail() { Toast.makeText(MyApplication.getContext(),"退出登录失败,请重试",Toast.LENGTH_SHORT).show(); } //-----------------------------总线事件---------------------------------------------------- public class LogoutToMainEvent extends RxBus.BusEvent{} }
package com.eagleshipperapi.service; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import org.springframework.stereotype.Service; import com.eagleshipperapi.bean.States; import com.eagleshipperapi.exception.ResourceNotFoundException; import com.google.api.core.ApiFuture; import com.google.cloud.firestore.Firestore; import com.google.cloud.firestore.QueryDocumentSnapshot; import com.google.cloud.firestore.QuerySnapshot; import com.google.firebase.cloud.FirestoreClient; @Service public class StateService { public ArrayList<States> getStateList() throws InterruptedException, ExecutionException { Firestore fireStore = FirestoreClient.getFirestore(); ArrayList<States> al = new ArrayList<>(); ApiFuture<QuerySnapshot> apiFuture = fireStore.collection("State").get(); QuerySnapshot querySnapshot = apiFuture.get(); List<QueryDocumentSnapshot> documentSnapshotList = querySnapshot.getDocuments(); for (QueryDocumentSnapshot document : documentSnapshotList) { States state = document.toObject(States.class); al.add(state); } return al; } public States saveState(States s) throws Exception { Firestore fireStore = FirestoreClient.getFirestore(); fireStore.collection("State").document(s.getStateId()).set(s); return s; } public States getStateById(String stateId) throws InterruptedException, ExecutionException, ResourceNotFoundException { Firestore fireStore = FirestoreClient.getFirestore(); States state = fireStore.collection("State").document(stateId).get().get().toObject(States.class); if (state!= null) return state; else throw new ResourceNotFoundException("state not found for this id "+stateId); } }
package com.hyokeun.org.model; import java.io.Serializable; public class Name implements Serializable { private String firstName; private String lastName; public Name(final String fName, final String lName) { firstName = fName; lastName = lName; } public String getFirst() { return firstName; } public String getLast() { return lastName; } public void setFirst(final String firstName) { this.firstName = firstName; } public void setLast(final String lastName) { this.lastName = lastName; } }
package common; /** * @author Steve Riley */ public class SimpleDBCell { private String m_value; public SimpleDBCell() { this(""); //$NON-NLS-1$ } /** * @param p_value */ public SimpleDBCell(final String p_value) { m_value = p_value; } public boolean asBoolean() { return Boolean.parseBoolean(m_value); } /** * @return The value of the cell parsed as a double */ public double asDouble() { return Double.parseDouble(m_value); } /** * @return The value of the cell parsed as an int */ public int asInt() { return Integer.parseInt(m_value); } public RepeatPeriodType asRepeatPeriodType() { return RepeatPeriodType.parseRepeatPeriodType(m_value); } public RepeatRestartType asRepeatRestartType() { return RepeatRestartType.parseRepeatRestartType(m_value); } /** * @return The String in this cell */ public String asString() { return m_value; } /** * @return The value of this cell as a string */ public String getValue() { return m_value; } /** * Sets the value of this cell * * @param p_value */ public void setValue(final String p_value) { m_value = p_value; } @Override public String toString() { return m_value; } }
package com.example.steve.moviecatalogue3.adapter; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.example.steve.moviecatalogue3.R; import com.example.steve.moviecatalogue3.entity.TvSeries; import java.util.ArrayList; public class TvAdapter extends RecyclerView.Adapter<TvAdapter.CategoryViewHolder> { private Context context; public TvAdapter(Context context) { this.context = context; } public ArrayList<TvSeries> getTvSeriesList() { return tvSeriesList; } public void setTvSeriesList(ArrayList<TvSeries> tvSeriesList) { this.tvSeriesList = tvSeriesList; } private ArrayList<TvSeries> tvSeriesList; @NonNull @Override public CategoryViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View itemview = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.tv_series_row, viewGroup, false ); return new CategoryViewHolder(itemview); } @Override public void onBindViewHolder(@NonNull CategoryViewHolder categoryViewHolder, int i) { categoryViewHolder.namaFilm.setText(getTvSeriesList().get(i).getTitle()); categoryViewHolder.rateFilm.setText(String.format("%s %.2f",context.getResources().getString(R.string.rate) , getTvSeriesList().get(i).getVote_average())); categoryViewHolder.descFilm.setText(getTvSeriesList().get(i).getOverview()); String linkPoster = "https://image.tmdb.org/t/p/w500" + getTvSeriesList().get(i).getPath(); Glide.with(context) .load(linkPoster) .into(categoryViewHolder.fotoFilm); } @Override public int getItemCount() { return getTvSeriesList().size(); } public class CategoryViewHolder extends RecyclerView.ViewHolder { TextView namaFilm; TextView descFilm; TextView rateFilm; ImageView fotoFilm; public CategoryViewHolder(View itemView) { super(itemView); namaFilm = itemView.findViewById(R.id.tv_series_title); descFilm = itemView.findViewById(R.id.tv_series_desc); fotoFilm = itemView.findViewById(R.id.tv_series_mini_poster); rateFilm = itemView.findViewById(R.id.tv_series_rate); } } }
import gov.nih.mipav.model.algorithms.*; import gov.nih.mipav.model.file.FileInfoBase.Unit; import gov.nih.mipav.model.structures.*; import gov.nih.mipav.view.*; import java.io.*; /** * This is simple plugin that finds the distances between 2 different color centers of mass weighted by fluorescence and * thresholded within a 2D or 3D voi. Multiple VOIs can be handled. 2D or 3D color images are allowed. Only color values * >= threshold will be counted toward the center of mass. The thresholds are specified for each color by the user in * the dialog box. Be sure to hit the new VOI button for each new VOI. Note that a single VOI can contain multiple * contours so if mulitple curves are used without hitting the new VOI button, then the interiors of all these curves * will belong to the same VOI. * * @version June 3, 2004 * @author DOCUMENT ME! * @see AlgorithmBase * * <p>$Logfile: /mipav/src/plugins/PlugInAlgorithmObjectDistanceKruhlak.java $ $Revision: 7 $ $Date: 1/25/06 * 4:59p $</p> */ public class PlugInAlgorithmObjectDistanceKruhlak extends AlgorithmBase { //~ Instance fields ------------------------------------------------------------------------------------------------ /** DOCUMENT ME! */ private int threshold1 = 0; /** DOCUMENT ME! */ private int threshold2 = 0; /** DOCUMENT ME! */ private boolean useBlue = false; /** DOCUMENT ME! */ private boolean useRed = true; //~ Constructors --------------------------------------------------------------------------------------------------- /** * Constructor. * * @param srcImg Source image model. * @param useRed DOCUMENT ME! * @param useGreen DOCUMENT ME! * @param useBlue DOCUMENT ME! * @param threshold1 DOCUMENT ME! * @param threshold2 DOCUMENT ME! */ public PlugInAlgorithmObjectDistanceKruhlak(ModelImage srcImg, boolean useRed, boolean useGreen, boolean useBlue, int threshold1, int threshold2) { super(null, srcImg); this.useRed = useRed; this.useBlue = useBlue; this.threshold1 = threshold1; this.threshold2 = threshold2; } //~ Methods -------------------------------------------------------------------------------------------------------- /** * Prepares this class for destruction. */ public void finalize() { srcImage = null; super.finalize(); } /** * Starts the algorithm. */ public void runAlgorithm() { if (srcImage == null) { displayError("Source Image is null"); return; } if (srcImage.getNDims() == 2) { calc2D(); } else if (srcImage.getNDims() > 2) { calc3D(); } } // end runAlgorithm() /** * DOCUMENT ME! */ private void calc2D() { int length; // total number of data-elements (pixels) in image float[] buffer1; float[] buffer2; int count1; int count2; float xPos1; float yPos1; float xPos2; float yPos2; float centerToCenter; int i, j; int x, y; int xDim = srcImage.getExtents()[0]; int yDim = srcImage.getExtents()[1]; float xRes = srcImage.getResolutions(0)[0]; float yRes = srcImage.getResolutions(0)[1]; ViewVOIVector VOIs = null; int nVOIs; short[] shortMask; int index; ViewUserInterface UI = ViewUserInterface.getReference(); int xUnits = srcImage.getFileInfo(0).getUnitsOfMeasure()[0]; int yUnits = srcImage.getFileInfo(0).getUnitsOfMeasure()[1]; String unitsString = null; if ((xUnits == yUnits) && (xUnits != Unit.UNKNOWN_MEASURE.getLegacyNum())) { unitsString = (Unit.getUnitFromLegacyNum(xUnits)).toString(); } try { // image length is length in 2 dims length = xDim * yDim; buffer1 = new float[length]; buffer2 = new float[length]; if (useRed) { srcImage.exportRGBData(1, 0, length, buffer1); // export red data } else { srcImage.exportRGBData(2, 0, length, buffer1); // export green data } if (useBlue) { srcImage.exportRGBData(3, 0, length, buffer2); // export blue data } else { srcImage.exportRGBData(2, 0, length, buffer2); // export green data } } catch (IOException error) { buffer1 = null; buffer2 = null; errorCleanUp("Algorithm ObjectDistanceKruhlak reports: source image locked", true); return; } catch (OutOfMemoryError e) { buffer1 = null; buffer2 = null; errorCleanUp("Algorithm ObjectDistanceKruhlak reports: out of memory", true); return; } fireProgressStateChanged("Processing image ..."); VOIs = srcImage.getVOIs(); nVOIs = VOIs.size(); shortMask = new short[length]; for (i = 0; i < length; i++) { shortMask[i] = -1; } for (i = 0; i < nVOIs; i++) { fireProgressStateChanged("Processing VOI " + (i + 1) + " of " + nVOIs); fireProgressStateChanged(100 * i / nVOIs); if (VOIs.VOIAt(i).getCurveType() == VOI.CONTOUR) { shortMask = srcImage.generateVOIMask(shortMask, i); count1 = 0; count2 = 0; xPos1 = 0.0f; yPos1 = 0.0f; xPos2 = 0.0f; yPos2 = 0.0f; for (j = 0, y = 0; y < yDim; y++, j += xDim) { for (x = 0; x < xDim; x++) { index = x + j; if (shortMask[index] == i) { if (buffer1[index] >= threshold1) { xPos1 += buffer1[index] * x; yPos1 += buffer1[index] * y; count1 += buffer1[index]; } if (buffer2[index] >= threshold2) { xPos2 += buffer2[index] * x; yPos2 += buffer2[index] * y; count2 += buffer2[index]; } } // if (shortMask[index] == i) } // for (x = 0; x < xDim; x++) } // for (j = 0, y = 0; y < yDim; y++, j += xDim) xPos1 /= count1; yPos1 /= count1; xPos2 /= count2; yPos2 /= count2; centerToCenter = (float) Math.sqrt(((xPos1 - xPos2) * (xPos1 - xPos2) * xRes * xRes) + ((yPos1 - yPos2) * (yPos1 - yPos2) * yRes * yRes)); if (useRed) { UI.setDataText("VOI ID = " + i + " with red weighted voi center of mass = " + "(" + xPos1 + ", " + yPos1 + ")\n"); } else { UI.setDataText("VOI ID = " + i + " with green weighted voi center of mass = " + "(" + xPos1 + ", " + yPos1 + ")\n"); } if (useBlue) { UI.setDataText("VOI ID = " + i + " with blue weighted voi center of mass = " + "(" + xPos2 + ", " + yPos2 + ")\n"); } else { UI.setDataText("VOI ID = " + i + " with green weighted voi center of mass = " + "(" + xPos2 + ", " + yPos2 + ")\n"); } if (unitsString != null) { UI.setDataText("Center to center distance = " + centerToCenter + " " + unitsString + "\n"); } else { UI.setDataText("Center to center distance = " + centerToCenter + "\n"); } } // if (VOIs.VOIAt(i).getCurveType() == VOI.CONTOUR) } // for (i = 0; i < nVOIs; i++) fireProgressStateChanged(100); if (threadStopped) { finalize(); return; } setCompleted(true); } /** * DOCUMENT ME! */ private void calc3D() { int sliceLength; int totLength; float[] buffer1; float[] buffer2; int count1; int count2; float xPos1; float yPos1; float zPos1; float xPos2; float yPos2; float zPos2; float centerToCenter; int i, j, k; int x, y, z; int xDim = srcImage.getExtents()[0]; int yDim = srcImage.getExtents()[1]; int zDim = srcImage.getExtents()[2]; float xRes = srcImage.getResolutions(0)[0]; float yRes = srcImage.getResolutions(0)[1]; float zRes = srcImage.getResolutions(0)[2]; ViewVOIVector VOIs = null; int nVOIs; short[] shortMask; int index; ViewUserInterface UI = ViewUserInterface.getReference(); int xUnits = srcImage.getUnitsOfMeasure()[0]; int yUnits = srcImage.getUnitsOfMeasure()[1]; int zUnits = srcImage.getUnitsOfMeasure()[2]; String unitsString = null; if ((xUnits == yUnits) && (xUnits == zUnits) && (xUnits != Unit.UNKNOWN_MEASURE.getLegacyNum())) { unitsString = (Unit.getUnitFromLegacyNum(xUnits)).toString(); } try { sliceLength = xDim * yDim; totLength = sliceLength * zDim; buffer1 = new float[totLength]; buffer2 = new float[totLength]; if (useRed) { srcImage.exportRGBData(1, 0, totLength, buffer1); // export red data } else { srcImage.exportRGBData(2, 0, totLength, buffer1); // export green data } if (useBlue) { srcImage.exportRGBData(3, 0, totLength, buffer2); // export blue data } else { srcImage.exportRGBData(2, 0, totLength, buffer2); // export green data } } catch (IOException error) { buffer1 = null; buffer2 = null; errorCleanUp("Algorithm ObjectDistanceKruhlak reports: source image locked", true); return; } catch (OutOfMemoryError e) { buffer1 = null; buffer2 = null; errorCleanUp("Algorithm ObjectDistanceKruhlak reports: out of memory", true); return; } fireProgressStateChanged("Processing image ..."); VOIs = srcImage.getVOIs(); nVOIs = VOIs.size(); shortMask = new short[totLength]; for (i = 0; i < totLength; i++) { shortMask[i] = -1; } for (i = 0; i < nVOIs; i++) { fireProgressStateChanged("Processing VOI " + (i + 1) + " of " + nVOIs); fireProgressStateChanged(100 * i / nVOIs); if (VOIs.VOIAt(i).getCurveType() == VOI.CONTOUR) { shortMask = srcImage.generateVOIMask(shortMask, i); count1 = 0; count2 = 0; xPos1 = 0.0f; yPos1 = 0.0f; zPos1 = 0.0f; xPos2 = 0.0f; yPos2 = 0.0f; zPos2 = 0.0f; for (k = 0, z = 0; z < zDim; z++, k += sliceLength) { for (j = k, y = 0; y < yDim; y++, j += xDim) { for (x = 0; x < xDim; x++) { index = x + j; if (shortMask[index] == i) { if (buffer1[index] >= threshold1) { xPos1 += buffer1[index] * x; yPos1 += buffer1[index] * y; zPos1 += buffer1[index] * z; count1 += buffer1[index]; } if (buffer2[index] >= threshold2) { xPos2 += buffer2[index] * x; yPos2 += buffer2[index] * y; zPos2 += buffer2[index] * z; count2 += buffer2[index]; } } // if (shortMask[index] == i) } // for (x = 0; x < xDim; x++) } // for (j = k, y = 0; y < yDim; y++, j += xDim) } // for (k = 0, z = 0; z < zDim; z++, k += sliceLength) xPos1 /= count1; yPos1 /= count1; zPos1 /= count1; xPos2 /= count2; yPos2 /= count2; zPos2 /= count2; centerToCenter = (float) Math.sqrt(((xPos1 - xPos2) * (xPos1 - xPos2) * xRes * xRes) + ((yPos1 - yPos2) * (yPos1 - yPos2) * yRes * yRes) + ((zPos1 - zPos2) * (zPos1 - zPos2) * zRes * zRes)); if (useRed) { UI.setDataText("VOI ID = " + i + " with red weighted voi center of mass = " + "(" + xPos1 + ", " + yPos1 + ", " + zPos1 + ")\n"); } else { UI.setDataText("VOI ID = " + i + " with green weighted voi center of mass = " + "(" + xPos1 + ", " + yPos1 + ", " + zPos1 + ")\n"); } if (useBlue) { UI.setDataText("VOI ID = " + i + " with blue weighted voi center of mass = " + "(" + xPos2 + ", " + yPos2 + ", " + zPos2 + ")\n"); ; } else { UI.setDataText("VOI ID = " + i + " with green weighted voi center of mass = " + "(" + xPos2 + ", " + yPos2 + ", " + zPos2 + ")\n"); } if (unitsString != null) { UI.setDataText("Center to center distance = " + centerToCenter + " " + unitsString + "\n"); } else { UI.setDataText("Center to center distance = " + centerToCenter + "\n"); } } // if (VOIs.VOIAt(i).getCurveType() == VOI.CONTOUR) } // for (i = 0; i < nVOIs; i++) fireProgressStateChanged(100); if (threadStopped) { finalize(); return; } setCompleted(true); } }
package controller.registrar.summer; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; 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 org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import configuration.EncryptandDecrypt; import configuration.GetActive; import connection.DBConfiguration; /** * Servlet implementation class GetDocument */ @WebServlet("/Registrar/Controller/Registrar/Summer/Summer") public class Summer extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Summer() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); EncryptandDecrypt ec = new EncryptandDecrypt(); JSONArray studentlist = new JSONArray(); JSONArray schedlist = new JSONArray(); Object sched=null; Object student=null; JSONParser jsonParser=new JSONParser(); String subject = request.getParameter("subject"); String faculty = request.getParameter("faculty"); String campus = request.getParameter("campus"); try { sched=jsonParser.parse(request.getParameter("schedule")); student=jsonParser.parse(request.getParameter("student")); } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } studentlist = (JSONArray) student; schedlist = (JSONArray) sched; DBConfiguration db = new DBConfiguration(); Connection conn = db.getConnection(); Statement stmnt = null; try { stmnt = conn.createStatement(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } String sql = ""; PrintWriter out = response.getWriter(); try { GetActive ga = new GetActive(); String acadyear = ga.getAcadYear(); ResultSet rs = stmnt.executeQuery("SELECT YEAR(CURRENT_DATE) AS YEAR ,RIGHT(count(*) + 100001,5) AS NUM FROM `t_summer_class` where Summer_Class_Academic_Year = (SELECT Academic_Year_ID FROM `r_academic_year` where Academic_Year_Active_Flag = 'Present') and Summer_Class_Subject_ID = (SELECT Subject_ID FROM `r_subject` where Subject_Code = '"+ec.encrypt(ec.key, ec.initVector, subject)+"') "); int i = 0 ; String year = ""; String num = ""; String code = ""; while(rs.next()){ year = rs.getString("YEAR"); num = rs.getString("NUM"); } code = year + "-"+subject+"-"+num+"-"+campus; sql = "INSERT INTO t_summer_class (Summer_Class_Code,Summer_Class_Academic_Year,Summer_Class_Subject_ID,Summer_Class_ProfessorID,Summer_Class_CampusID) VALUES ('"+code+"',(SELECT Academic_Year_ID FROM `r_academic_year` where Academic_Year_Active_Flag = 'Present'),(SELECT Subject_ID FROM `r_subject` where Subject_Code = '"+ec.encrypt(ec.key, ec.initVector, subject)+"'),(SELECT Professor_ID FROM `r_professor` where Professor_Code = '"+faculty+"'),(SELECT Campus_ID FROM `r_campus` where Campus_Code = '"+ec.encrypt(ec.key, ec.initVector, campus)+"')) "; out.print(sql+"\n"); stmnt.execute(sql); for (Object o : studentlist) { sql = "INSERT INTO t_summer_class_student (Summer_Class_Student_SummerClassID,Summer_Class_Student_StudentAccountID) VALUES ((SELECT max(Summer_Class_ID) FROM `t_summer_class` ),(SELECT Student_Account_ID FROM `t_student_account` where Student_Account_Student_Number = '"+o+"')) "; stmnt.execute(sql); out.print(sql+"\n"); rs = stmnt.executeQuery(" SELECT * FROM `t_student_account` where Student_Account_Student_Number = '"+o+"'"); String accid = ""; String yearlvl = ""; String section = ""; String course = ""; while(rs.next()){ accid = rs.getString("Student_Account_ID"); yearlvl = rs.getString("Student_Account_Year"); section = rs.getString("Student_Account_SectionID"); course = rs.getString("Student_Account_CourseID"); } sql = "INSERT INTO t_student_taken_curriculum_subject (Student_Taken_Curriculum_Subject_SubjectID,Student_Taken_Curriculum_Subject_StudentAccountID,Student_Taken_Curriculum_Subject_Taken_Status,Student_Taken_Curriculum_Subject_YearLevel,Student_Taken_Curriculum_Subject_SemesterID,Student_Taken_Curriculum_Subject_AcademicIYearID,Student_Taken_Curriculum_Subject_SectionID,Student_Taken_Curriculum_Subject_CourseID) VALUES ((SELECT Subject_ID FROM `r_subject` where Subject_Code = '"+ec.encrypt(ec.key, ec.initVector, subject)+"'),'"+accid+"','true','"+yearlvl+"',( SELECT Semester_ID FROM `r_semester` where Semester_Description = '"+ec.encrypt(ec.key, ec.initVector, "Summer")+"' ),(SELECT Academic_Year_ID FROM `r_academic_year` where Academic_Year_Active_Flag = 'Present'),'"+section+"','"+course+"') "; out.print(sql+"\n"); stmnt.execute(sql); } for (Object o : schedlist) { JSONObject jsonLineItem = (JSONObject) o; String room = (String) jsonLineItem.get("room"); String tend = (String) jsonLineItem.get("tend"); String tstart = (String) jsonLineItem.get("tstart"); String day = (String) jsonLineItem.get("day"); sql = "INSERT INTO t_summer_class_schedule (Summer_Class_Schedule_SummerClassID,Summer_Class_Schedule_RoomID,Summer_Class_Schedule_Time_Start,Summer_Class_Schedule_Time_End,Summer_Class_Schedule_Day) VALUES ((SELECT max(Summer_Class_ID) FROM `t_summer_class` ),(SELECT Room_ID FROM `r_room` where Room_Code = '"+ec.encrypt(ec.key, ec.initVector, room)+"'),'"+tstart+"','"+tend+"','"+day+"') "; out.print(sql+"\n"); stmnt.execute(sql); } // conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package returnTypeTest; public class ReturnTypeTest { }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Controller.Admin; import Business.TableBookingBAL; import Entity.Booking; import Entity.TableBooking; import java.util.List; import java.util.TimeZone; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; /** * * @author TUNT */ @ManagedBean @RequestScoped public class TableBookingList { /** Creates a new instance of TableBookingList */ public TableBookingList() { } private String redirect = "?faces-redirect=true"; private static int choice = 0; private static String bookingChoice = "Table bookings"; private static String bookedChoice = "Table bookeds"; private static Booking booking; private String errorMessage = "none"; private TimeZone timeZone = TimeZone.getDefault(); public TimeZone getTimeZone() { return timeZone; } public void setTimeZone(TimeZone timeZone) { this.timeZone = timeZone; } public int getChoice() { return choice; } public void setChoice(int choice) { TableBookingList.choice = choice; } public String getBookingChoice() { return bookingChoice; } public String getBookedChoice() { return bookedChoice; } public Booking getBooking() { return booking; } public void setBooking(Booking booking) { TableBookingList.booking = booking; } public String getErrorMessage() { return errorMessage; } public String getAction() { if(choice == 0) { return "block"; } else { return "none"; } } public String choice() { if (choice == 0) { choice = 1; bookingChoice = "Table bookeds"; bookedChoice = "Table bookings"; } else { choice = 0; bookingChoice = "Table bookings"; bookedChoice = "Table bookeds"; } return "TableBookingList" + redirect; } private List<TableBooking> tableBookingList; public List<TableBooking> getTableBookingList() { if (choice == 0) { tableBookingList = TableBookingBAL.getInstance().getTableBookingList(); } else { tableBookingList = TableBookingBAL.getInstance().getTableBookedList(); } return tableBookingList; } public String viewTableBooking() { return "TableBookingDetails" + redirect; } public String updateTableBooking() { if (TableBookingBAL.getInstance().updateTableBooking(booking)) { return "TableBookingList" + redirect; } errorMessage = "block"; return "TableBookingDetails" + redirect; } }
package com.nexlesoft.tenwordsaday_chiforeng.widget; import static com.nexlesoft.tenwordsaday_chiforeng.utilities.Strings.isNotEmpty; import android.content.Context; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.View.OnFocusChangeListener; import android.view.View.OnTouchListener; import android.widget.AutoCompleteTextView; import android.widget.EditText; import com.nexlesoft.tenwordsaday_chiforeng.R; import com.nexlesoft.tenwordsaday_chiforeng.widget.TextWatcherAdapter.TextWatcherListener; public class FontableAutoCompleteTextView extends AutoCompleteTextView implements OnTouchListener, OnFocusChangeListener, TextWatcherListener { public interface Listener { void didClearText(); } public void setListener(Listener listener) { this.listener = listener; } private Drawable xD; private Listener listener; public FontableAutoCompleteTextView(Context context) { super(context); init(); } public FontableAutoCompleteTextView(Context context, AttributeSet attrs) { super(context, attrs); UiUtil.setCustomFont(this, context, attrs, R.styleable.ClearableEditText, R.styleable.ClearableEditText_font); init(); } public FontableAutoCompleteTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); UiUtil.setCustomFont(this, context, attrs, R.styleable.ClearableEditText, R.styleable.ClearableEditText_font); init(); } private void init() { xD = getCompoundDrawables()[2]; if (xD == null) { xD = getResources().getDrawable(R.drawable.icon_clear); } xD.setBounds(0, 0, xD.getIntrinsicWidth(), xD.getIntrinsicHeight()); setClearIconVisible(false); super.setOnTouchListener(this); super.setOnFocusChangeListener(this); addTextChangedListener(new TextWatcherAdapter(this, this)); } @Override public void setOnTouchListener(OnTouchListener l) { this.l = l; } @Override public void setOnFocusChangeListener(OnFocusChangeListener f) { this.f = f; } private OnTouchListener l; private OnFocusChangeListener f; @Override public boolean onTouch(View v, MotionEvent event) { if (getCompoundDrawables()[2] != null) { if (event.getAction() == MotionEvent.ACTION_UP) { boolean tappedX = event.getX() > (getWidth() - getPaddingRight() - xD.getIntrinsicWidth()); if (tappedX) { setText(""); if (listener != null) { listener.didClearText(); } return true; } } } if (l != null) { return l.onTouch(v, event); } return false; } @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { setClearIconVisible(isNotEmpty(getText())); } else { setClearIconVisible(false); } if (f != null) { f.onFocusChange(v, hasFocus); } } @Override public void onTextChanged(EditText view, String text) { if (view.isFocused()) setClearIconVisible(isNotEmpty(text)); } protected void setClearIconVisible(boolean visible) { Drawable x = visible ? xD : null; setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], x, getCompoundDrawables()[3]); } }
public class Prime { public static void main(String[] args) { int limit =50000; boolean[] prime = new boolean[limit+1]; prime[0] = true; prime[1] = true; for(int i=2;i<limit+1;i++) { if(!prime[i]) { for(int j=2; i*j<=limit; j++) { prime[i*j]=true; } } } for (int i = 0; i < prime.length; i++) { if(!prime[i]) { System.out.println(i); } } } }
package com.jagdish.bakingapp; import android.app.Application; public class BakingApplication extends Application { public static final String TAG = BakingApplication.class.getName(); private static BakingApplication instance; @Override public void onCreate() { super.onCreate(); } public BakingApplication() { // TODO Auto-generated constructor stub instance = this; } public static BakingApplication getContext() { if (instance == null) { instance = new BakingApplication(); } return instance; } }
package com.example.isufdeliu; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; public class KosovoImage extends Activity { final static String IMAGE_URL = "http://img.fotocommunity.com/images/Balkans/Kosovo/Newborn-Prishtina-a27506692.jpg"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_kosovo_image); try { new DownloadImageTask().execute(new URL(IMAGE_URL)); } catch (MalformedURLException e) { e.printStackTrace(); } } private class DownloadImageTask extends AsyncTask<URL, Void, Bitmap> { @Override protected Bitmap doInBackground(URL... urls) { assert urls.length == 1; // sanity check return downloadImage(urls[0]); } @Override protected void onPostExecute(Bitmap bitmap) { // Then display the image to a view final ImageView img = (ImageView) findViewById(R.id.ksImage); img.setImageBitmap(bitmap); } } private Bitmap downloadImage(final URL url) { Bitmap bitmap = null; InputStream in = null; try { in = openHttpConnection(url); bitmap = BitmapFactory.decodeStream(in); in.close(); } catch (IOException e) { e.printStackTrace(); } return bitmap; } private InputStream openHttpConnection(final URL url) throws IOException { InputStream in = null; int response = -1; final URLConnection conn = url.openConnection(); if (!(conn instanceof HttpURLConnection)) { throw new IOException("Not an HTTP connection"); } try { final HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setAllowUserInteraction(false); httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.connect(); response = httpConn.getResponseCode(); if (response == HttpURLConnection.HTTP_OK) { in = httpConn.getInputStream(); } } catch (Exception ex) { ex.printStackTrace(); } return in; } }
package no.ntnu.stud.ubilearn.models; import java.util.Date; import no.ntnu.stud.ubilearn.R; import no.ntnu.stud.ubilearn.fragments.handbook.ArticleFragment; /** * Simple model containing data for Articles used in {@link ArticleFragment}. */ public class Article extends ListItem{ private String objectId; private String title; private String content; private Date createdAt; public Article(String title, String content) { this.title = title; this.content = content; } // public Article(long id, String objectId, String title, String content, Date createdAt, long parentId) { // super(); // this.id = id; // this.objectId = objectId; // this.title = title; // this.content = content; // this.createdAt = createdAt; // this.parentId = parentId; // } public Article(String objectId, String title, String content, Date createdAt, String parentId) { super(); this.objectId = objectId; this.title = title; this.content = content; this.createdAt = createdAt; this.parentId = parentId; } @Override protected void setIcon() { this.icon = R.drawable.ic_handbook_black; } public String getObjectId() { return objectId; } public String getTitle() { return title; } public String getContent() { return content; } public Date getCreatedAt() { return createdAt; } public String getParentId(){ return parentId; } @Override public String getName() { return title; } @Override public void setName(String name) { title = name; } public String printContent() { return "Article [objectId=" + objectId + ", title=" + title + ", content=" + content + ", createdAt=" + createdAt + ", parentId=" + parentId + "]"; } @Override public String toString(){ return title; } }
/* * Copyright (c) 2013-2014, Neuro4j.org * * 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.neuro4j.studio.core; import java.util.List; import org.eclipse.gmf.runtime.notation.Edge; import org.eclipse.gmf.runtime.notation.Routing; import org.eclipse.gmf.runtime.notation.datatype.RelativeBendpoint; import org.eclipse.swt.graphics.Color; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Operator Output</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link org.neuro4j.studio.core.OperatorOutput#getSource <em>Source</em>}</li> * <li>{@link org.neuro4j.studio.core.OperatorOutput#getName <em>Name</em>}</li> * <li>{@link org.neuro4j.studio.core.OperatorOutput#getTarget <em>Target</em>}</li> * </ul> * </p> * * @see org.neuro4j.studio.core.Neuro4jPackage#getOperatorOutput() * @model * @generated */ public interface OperatorOutput extends Node { // public static final String POINTS_KEY = "points"; /** * Returns the value of the '<em><b>Source</b></em>' containment reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Source</em>' reference isn't clear, there really should be more of a description * here... * </p> * <!-- end-user-doc --> * * @return the value of the '<em>Source</em>' containment reference. * @see #setSource(ActionNode) * @see org.neuro4j.studio.core.Neuro4jPackage#getOperatorOutput_Source() * @model containment="true" * @generated */ ActionNode getSource(); /** * Sets the value of the '{@link org.neuro4j.studio.core.OperatorOutput#getSource <em>Source</em>}' containment * reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @param value * the new value of the '<em>Source</em>' containment reference. * @see #getSource() * @generated */ void setSource(ActionNode value); /** * Returns the value of the '<em><b>Name</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Name</em>' attribute isn't clear, there really should be more of a description here... * </p> * <!-- end-user-doc --> * * @return the value of the '<em>Name</em>' attribute. * @see #setName(String) * @see org.neuro4j.studio.core.Neuro4jPackage#getOperatorOutput_Name() * @model dataType="org.eclipse.emf.ecore.xml.type.String" * @generated */ String getName(); /** * Sets the value of the '{@link org.neuro4j.studio.core.OperatorOutput#getName <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @param value * the new value of the '<em>Name</em>' attribute. * @see #getName() * @generated */ void setName(String value); /** * Returns the value of the '<em><b>Target</b></em>' reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Target</em>' reference isn't clear, there really should be more of a description * here... * </p> * <!-- end-user-doc --> * * @return the value of the '<em>Target</em>' reference. * @see #setTarget(ActionNode) * @see org.neuro4j.studio.core.Neuro4jPackage#getOperatorOutput_Target() * @model * @generated */ ActionNode getTarget(); /** * Sets the value of the '{@link org.neuro4j.studio.core.OperatorOutput#getTarget <em>Target</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @param value * the new value of the '<em>Target</em>' reference. * @see #getTarget() * @generated */ void setTarget(ActionNode value); public void setNameWithoutNotification(String name); public void setEdge(Edge edge); public Edge getEdge(); public List<RelativeBendpoint> getCoordinates(); public void setCoordinates(List<RelativeBendpoint> coordinates); public List<KeyValuePair> getProperties(); public void addProperty(String key, String value); void setBGColor(Color gray); OperatorOutput cloneForPast(ActionNode target); Routing getRouting(); void setRouting(Routing routing); } // OperatorOutput
package com.trannguyentanthuan2903.yourfoods.history_order_user.model; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.LinearLayoutManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.bignerdranch.expandablerecyclerview.ExpandableRecyclerAdapter; import com.bumptech.glide.Glide; import com.trannguyentanthuan2903.yourfoods.R; import com.trannguyentanthuan2903.yourfoods.history_ship_store.model.ListOrderProduct; import com.trannguyentanthuan2903.yourfoods.history_ship_store.model.OrderItemAdapter; import java.util.List; /** * Created by Administrator on 10/16/2017. */ public class OrderListUserAdapter extends ExpandableRecyclerAdapter<ParentHistoryOrderUser , ListOrderProduct, ParentOrderUserViewHolder, ChildOrderUserViewHolder> { List<ParentHistoryOrderUser> parentList; LayoutInflater inflater ; Context mContext; public OrderListUserAdapter(Context mContext , @NonNull List<ParentHistoryOrderUser> parentList) { super(parentList); this.mContext = mContext; inflater = LayoutInflater.from(mContext); this.parentList = parentList; } @Override public ParentOrderUserViewHolder onCreateParentViewHolder(@NonNull ViewGroup parentViewGroup, int viewType) { View recipeView = inflater.inflate(R.layout.item_user_history_order_parent, parentViewGroup, false); return new ParentOrderUserViewHolder(recipeView); } @Override public ChildOrderUserViewHolder onCreateChildViewHolder(@NonNull ViewGroup childViewGroup, int viewType) { View recipeView = inflater.inflate(R.layout.item_user_history_order_child, childViewGroup, false); return new ChildOrderUserViewHolder(recipeView); } @Override public void onBindParentViewHolder(@NonNull ParentOrderUserViewHolder parentViewHolder, int parentPosition, @NonNull ParentHistoryOrderUser parent) { parentViewHolder.setNameTxtAddressShop(parent.getInfoShopOrder().getAddressShop()); parentViewHolder.setNameTxtShopUserNameItemOrderList(parent.getInfoShopOrder().getNameShop()); parentViewHolder.setNameTxtPhoneNumberShopItemOrderList(parent.getInfoShopOrder().getPhoneNumberShop()); parentViewHolder.setNameTxtTimeOrderShop(parent.getInfoShopOrder().getTimeOrderShop()); String linkPhotoUser = ""; if(parent.getInfoShopOrder().getLinkPhotoShop() != null) linkPhotoUser = parent.getInfoShopOrder().getLinkPhotoShop(); if(!linkPhotoUser.equals("")){ Glide.with(mContext).load(linkPhotoUser).into(parentViewHolder.getImgAvataShopItemOrderHistory()); } if (parent.getInfoShopOrder().getStatusShop() == 0){ parentViewHolder.getImgStatusUser().setVisibility(View.INVISIBLE); } if (parent.getInfoShopOrder().getStatusShop() == 1){ parentViewHolder.getImgStatusUser().setVisibility(View.VISIBLE); parentViewHolder.getImgStatusUser().setImageResource(R.drawable.imgshipped); } if (parent.getInfoShopOrder().getStatusShop() == 2){ parentViewHolder.getImgStatusUser().setVisibility(View.VISIBLE); parentViewHolder.getImgStatusUser().setImageResource(R.drawable.imgcanceled); } } @Override public void onBindChildViewHolder(@NonNull ChildOrderUserViewHolder childViewHolder, int parentPosition, int childPosition, @NonNull ListOrderProduct child) { childViewHolder.recyclerView.setAdapter(new OrderItemAdapter(child.getOrderProductList())); childViewHolder.recyclerView.setLayoutManager(new LinearLayoutManager(mContext)); } }
package info.datacluster.test; import com.google.gson.Gson; import info.datacluster.crawler.utils.UrlUtils; import org.junit.Test; import java.util.Map; public class TaskParseTest { @Test public void test(){ String s = "{\"taskId\":\"1\",\"urls\":\"https://movie.douban.com\",\"className\":\"info.datacluster.example.DoubanCrawler\",\"jarPath\":\"file:E:/IdeaProjects/attackcrawler/example/target/example-1.0-SNAPSHOT.jar\",\"urlFilter\":\"https://movie.douban.com/subject/\"}"; Gson gson = new Gson(); Map<String, Object> param = gson.fromJson(s, Map.class); String taskId = param.get("taskId").toString(); String urls = param.get("urls").toString(); String className = param.get("className").toString(); String jarPath = param.get("jarPath").toString(); String urlFilter = param.get("urlFilter").toString(); String domain = UrlUtils.getDomain(urls.split(";")[0]); System.out.println(domain); } }
package com.example.marta.zoo; import com.example.marta.zoo.animals.Zoo.Visitor; import org.junit.Before; import org.junit.Test; import static junit.framework.Assert.assertEquals; /** * Created by marta on 12/11/2017. */ public class VisitorTest { Visitor visitor; @Before public void before() { visitor = new Visitor("Fran", 60); } @Test public void canGetName() { assertEquals("Fran", visitor.getName()); } @Test public void canGetBudget() { assertEquals(60, visitor.getBudget()); } @Test public void canSpendMoneyFromBudget() { visitor.payFromBudget(15); assertEquals(45, visitor.getBudget()); } @Test public void canCheckFunds() { visitor.checkFunds(17); assertEquals(true, visitor.checkFunds(17)); } }
import java.util.ArrayList; /** * * @author ntnrc */ public class TestDisco { public static void main(String args[]){ ArrayList <Cancion> canciones = new ArrayList(); Cancion cancion1 = new Cancion(1, "como una novela", 3.46); Cancion cancion2 = new Cancion(2, "contra el dragon", 3.48); Cancion cancion3 = new Cancion(3, "viri viri bambam",3.50); canciones.add(cancion1); canciones.add(cancion2); canciones.add(cancion3); String nombre = "lo mas romanticas"; Disco losAcosta = new Disco(nombre, "los acosta", 2005, canciones); System.out.println(losAcosta); } }
package org.exercise; import java.util.List; import java.util.stream.Collectors; public class TestProductSelections { public static void main(String args[]) { List<Laptops> laptops = Laptops.fetchLaptops(); List<Laptops> particularlaptops = laptops.stream().filter(item -> item.getBrandName().equals("lenova")) .filter(item -> item.getPrice() > 30000) .sorted((l1, l2) -> Double.compare(l2.getRatings(), l1.getRatings())).collect(Collectors.toList()); particularlaptops.forEach(item -> System.out.println(item)); } }
package gg.bayes.challenge.persistance.repositories; import gg.bayes.challenge.persistance.model.SpellEventsPO; import gg.bayes.challenge.rest.model.HeroSpells; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import java.util.List; import java.util.UUID; public interface SpellEventRepository extends JpaRepository<SpellEventsPO, UUID> { @Query("select new gg.bayes.challenge.rest.model.HeroSpells(s.spell.name, CAST(count(s.id) as int)) " + "from SpellEventsPO s where s.match.id=:matchId and s.source.name=:heroName " + "group by s.spell.name") List<HeroSpells> getHeroSpellStat(Long matchId, String heroName); }
import java.util.*; public class ARR { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("Enter the size of the array:"); int l=sc.nextInt(); int arr[]=new int[l]; int i,j,k,a,b,c,count=0; System.out.println("Enter the elements of the array:"); for(i=0;i<l;i++) { arr[i]=sc.nextInt(); } System.out.println("Enter the value of a,b,c"); //int arr[]= {3,0,1,1,9,7}; a=sc.nextInt(); b=sc.nextInt(); c=sc.nextInt(); for(i=0;i<l;i++) { for(j=i+1;j<l;j++) { for(k=j+1;k<l;k++) { if((Math.abs(arr[i]-arr[j])<=a) && (Math.abs(arr[j]-arr[k])<=b) && (Math.abs(arr[i]-arr[k])<=c)) { //System.out.println(arr[i]+","+arr[j]+","+arr[k]); count++; } } } } System.out.println("Output : "+count); } }
package tree; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; public class C429 { public static void main(String[] args) { Node t1 = new Node(5); Node t2 = new Node(6); List<Node> childT = new ArrayList<>(); childT.add(t1); childT.add(t2); Node l1 = new Node(3, childT); Node l2 = new Node(2); Node l3 = new Node(4); List<Node> childL = new ArrayList<>(); childL.add(l1); childL.add(l2); childL.add(l3); Node root = new Node(1, childL); solution_1 solution = new solution_1(); List<List<Integer>> res = solution.levelOrder(root); System.out.println(res.toString()); } /** * 429. N ²æÊ÷µÄ²ãÐò±éÀú * */ static class solution_1 { List<List<Integer>> res = new ArrayList<>(); public List<List<Integer>> levelOrder(Node root) { if (root == null) { return res; } Queue<Node> queue = new LinkedList<Node>(); queue.add(root); while (!queue.isEmpty()) { int curSize = queue.size(); List<Integer> tmp = new ArrayList<>(); for (int i = 0; i < curSize; i++) { Node node = queue.poll(); tmp.add(node.val); List<Node> children = node.children; if (children != null) { for (Node n : children) { queue.add(n); } } } res.add(tmp); } return res; } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * MenuUtama.java * * Created on 03 Nov 15, 13:03:37 */ package Forms; import cls.ClassDB; import java.awt.Dimension; import java.awt.Image; import java.awt.Toolkit; import java.io.InputStream; import java.sql.Connection; import java.util.HashMap; import javax.swing.ImageIcon; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.view.JasperViewer; /** * * @author HadraFathaki */ public class MenuUtama extends javax.swing.JFrame { /** Creates new form MenuUtama */ public MenuUtama() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { desktopPane = new javax.swing.JDesktopPane(); jLabel1 = new javax.swing.JLabel(); menuBar = new javax.swing.JMenuBar(); fileMenu = new javax.swing.JMenu(); jMenuItem1 = new javax.swing.JMenuItem(); jMenuItem12 = new javax.swing.JMenuItem(); jMenuItem13 = new javax.swing.JMenuItem(); exitMenuItem = new javax.swing.JMenuItem(); jMenu4 = new javax.swing.JMenu(); jMenuItem2 = new javax.swing.JMenuItem(); jMenuItem3 = new javax.swing.JMenuItem(); editMenu = new javax.swing.JMenu(); jMenuItem10 = new javax.swing.JMenuItem(); jMenuItem11 = new javax.swing.JMenuItem(); jSeparator1 = new javax.swing.JPopupMenu.Separator(); jMenuItem9 = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/wallpaper.jpg"))); // NOI18N jLabel1.setText("jLabel1"); desktopPane.add(jLabel1); jLabel1.setBounds(540, 750, 30, 0); fileMenu.setMnemonic('f'); fileMenu.setText("Input"); jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_B, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem1.setText("Data Barang"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); fileMenu.add(jMenuItem1); jMenuItem12.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem12.setText("Data Pelanggan"); jMenuItem12.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem12ActionPerformed(evt); } }); fileMenu.add(jMenuItem12); jMenuItem13.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK)); jMenuItem13.setText("Data Supplier"); jMenuItem13.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem13ActionPerformed(evt); } }); fileMenu.add(jMenuItem13); exitMenuItem.setMnemonic('x'); exitMenuItem.setText("Exit"); exitMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitMenuItemActionPerformed(evt); } }); fileMenu.add(exitMenuItem); menuBar.add(fileMenu); jMenu4.setText("Transaksi"); jMenuItem2.setText("Penjualan Barang"); jMenuItem2.setRolloverEnabled(true); jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem2ActionPerformed(evt); } }); jMenu4.add(jMenuItem2); jMenuItem3.setText("Pembelian barang"); jMenuItem3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem3ActionPerformed(evt); } }); jMenu4.add(jMenuItem3); menuBar.add(jMenu4); editMenu.setMnemonic('e'); editMenu.setText("Laporan"); jMenuItem10.setText("Penjualan"); jMenuItem10.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem10ActionPerformed(evt); } }); editMenu.add(jMenuItem10); jMenuItem11.setText("Pembelian"); jMenuItem11.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem11ActionPerformed(evt); } }); editMenu.add(jMenuItem11); editMenu.add(jSeparator1); jMenuItem9.setText("Stok Barang"); jMenuItem9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem9ActionPerformed(evt); } }); editMenu.add(jMenuItem9); menuBar.add(editMenu); setJMenuBar(menuBar); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(desktopPane, javax.swing.GroupLayout.DEFAULT_SIZE, 1024, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(desktopPane, javax.swing.GroupLayout.DEFAULT_SIZE, 747, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed System.exit(0); }//GEN-LAST:event_exitMenuItemActionPerformed private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed FrmBarang s=new FrmBarang(); desktopPane.add(s); s.setVisible(true); }//GEN-LAST:event_jMenuItem1ActionPerformed private void jMenuItem12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem12ActionPerformed FrmPelanggan s=new FrmPelanggan(); desktopPane.add(s); s.setVisible(true); }//GEN-LAST:event_jMenuItem12ActionPerformed private void jMenuItem13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem13ActionPerformed FrmSupplier s=new FrmSupplier(); desktopPane.add(s); s.setVisible(true); }//GEN-LAST:event_jMenuItem13ActionPerformed private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed FrmPembelian s=new FrmPembelian(); desktopPane.add(s); s.setVisible(true); }//GEN-LAST:event_jMenuItem3ActionPerformed private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed FrmPenjualan s=new FrmPenjualan(); desktopPane.add(s); s.setVisible(true); }//GEN-LAST:event_jMenuItem2ActionPerformed private void jMenuItem9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem9ActionPerformed Connection con = ClassDB.getkoneksi(); String NamaFile = "/laporan/stokbarang.jasper"; HashMap hash = new HashMap(); try { runReportDefault(NamaFile,hash); } catch (Exception e) { } }//GEN-LAST:event_jMenuItem9ActionPerformed private void jMenuItem10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem10ActionPerformed Connection con = ClassDB.getkoneksi(); String NamaFile = "/laporan/laporanpenjualan.jasper"; HashMap hash = new HashMap(); try { runReportDefault(NamaFile,hash); } catch (Exception e) { } }//GEN-LAST:event_jMenuItem10ActionPerformed private void jMenuItem11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem11ActionPerformed Connection con = ClassDB.getkoneksi(); String NamaFile = "/laporan/laporanpembelian.jasper"; HashMap hash = new HashMap(); try { runReportDefault(NamaFile,hash); } catch (Exception e) { } }//GEN-LAST:event_jMenuItem11ActionPerformed public void runReportDefault(String sourcefilename, HashMap hash) { Connection con = ClassDB.getkoneksi(); try { InputStream report; report = getClass().getResourceAsStream(sourcefilename); JasperPrint jprint = JasperFillManager.fillReport(report,hash, con); JasperViewer viewer = new JasperViewer(jprint, false); viewer.setFitPageZoomRatio(); viewer.setVisible(true); } catch (Exception e) { System.out.print(e.getMessage()); } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MenuUtama.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MenuUtama.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MenuUtama.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MenuUtama.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MenuUtama().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JDesktopPane desktopPane; private javax.swing.JMenu editMenu; private javax.swing.JMenuItem exitMenuItem; private javax.swing.JMenu fileMenu; private javax.swing.JLabel jLabel1; private javax.swing.JMenu jMenu4; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem10; private javax.swing.JMenuItem jMenuItem11; private javax.swing.JMenuItem jMenuItem12; private javax.swing.JMenuItem jMenuItem13; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JMenuItem jMenuItem9; private javax.swing.JPopupMenu.Separator jSeparator1; private javax.swing.JMenuBar menuBar; // End of variables declaration//GEN-END:variables }
package design_pattern.factory.parts; import design_pattern.factory.Factory; import design_pattern.factory.Part; public class Vision extends Part { public static class VisionFactory implements Factory<Vision> { public Vision create(){ System.out.println("create Vision"); return new Vision(); } } }
package com.mobile.mobilehardware.hook; import android.content.Context; import org.json.JSONObject; /** * @author 谷闹年 * @date 2018/8/8 * Xposed CydiaSubstrate 框架检测工具类 */ public class HookHelper extends HookInfo { /** * 判断是否有xposed等hook工具 * * @param context * @return */ public static JSONObject isXposedHook(Context context) { return getXposedHook(context); } }
package escolasis.modelo.dao.jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import escolasis.exceptions.AutenticacaoException; import escolasis.modelo.Pessoa; import escolasis.modelo.TokenUsuario; import escolasis.modelo.dao.interfaces.PessoaDao; import escolasis.modelo.xml.ListaPessoa; import escolasis.utils.Utils; public class JdbcPessoaDao implements PessoaDao { Connection conexao; public JdbcPessoaDao(Connection conexao) { this.conexao = conexao; } @Override public void salvar(Pessoa pessoa) { if (!cpfValido(pessoa.getCpf())) { throw new RuntimeException("CPF Inválido"); } String sql = "insert into tab_pessoa values (?,?,?,?)"; try { PreparedStatement insert = this.conexao.prepareStatement(sql); insert.setString(1, pessoa.getCpf()); insert.setString(2, pessoa.getNome()); insert.setDate(3, Utils.converteLocalDateToDate(pessoa.getDtNascto())); insert.setLong(4, pessoa.getIdPapelPessoa()); insert.execute(); this.conexao.commit(); } catch (Exception e) { try { this.conexao.rollback(); } catch (Exception e1) { throw new RuntimeException("Falha ao executar o rollback",e1); } throw new RuntimeException("Falha ao inserir na tabela tab_pessoa",e); } } @Override public List<Pessoa> listar() { String sql = "select * from tab_pessoa"; List<Pessoa> lista = new ArrayList<Pessoa>(); try { ResultSet consulta = this.conexao.createStatement().executeQuery(sql); while(consulta.next()) { Pessoa pessoa = new Pessoa(consulta.getString(1),consulta.getString(2), Utils.converteDateToLocalDate(consulta.getDate(3)), consulta.getLong(4)); lista.add(pessoa); } } catch (Exception e) { throw new RuntimeException("Falha ao obter registros de Pessoa",e); } return lista; } @Override public ListaPessoa salvar(TokenUsuario token, ListaPessoa pessoas) throws AutenticacaoException, ParseException { System.out.println("Salvando a lista de pessoas"); if (!Utils.tokenVerdadeiro(token)) { throw new AutenticacaoException("Falha na autenticação"); } for (Pessoa pessoa : pessoas.getPessoas()) { salvar(pessoa); } return pessoas; } private boolean cpfValido(String cpf) { if (cpf.length() < 11) { return false; } return true; } }
package com.gxtc.huchuan.ui.live.invitation; import android.os.Bundle; import android.view.View; import com.gxtc.commlibrary.base.BaseTitleActivity; import com.gxtc.huchuan.R; import butterknife.OnClick; /** * Created by Gubr on 2017/3/17. */ public class ActivityInvitationHonored extends BaseTitleActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_invitation_honored); } @Override public void initView() { getBaseHeadView().showTitle("邀请嘉宾"); getBaseHeadView().showBackButton(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } @OnClick(R.id.btn_submit) public void onClick(View view) { } }
/* * Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.webui.common; import com.vaadin.data.Validatable; import com.vaadin.data.Validator.InvalidValueException; import com.vaadin.ui.AbstractComponent; import com.vaadin.ui.Component; import com.vaadin.ui.HasComponents; /** * Simple form validator. Instead of employing the whole Vaadin infrastructure, this one * simply iterates over all components of a container recursively. If error is found * then error state is set and finally an exception is thrown. * * Disabled components are ignored. * * @author K. Benedyczak */ public class FormValidator { private HasComponents container; public FormValidator(HasComponents container) { this.container = container; } public void validate() throws FormValidationException { if (validate(container)) throw new FormValidationException(); } private boolean validate(HasComponents container) { boolean invalid = false; for (Component c: container) { if (c instanceof HasComponents) invalid |= validate((HasComponents)c); if (c instanceof Validatable && c instanceof AbstractComponent) invalid |= validateComponent((Validatable)c); } return invalid; } private boolean validateComponent(Validatable c) { if (!((AbstractComponent)c).isEnabled()) return false; try { c.validate(); return false; } catch (InvalidValueException e) { return true; } } }
package com.movieapp.anti.movieapp.Api; public class ApiConstants { public static final String ConsumerKey = "api_key=1702d47c418687e73ada55eda26d078b"; // public static final String PHOTOS_ENDPOINT = "ticker/"; }
package com.example.hellostudiotesting; import android.app.Application; import android.test.ActivityInstrumentationTestCase2; import android.test.ApplicationTestCase; import android.widget.TextView; /** * A Simple test of the Main Activity */ public class MainTest extends ActivityInstrumentationTestCase2<MainActivity> { public MainTest() { super("my.pkg.app", MainActivity.class); } public void test() { TextView textView = (TextView) getActivity().findViewById(R.id.textView); assertEquals("Hello World!", textView.getText()); } }
package com.barrunner.view; import java.util.LinkedList; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.barrunner.factories.TileHandler; import com.barrunner.model.EntityMovable; import com.barrunner.model.Level; public class LevelRenderer { /* Variables */ private Level level; private SpriteBatch batch; private Texture [] floorTextures; private Texture [] propTextures; private Texture [] backgroundTextures; private Texture [] foregroundTextures; private TextureRegion [] floorRegions; private TextureRegion [] propRegions; private TextureRegion [] foregroundRegions; private TextureRegion [] backgroundRegions; /* Constructors */ public LevelRenderer(Level level, SpriteBatch batch) { this.level = level; this.batch = batch; floorTextures = new Texture[2]; backgroundTextures = new Texture[3]; foregroundTextures = new Texture[3]; propTextures = new Texture[3]; floorRegions = new TextureRegion[2]; backgroundRegions = new TextureRegion[3]; foregroundRegions = new TextureRegion[3]; propRegions = new TextureRegion[3]; //HardCoded textures for now floorTextures[0] = new Texture("floors/ground.png"); floorTextures[1] = new Texture("floors/ground_inverted.png"); // floorTextures[1] = new Texture("floors/floor.png"); floorRegions[0] = new TextureRegion(floorTextures[0]); floorRegions[1] = new TextureRegion(floorTextures[1]); backgroundTextures[0] = new Texture("backgrounds/smoke.png"); backgroundTextures[1] = new Texture("backgrounds/trippy.png"); backgroundTextures[2] = new Texture("silhouettes/bannana.png"); backgroundRegions[0] = new TextureRegion(backgroundTextures[0]); backgroundRegions[1] = new TextureRegion(backgroundTextures[1]); backgroundRegions[2] = new TextureRegion(backgroundTextures[2]); foregroundTextures[0] = new Texture("props/light1.png"); foregroundTextures[1] = new Texture("props/pool_table1.png"); foregroundTextures[2] = new Texture("silhouettes/double_fist.png"); foregroundRegions[0] = new TextureRegion(foregroundTextures[0]); foregroundRegions[1] = new TextureRegion(foregroundTextures[1]); foregroundRegions[2] = new TextureRegion(foregroundTextures[2]); propTextures[0] = new Texture("props/bar1.png"); propTextures[1] = new Texture("props/bar2.png"); propTextures[2] = new Texture("props/light1.png"); propRegions[0] = new TextureRegion(propTextures[0]); propRegions[1] = new TextureRegion(propTextures[1]); propRegions[2] = new TextureRegion(propTextures[2]); } /* Methods */ public void renderBackground() { renderTilesForEachSetOfHandlers(level.getBackgroundHandlers(),backgroundRegions); renderTilesForEachSetOfHandlers(level.getPropHandlers(),propRegions); renderTilesForEachSetOfHandlers(level.getFloorHandlers(),floorRegions); } public void renderForeground() { renderTilesForEachSetOfHandlers(level.getForegroundHandlers(),foregroundRegions); } /* Helper Methods */ private void renderTilesForEachSetOfHandlers(LinkedList<TileHandler> handlers, TextureRegion[] textureArray) { for(TileHandler handler : handlers) { for(Object tile : level.getTilesFromHandler(handler)) { drawTile(tile, textureArray); } } } private void drawTile(Object tile, TextureRegion[] textureArray) { batch.draw(textureArray[((EntityMovable) tile).getTypeID()], ((EntityMovable) tile).getX(), ((EntityMovable) tile).getY(), 0f, 0f, ((EntityMovable) tile).getTextureWidth(), ((EntityMovable) tile).getTextureHeight(), 1f, 1f, ((EntityMovable) tile).getRotation()); } }
package ioc.Demo_16; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.annotation.Resource; /** * Created by Yingjie.Lu on 2018/8/3. */ @Component public class People { @Value("1") private int id; @Value("张三") private String name; @Value("12") private int age; @Autowired //会从容器中按照类型去匹配 private Dog dogs; @Resource(name = "cat") //会从容器中按照名称去匹配,默认的名称是成员变量中的名称 private Cat cat; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Dog getDogs() { return dogs; } public void setDogs(Dog dogs) { this.dogs = dogs; } @Override public String toString() { return "People{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", dogs=" + dogs + ", cat=" + cat + '}'; } }
package controller; import database.dao.Dao; import database.entity.User; import javafx.collections.ObservableList; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.util.Callback; import utils.Method; import utils.UtilFunctions; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.ResourceBundle; import static javafx.collections.FXCollections.observableArrayList; import static utils.UtilFunctions.isNullString; /** * Created by Алексей on 13.06.2016. */ public class RegistryController implements Initializable { public static Dao<User> userDao; public static Stage STAGE; public static Pane parentPane; public Button reset; public Button signUp; public TextField login; public PasswordField password; public TextField firstName; public TextField lastName; public Button back; public ComboBox<Method> firstMethod; public ComboBox<Method> secondMethod; public Label outputErrorText; private final ObservableList<Method> methods; private StringBuilder errorText; public RegistryController() { methods = observableArrayList( new Method("MonoAlphabet", "моноалфавитная замена"), new Method("HomophonyReplacement", "гомофоническая замена"), new Method("PolyalphabeticReplacement", "полиалфавитная замена"), new Method("PoligrammnayaReplacement", "полиграммная замена"), new Method("VerticalPermutation", "вертикальная перестановка с ключом"), new Method("BitRevers", "побитовая перестановка"), new Method("VizhinerMethod", "код Виженера"), new Method("XOR", "гоммирование с ключом") ); } public void initialize(URL location, ResourceBundle resources) { setSettingComboBox(firstMethod); setSettingComboBox(secondMethod); } private void setSettingComboBox(ComboBox<Method> comboBox) { comboBox.setItems(methods); comboBox.getSelectionModel().selectFirst(); //select the first element comboBox.setCellFactory(new Callback<ListView<Method>, ListCell<Method>>() { @Override public ListCell<Method> call(ListView<Method> p) { return new ListCell<Method>() { @Override protected void updateItem(Method t, boolean bln) { super.updateItem(t, bln); if (t != null) { setText(t.getMethodCaption()); } else { setText(null); } } }; } }); } public void backAction() { STAGE.close(); parentPane.setDisable(false); } public void resetAction() { this.login.clear(); this.firstName.clear(); this.lastName.clear(); this.password.clear(); this.outputErrorText.setText(""); } public void singUpAction() { if (!isValidFields()) { outputErrorText.setText("Не заполнены обязательные поля: " + errorText.toString()); outputErrorText.setTextFill(Color.FIREBRICK); return; } if (isExistsUser()) { outputErrorText.setText("Пользователь с логином: " + login.getText() + " существует!"); outputErrorText.setTextFill(Color.FIREBRICK); return; } User user = createUser(); userDao.addObject(user); backAction(); } private User createUser() { User user = new User(); user.setLogin(login.getText()); user.setPassword(UtilFunctions.md5Custom(password.getText())); String firstName = isNullString(this.firstName.getText())? "" : this.firstName.getText(); String lastName = isNullString(this.lastName.getText()) ? "" : this.lastName.getText(); user.setFirstName(firstName); user.setLastName(lastName); Method first, second; first = firstMethod.getValue(); second = secondMethod.getValue(); if (first.equals(second)) { user.setMethods(Collections.singletonList(first.getMethodName())); } else { user.setMethods(Arrays.asList(first.getMethodName(), second.getMethodName())); } return user; } private boolean isValidFields() { boolean result = true; errorText = new StringBuilder(""); if (isNullString(login.getText())) { errorText = errorText.append("Логин; "); result = false; } if (isNullString(password.getText())) { errorText= errorText.append("Пароль; "); result = false; } return result; } private boolean isExistsUser() { User user = userDao.getEntityByStringProperty("login", login.getText()); return user != null; } }
package br.assembleia.controle; import javax.annotation.PostConstruct; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import br.assembleia.entidades.Congregacao; import br.assembleia.enuns.EnumEstado; import br.assembleia.service.CongregacaoService; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.PersistenceException; import javax.servlet.ServletContext; import org.primefaces.event.FileUploadEvent; import org.primefaces.model.DefaultStreamedContent; import org.primefaces.model.StreamedContent; import org.primefaces.model.UploadedFile; @Controller @Scope("session") public class CongregacaoControle { private Congregacao congregacao; private List<Congregacao> congregacaos; private List<Congregacao> congregacaosFiltrados; private String titulo; private StreamedContent fotoBanco; private UploadedFile file; private byte[] bimagem; private File arquivo; FacesContext facesContext = FacesContext.getCurrentInstance(); ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext(); String teste = servletContext.getRealPath("/Resources/img/semFoto2.jpg"); @Autowired private CongregacaoService service; @PostConstruct private void init() { congregacao = new Congregacao(); } public String novo() throws FileNotFoundException { congregacao = new Congregacao(); titulo = "Cadastrar Congregacao"; arquivo = new File(teste); InputStream f = new FileInputStream(arquivo); StreamedContent img = new DefaultStreamedContent(f); fotoBanco = img; return "form?faces-redirect=true"; } public String carregarCadastro() { if (congregacao != null) { titulo = "Editar Congregacao"; fotoBanco = new DefaultStreamedContent(new ByteArrayInputStream(congregacao.getLogoIgreja())); return "form?faces-redirect=true"; } adicionaMensagem("Nenhuma Congregacao foi selecionada para a alteração!", FacesMessage.SEVERITY_INFO); return "lista?faces-redirect=true"; } public String salvar() throws IOException { try { if (congregacao.getId() == null && file == null) { Path path = Paths.get(teste); byte[] data = Files.readAllBytes(path); congregacao.setLogoIgreja(data); service.salvar(congregacao); adicionaMensagem("Congregacao salva com sucesso!", FacesMessage.SEVERITY_INFO); fotoBanco = null; arquivo = null; } else if (file == null && congregacao.getId() != null) { service.salvar(congregacao); adicionaMensagem("Congregacao salva com sucesso!", FacesMessage.SEVERITY_INFO); fotoBanco = null; arquivo = null; } else { bimagem = file.getContents(); congregacao.setLogoIgreja(bimagem); service.salvar(congregacao); adicionaMensagem("Congregacao salva com sucesso!", FacesMessage.SEVERITY_INFO); congregacao = null; fotoBanco = null; arquivo = null; } } catch (PersistenceException ex) { adicionaMensagem(ex.getMessage(), FacesMessage.SEVERITY_ERROR); } return "lista?faces-redirect=true"; } public void chamarExclusao() { if (new AplicacaoControle().validaUsuario()) { if (congregacao == null) { adicionaMensagem("Nenhuma Congregacao foi selecionada para a exclusão!", FacesMessage.SEVERITY_INFO); return; } org.primefaces.context.RequestContext.getCurrentInstance().execute("confirmacaoMe.show()"); } } public String deletar() { try { service.deletar(congregacao); congregacaos = null; adicionaMensagem("Congregação Excluida com Sucesso!", FacesMessage.SEVERITY_INFO); } catch (PersistenceException ex) { adicionaMensagem(ex.getMessage(), FacesMessage.SEVERITY_INFO); voltar(); } return "lista?faces-redirect=true"; } public String voltar() { congregacao = null; return "lista?faces-redirect=true"; } public static void adicionaMensagem(String message, FacesMessage.Severity tipo) { FacesContext context = FacesContext.getCurrentInstance(); context.getExternalContext().getFlash().setKeepMessages(true); context.addMessage(null, new FacesMessage(tipo, message, null)); } public List<Congregacao> getCongregacaos() { congregacaos = service.listarTodos(); Collections.sort(congregacaos); return congregacaos; } public void setCongregacaos(List<Congregacao> congregacaos) { this.congregacaos = congregacaos; } public Congregacao getCongregacao() { return congregacao; } public void setCongregacao(Congregacao congregacao) { this.congregacao = congregacao; } public String getTitulo() { return titulo; } public void setTitulo(String titulo) { this.titulo = titulo; } public List<Congregacao> getCongregacaosFiltrados() { return congregacaosFiltrados; } public void setCongregacaosFiltrados(List<Congregacao> congregacaosFiltrados) { this.congregacaosFiltrados = congregacaosFiltrados; } public List<EnumEstado> getListaEstado() { return Arrays.asList(EnumEstado.values()); } public void fileUploadAction(FileUploadEvent event) { try { InputStream is = event.getFile().getInputstream(); fotoBanco = new DefaultStreamedContent(is); file = event.getFile(); } catch (IOException ex) { Logger.getLogger(MembroControle.class.getName()).log(Level.SEVERE, null, ex); } } public StreamedContent getFotoBanco() { return fotoBanco; } public void setFotoBanco(StreamedContent fotoBanco) { this.fotoBanco = fotoBanco; } public UploadedFile getFile() { return file; } public void setFile(UploadedFile file) { this.file = file; } public File getArquivo() { return arquivo; } public void setArquivo(File arquivo) { this.arquivo = arquivo; } public byte[] getBimagem() { return bimagem; } public void setBimagem(byte[] bimagem) { this.bimagem = bimagem; } }
package me.ThaH3lper.com.Grades; import java.util.ArrayList; import java.util.List; import java.util.Random; import me.ThaH3lper.com.Dungeon; public class Grade { public float boost; public int levels; public int lives; Dungeon dun; public List<String> waves= new ArrayList<String>(); Random r = new Random(); public Grade(Float boost, int levels, List<String> waves, int lives, Dungeon dun) { this.dun = dun; this.boost = boost; this.levels = levels; this.waves = waves; this.lives = lives; } public Wave GetWave(String name) { for(Wave w : dun.waveList) { if(w.Name.equals(name)) return w; } return null; } public Wave getWaveForLevel(int lvl) { String[] parts = waves.get(lvl - 1).split(","); String s = parts[r.nextInt(parts.length)]; return GetWave(s); } }
package com.miro.platform.widget.config; import com.miro.platform.widget.domain.repository.WidgetRepo; import com.miro.platform.widget.domain.service.WidgetService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import java.util.concurrent.locks.StampedLock; @Configuration public class WidgetApplicationConfig { @Autowired private ApplicationContext context; @Bean @Primary public WidgetService WidgetService(@Value("${service.type}") String qualifier) { return (WidgetService) context.getBean(qualifier); } @Bean @Primary public WidgetRepo WidgetRepo(@Value("${storage.type}") String qualifier) { return (WidgetRepo) context.getBean(qualifier); } @Bean public StampedLock StampedLock() { return new StampedLock(); } }
package com.Premium.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import lombok.Data; import lombok.NonNull; @Entity @Table(name = "Roles") @Data public class Roles { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer role_id; @Column @NonNull private String name; @Column private String description; }
package com.example.laptopstore; public class LaptopModel { //region property private String model; private boolean status; private String company; private String madeIn; private int price; //endregion //region Constructor public LaptopModel(String model, boolean status, String company, String madeIn, int price) { this.model = model; this.status = status; this.company = company; this.madeIn = madeIn; this.price = price; } //endregion //region Getters & Setters public String getModel() { return model; } public void setModel(String model) { this.model = model; } public boolean isStatus() { return status; } public void setStatus(boolean status) { this.status = status; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getMadeIn() { return madeIn; } public void setMadeIn(String madeIn) { this.madeIn = madeIn; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } //endregion }
package com.atguigu.lgl; // 创建线程的方式之二: 实现Runnable接口 class TestLuo4 implements Runnable{ @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println(Thread.currentThread().getName()+ "--" + i); } } } public class MakeThread2_2 { public static void main(String[] args) { //主线程 for (int i = 0; i < 100; i++) { System.out.println(Thread.currentThread().getName()+ "++" + i); } //普通 TestLuo4 testLuo4 = new TestLuo4(); Thread thread = new Thread(testLuo4); thread.start(); //匿名对象 new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println(Thread.currentThread().getName()+ "==" + i); } } }).start(); } }
package com.atguigu.java; public class Creature { public void show(){ System.out.println("creature show"); } public void say(){ System.out.println("creature say"); } }
package io.jee.alaska.util; import javax.servlet.http.HttpServletRequest; public class UrlUtils { public static StringBuffer currentProject(HttpServletRequest request){ StringBuffer buffer = new StringBuffer(request.isSecure() ? "https://" : "http://"); buffer.append(request.getServerName()); if ((request.isSecure() && request.getServerPort() != 443) || (!request.isSecure() && request.getServerPort() != 80)) { buffer.append(":"); buffer.append(request.getServerPort()); } buffer.append(request.getContextPath()); return buffer; } }
package com.classroom.app.services; import com.classroom.app.Interfaces.SignUpInterface; import com.classroom.app.database.DBConnection; import com.classroom.app.model.SignIn; import com.classroom.app.model.SignUp; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; /** * Created by Muhammad Sadiq Saeed on 3/2/2017. */ public class SignUpService implements SignUpInterface { private Connection con = null; private String id; private String Message = null; private DBConnection dbConnection = new DBConnection(); @Override public String createUser(String userName, String email, String password) { SignUpService signUpService = new SignUpService(); KeyGenerationService keyGenerationService = new KeyGenerationService(); id = keyGenerationService.generateRandomString(6); SignUp signUp = new SignUp(userName, email, password); try { con = dbConnection.openConnection(); Statement statement = con.createStatement(); String Query = "Insert into signup (id, userName, email, password, status) Values ('" + id + "'," + "'" + signUp.getUserName() + "', '" + signUp.getEmail() + "', '" + signUp.getPassword() + "', '" + signUp.getStatus() + "')"; String checkMessage1 = null; String checkMessage2 = null; checkMessage1 = signUpService.checkIfUserExists(email); checkMessage2 = signUpService.checkUserName(userName); if (checkMessage1 != null) { Message = checkMessage1; } else if (checkMessage2 != null) { Message = checkMessage2; } else { statement.execute(Query); Message = "Account created Successfully!!! "; } } catch (SQLException ex) { System.out.println(ex.getMessage()); } finally { dbConnection.closeConnection(con); } return Message; } @Override public String checkIfUserExists(String email) { try { con = dbConnection.openConnection(); String query = "Select email from signUp where email = '" + email + "' "; Statement statement = con.createStatement(); ResultSet resultSet = statement.executeQuery(query); if (resultSet.next()) { email = resultSet.getString("email"); if (email != null) { Message = "Account with this email already exists"; } } } catch (SQLException e) { System.out.println(e.getMessage()); } return Message; } @Override public String checkUserName(String userName) { try { con = dbConnection.openConnection(); String query = "Select userName from signUp where userName = '" + userName + "'"; Statement statement = con.createStatement(); ResultSet resultSet = statement.executeQuery(query); if (resultSet.next()) { userName = resultSet.getString("userName"); if (userName != null) { Message = "Username already in use!!! "; } } } catch (SQLException e) { System.out.println(e.getMessage()); } return Message; } @Override public List<SignUp> getUserData(String userName) { List<SignUp> userData = new ArrayList<>(); try { con = dbConnection.openConnection(); String query = "SELECT * FROM signUp WHERE userName = '" + userName + "'"; Statement statement = con.createStatement(); ResultSet resultSet = statement.executeQuery(query); while (resultSet.next()) { SignUp signUp = new SignUp(); signUp.setId(resultSet.getString("id")); signUp.setUserName(resultSet.getString("userName")); signUp.setEmail(resultSet.getString("email")); signUp.setPassword(resultSet.getString("password")); userData.add(signUp); } } catch (SQLException e) { System.out.println(e.getMessage()); } finally { dbConnection.closeConnection(con); } return userData; } @Override public String updateUserData(String id, String userName, String password) { SignUpService signUpService = new SignUpService(); SignUp signUp = new SignUp(); signUp.setId(id); signUp.setUserName(userName); signUp.setPassword(password); String checkMessage = null; try { con = dbConnection.openConnection(); Statement statement = con.createStatement(); String query = "UPDATE signUp SET userName = '" + signUp.getUserName() + "', password = '" + signUp.getPassword() + "' WHERE id = '" + signUp.getId() + "'"; checkMessage = signUpService.checkUserName(userName); if (checkMessage != null) { Message = checkMessage; } else { statement.execute(query); Message = "Saved!!! "; } } catch (SQLException ex) { System.out.println(ex.getMessage()); } finally { dbConnection.closeConnection(con); } return Message; } @Override public String updateStatus(String id) { SignIn signIn = new SignIn(); try { con = dbConnection.openConnection(); Statement statement = con.createStatement(); signIn.setStatus(checkStatus(id)); if (signIn.getStatus() == 0) { signIn.setStatus(1); String query = "Update signup set status = '" + signIn.getStatus() + "' where id = '" + id + "'"; statement.execute(query); Message = "Account Activated Successfully!!!! "; } else if (signIn.getStatus() == 1) { Message = "Your Account is already activated!!!! "; } else if (signIn.getStatus() == 2) { Message = "Your account is blocked and cannot be activated!!!! "; } } catch (SQLException ex) { System.out.println(ex.getMessage()); } finally { dbConnection.closeConnection(con); } return Message; } @Override public int checkStatus(String id) { int status = 0; try { con = dbConnection.openConnection(); Statement statement = con.createStatement(); String query = "Select status from signup where id= '" + id + "'"; ResultSet resultSet = statement.executeQuery(query); while (resultSet.next()) { status = resultSet.getInt("status"); } } catch (SQLException ex) { System.out.println(ex.getMessage()); } finally { dbConnection.closeConnection(con); } return status; } }
package com.fbzj.track.exception; public class ApiException extends Exception implements ErrorCode { /** * serialVersionUID */ private static final long serialVersionUID = -1102180882102959348L; public static long getSerialversionuid() { return serialVersionUID; } /** * 错误代码 */ private int code; /** * 构造函数 * * @param errorCode * 错误代码 * @param message * 消息内容 */ public ApiException(int errorCode, String message) { super(message); this.code = errorCode; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } }
package plin.net.br.plin.activities; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.webkit.WebResourceRequest; import android.webkit.WebResourceResponse; import android.webkit.WebView; import android.webkit.WebViewClient; /** * Created by sandeco on 05/04/16. */ class MyWebViewClient extends WebViewClient { private final String FACEBOOK = "com.facebook.katana"; private final String TWITTER = "com.twitter.android"; private final String INSTAGRAM = "com.instagram.android"; private final String GOOGLEPLUS = "com.plus.google"; private Context context; public MyWebViewClient(Context context){ this.context = context; } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // String not in Logger. if (url != null) { if( url.startsWith("whatsapp://") || url.startsWith("https://twitter.com/") || url.startsWith("https://plus.google.com/") || url.startsWith("https://www.facebook.com/") ){ view.getContext().startActivity( new Intent(Intent.ACTION_VIEW, Uri.parse(url))); return true; } else { return false; } } return false; } @Override public void onPageFinished(WebView view, String url) { } }
package com.explore.service; import com.explore.common.ServerResponse; import com.explore.pojo.Conf; import com.explore.vo.ConfVo; /** * @author PinTeh * @date 2019/5/25 */ public interface IConfService { ServerResponse save(Conf conf); ServerResponse update(Conf conf); ServerResponse delete(Integer id); ServerResponse sources(); ServerResponse emp(); ServerResponse updateByCodeAndCampusId(ConfVo confVo); }
package com.jihu.service; import com.jihu.entity.User; import java.util.Set; public interface UserService { User findByUsername(String username); Set<String> findRoles(String username); Set<String> findPermissions(String username); }
package com.esum.comp.jms.converter; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Session; import com.esum.framework.core.event.message.MessageEvent; public interface MessageTypeHandler { String MESSAGE_CTRL_ID = "MESSAGE_CTRL_ID"; String MESSAGE_NUMBER = "MESSAGE_NUMBER"; String MESSAGE_NAME = "MESSAGE_NAME"; String MESSAGE_SENDER_ID = "MESSAGE_SENDER_ID"; String MESSAGE_RECEIVER_ID = "MESSAGE_RECEIVER_ID"; public Message toMessage(Session session, MessageEvent messageEvent) throws JMSException; public byte[] fromMessage(Message jmsMessage) throws JMSException; }
package com.pbadun.database; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DBase extends SQLiteOpenHelper { public static final String DATABASE_NAME = "datebase.db"; private static final int DATABASE_VER = 1; public static final String TABLE_NAME = "rss_tab"; public static final String UID = "id"; public static final String TITLE = "title"; public static final String DESCRIPTION = "description"; public static final String PUBDATE = "date"; public static final String ICON = "img"; public static final String LINK = "url"; private static final String CREATE_QUERY = "CREATE TABLE " + TABLE_NAME + " ( " + UID + " INTEGER PRIMARY KEY AUTOINCREMENT , " + TITLE + " TEXT ," + DESCRIPTION + " TEXT NOT NULL ," + PUBDATE + " TEXT ," + ICON + " TEXT ," + LINK + " TEXT " + ") ;"; public DBase(Context context) { super(context, DATABASE_NAME, null, DATABASE_VER); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_QUERY); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
package com.sandrapenia.entities.uml; import com.sandrapenia.entities.Entity; /** Representa los objetos de tipo Parametro **/ public class UMLParameter extends Entity { private String name; private String type; public UMLParameter(String type, String name) { this.type = type; this.name = name; } public UMLParameter() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public String toString() { return type + " " + name; } }
package com.dassa.service; import java.util.ArrayList; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.dassa.mapper.ShopPremiumMapper; import com.dassa.vo.ShopPaymentVO; import com.dassa.vo.ShopPowerItemVO; import com.dassa.vo.ShopPremiumItemVO; @Service("shopPremiumService") public class ShopPremiumService { @Resource(name="shopPremiumMapper") private ShopPremiumMapper shopPremiumMapper; /** * 상품 구매 - 등록개수 * @param spiVo * @return * @throws Exception */ public int shopPayment(ShopPaymentVO spVo) throws Exception { return shopPremiumMapper.shopPayment(spVo); } public int PremiumItemAdd(ShopPremiumItemVO spiVo) throws Exception { shopPremiumMapper.PremiumItemAdd(spiVo); return shopPremiumMapper.PremiumItemAdd(spiVo); } /** * 상품 구매 - 파워링크 * @param spiVo * @return * @throws Exception */ public int PowerItemAdd(ShopPowerItemVO powerVo) throws Exception { return shopPremiumMapper.PowerItemAdd(powerVo); } /** * 등록 가능 매물 개수 * @param userIdx * @return * @throws Exception */ public int shopCount(int userIdx) throws Exception{ ArrayList<ShopPremiumItemVO> list = shopPremiumMapper.shopCount(userIdx); int arrSize = list.size(); System.out.println("service userIdx : "+userIdx); System.out.println("return count : "+arrSize); return arrSize; } /** * 아이템 적용 가능 매물 개수 * @param userIdx * @return * @throws Exception */ public int powerCount(int userIdx) throws Exception{ ArrayList<ShopPowerItemVO> list = shopPremiumMapper.powerCount(userIdx); int arrSize = list.size(); System.out.println("service userIdx : "+userIdx); System.out.println("return count : "+arrSize); return arrSize; } public ArrayList<ShopPaymentVO> ShopPemiumItemList(int userIdx) throws Exception{ return shopPremiumMapper.ShopPemiumItemList(userIdx); } }
package com.culturaloffers.maps.controllers; import com.culturaloffers.maps.dto.CommentDTO; import com.culturaloffers.maps.dto.GradeDTO; import com.culturaloffers.maps.dto.UserLoginDTO; import com.culturaloffers.maps.dto.UserTokenStateDTO; import com.culturaloffers.maps.helper.CommentMapper; import com.culturaloffers.maps.helper.GradeMapper; import com.culturaloffers.maps.model.Comment; import com.culturaloffers.maps.model.Grade; import com.culturaloffers.maps.services.CommentService; import com.culturaloffers.maps.services.CulturalOfferService; import com.culturaloffers.maps.services.GradeService; import com.culturaloffers.maps.services.GuestService; 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.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import javax.transaction.Transactional; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT) @TestPropertySource("classpath:test-grades.properties") public class CommentsControllerIntegrationTest { @Autowired private TestRestTemplate restTemplate; @Autowired private CommentService commentService; @Autowired private CulturalOfferService culturalOfferService; @Autowired private GuestService guestService; CommentMapper commentMapper = new CommentMapper(); private GradeMapper gradeMapper = new GradeMapper(); private String accessToken; private HttpHeaders httpHeaders; private void login(String username, String password) throws NullPointerException { ResponseEntity<UserTokenStateDTO> responseEntity = restTemplate.postForEntity("/auth/login", new UserLoginDTO(username,password), UserTokenStateDTO.class); accessToken = "Bearer " + responseEntity.getBody().getAccessToken(); } @Before public void setUp() { login("perica", "12345"); httpHeaders = new HttpHeaders(); httpHeaders.add("Authorization", accessToken); } @Test public void testGetGradesByCulturalOfferId() { HttpEntity<Object> httpEntity = new HttpEntity<Object>(httpHeaders); ResponseEntity<List<CommentDTO>> responseEntity = restTemplate.exchange("/c/culturaloffer/comments/" + 7, HttpMethod.GET, httpEntity, new ParameterizedTypeReference<List<CommentDTO>>() {}); List<CommentDTO> comments = responseEntity.getBody(); assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); assertEquals(1, comments.size()); } @Test public void testGetGradesByUserId() { HttpEntity<Object> httpEntity = new HttpEntity<Object>(httpHeaders); ResponseEntity<List<CommentDTO>> responseEntity = restTemplate.exchange("/c/user/comments/" + 1005, HttpMethod.GET, httpEntity, new ParameterizedTypeReference<List<CommentDTO>>() {}); List<CommentDTO> comments = responseEntity.getBody(); assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); assertEquals(1, comments.size()); } @Test public void testAddNewGrade() { CommentDTO commentDTO = new CommentDTO( 888, "Komentar", new Date(), new ArrayList<String>(), 1001, 14, "perica", "Cvetni Konaci" ); HttpEntity<CommentDTO> httpEntity = new HttpEntity<CommentDTO>(commentDTO, httpHeaders); int size = commentService.findByCulturalOfferId(14).size(); ResponseEntity<CommentDTO> responseEntity = restTemplate.exchange("/c", HttpMethod.POST, httpEntity, CommentDTO.class); CommentDTO comment = responseEntity.getBody(); assertNotNull(comment); assertEquals("Komentar", comment.getContent()); List<Comment> comments = commentService.findByCulturalOfferId(14); assertEquals(size + 1, comments.size()); commentService.deleteById(comment.getId()); } @Test public void testDeleteGrade() { HttpEntity<Object> httpEntity = new HttpEntity<Object>(httpHeaders); CommentDTO commentDTO = new CommentDTO( 888, "Komentar", new Date(), new ArrayList<String>(), 1001, 14, "perica", "Cvetni Konaci" ); Comment comment = commentService.addComment(commentMapper.toEntity(commentDTO), commentDTO.getCulturalOfferId(), commentDTO.getUserId()); int size = commentService.findByCulturalOfferId(14).size(); ResponseEntity<Map<String, Boolean>> responseEntity = restTemplate.exchange("/c/" + comment.getId(), HttpMethod.DELETE, httpEntity, new ParameterizedTypeReference<Map<String, Boolean>>(){}); assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); assertEquals(size - 1, commentService.findByCulturalOfferId(14).size()); } @Test @Transactional public void testUpdateGrade() { List<Comment> comments = commentService.findByUserId(1001); Comment toBeChanged = comments.get(0); toBeChanged.setContent("changed"); CommentDTO dto = commentMapper.toDto(toBeChanged); HttpEntity<CommentDTO> httpEntity = new HttpEntity<CommentDTO>(dto, httpHeaders); ResponseEntity<CommentDTO> responseEntity = restTemplate.exchange("/c/" + toBeChanged.getId(), HttpMethod.PUT, httpEntity, CommentDTO.class); CommentDTO commentChanged = responseEntity.getBody(); assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); assertNotNull(commentChanged); assertEquals(new Integer(1), commentChanged.getId()); assertEquals("changed", commentChanged.getContent()); commentChanged.setContent("Prelep pogled sa vrha"); responseEntity = restTemplate.exchange("/c/" + 1, HttpMethod.PUT, httpEntity, CommentDTO.class); } }
/* * Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.webui.common; import com.vaadin.data.validator.RangeValidator; public class LongRangeValidator extends RangeValidator<Long> { public LongRangeValidator(String errorMessage, Long minValue, Long maxValue) { super(errorMessage, Long.class, minValue, maxValue); } }
package com.xyt.model; import java.sql.Timestamp; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; /** * Topictbl entity. @author MyEclipse Persistence Tools */ @Entity @Table(name = "topictbl", catalog = "xiaoyuantong") public class Topictbl implements java.io.Serializable { // Fields private String topicid; private String topicname; private Timestamp createTime; private Set<Messagetbl> messagetbls = new HashSet<Messagetbl>(0); private Set<Usertopictbl> usertopictbls = new HashSet<Usertopictbl>(0); // Constructors /** default constructor */ public Topictbl() { } /** minimal constructor */ public Topictbl(String topicid) { this.topicid = topicid; } /** full constructor */ public Topictbl(String topicid, String topicname, Timestamp createTime, Set<Messagetbl> messagetbls, Set<Usertopictbl> usertopictbls) { this.topicid = topicid; this.topicname = topicname; this.createTime = createTime; this.messagetbls = messagetbls; this.usertopictbls = usertopictbls; } // Property accessors @Id @Column(name = "topicid", unique = true, nullable = false, length = 100) public String getTopicid() { return this.topicid; } public void setTopicid(String topicid) { this.topicid = topicid; } @Column(name = "topicname", length = 30) public String getTopicname() { return this.topicname; } public void setTopicname(String topicname) { this.topicname = topicname; } @Column(name = "createTime", length = 19) public Timestamp getCreateTime() { return this.createTime; } public void setCreateTime(Timestamp createTime) { this.createTime = createTime; } @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "topictbl") public Set<Messagetbl> getMessagetbls() { return this.messagetbls; } public void setMessagetbls(Set<Messagetbl> messagetbls) { this.messagetbls = messagetbls; } @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "topictbl") public Set<Usertopictbl> getUsertopictbls() { return this.usertopictbls; } public void setUsertopictbls(Set<Usertopictbl> usertopictbls) { this.usertopictbls = usertopictbls; } }
package com.legaoyi.management.ext.service.impl; import java.util.Date; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Service; import com.legaoyi.common.util.Constants; import com.legaoyi.common.util.DateUtils; import com.legaoyi.persistence.mongo.dao.MongoDao; import com.legaoyi.platform.ext.service.DefaultExtendService; import com.legaoyi.platform.model.Car; import com.legaoyi.platform.model.Device; /** * @author gaoshengbo */ @Service("carExtendService") public class CarExtendServiceImpl extends DefaultExtendService { private static final Logger logger = LoggerFactory.getLogger(CarExtendServiceImpl.class); @Autowired @Qualifier("cacheManager") private CacheManager cacheManager; @SuppressWarnings("rawtypes") @Autowired @Qualifier("mongoDao") private MongoDao<Map> mongoDao; @Override protected String getEntityName() { return Car.ENTITY_NAME; } @Override @Cacheable(value = Constants.CACHE_NAME_CAR_INFO_CACHE, key = "#id", unless = "#result == null") public Object get(Object id) throws Exception { return this.service.get(getEntityName(), id); } @Override public Object persist(Map<String, Object> entity) throws Exception { setEntity(entity); Car officersCar = (Car) super.persist(entity); evictCache(officersCar.getDeviceId()); return officersCar; } @Override @CacheEvict(value = Constants.CACHE_NAME_CAR_INFO_CACHE, key = "#id") public Object merge(Object id, Map<String, Object> entity) throws Exception { setEntity(entity); String enterpriseId = (String) entity.get("enterpriseId"); if (StringUtils.isNotEmpty(enterpriseId)) { Car oldCar = (Car) this.get(id); if (!oldCar.getEnterpriseId().equals(enterpriseId)) { // 更新绑定设备的企业 Device device = (Device) this.service.get(Device.ENTITY_NAME, oldCar.getDeviceId()); device.setEnterpriseId(enterpriseId); this.service.merge(device); String month = DateUtils.format(new Date(), "yyyyMM"); Query query = new Query(); query.addCriteria(Criteria.where("_id").is(month.concat("_").concat(device.getId()))); Update update = new Update(); update.set("enterpriseId", enterpriseId); String[] cols = new String[] {"online_time_day_report_", "gps_info_day_report_", "device_data_count_", "alarm_day_report_", "acc_time_day_report_"}; for (String col : cols) { mongoDao.getMongoTemplate().updateFirst(query, update, col.concat(month)); } mongoDao.getMongoTemplate().updateFirst(query, update, "car_report"); } } Car officersCar = (Car) super.merge(id, entity); evictCache(officersCar.getDeviceId()); return officersCar; } @Override public void delete(Object[] ids) throws Exception { for (Object id : ids) { Car officersCar = (Car) this.service.get(getEntityName(), id); if (officersCar == null) { continue; } this.service.delete(officersCar); this.cacheManager.getCache(Constants.CACHE_NAME_CAR_INFO_CACHE).evict(officersCar.getId()); evictCache(officersCar.getDeviceId()); } } private void evictCache(String deviceId) throws Exception { if (StringUtils.isNotBlank(deviceId)) { Device device = (Device) this.service.get(Device.ENTITY_NAME, deviceId); if (device != null) { this.cacheManager.getCache(Constants.CACHE_NAME_DEVICE_INFO_CACHE).evict(device.getId()); this.cacheManager.getCache(Constants.CACHE_NAME_DEVICE_INFO_CACHE).evict(device.getSimCode()); this.cacheManager.getCache(Constants.CACHE_NAME_CAR_INFO_CACHE).evict(device.getId()); } } } @SuppressWarnings("unchecked") private void setEntity(Map<String, Object> entity) { try { String plateNumber = (String) entity.get("plateNumber"); if (StringUtils.isNotBlank(plateNumber)) { String sql = "SELECT province_code as provinceCode,city_code as cityCode FROM system_plate_number_rule WHERE prefix = ? limit 1"; List<?> list = this.service.findBySql(sql, plateNumber.substring(0, 2)); if (list != null && !list.isEmpty()) { entity.putAll((Map<String, Object>) list.get(0)); } } } catch (Exception e) { logger.error("", e); } } }
import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import Propiedades.Jugador; import Propiedades.ventanaPrincipal; import java.awt.Color; import javax.swing.border.CompoundBorder; import javax.swing.border.LineBorder; public class Principal { //Entrada a Programa: public static void main(String[] args) { ventanaPrincipal jugador1 = new ventanaPrincipal(); jugador1.setVisible(true); } public Principal(){ } }
package projecteulerproblems; import java.math.BigInteger; /** * Project Euler - Problem 16 and 20.<br></br> * Calculates the sum of the digits in <br> * (a) two to the power of <i>n</i> <br> * (b) N factorial * * @author Phil * */ public class DigitSum { /** * Sums the digits in two to the power of <i>n</i>. * * @param power the power of two required * @return the sum of the digits in 2^N */ public static int sumOfDigitsInTwoToPowerOf(int power) { return sumDigitsInNumber(calculateTwoToPowerOf(power)); } /** * Sums the digits in a factorial number. * * @param factorial the factorial number required (e.g. !4) * @return */ public static int sumOfFactorials(int factorial) { return sumDigitsInNumber(calculateFactorialIteratively(factorial)); } /** * Helper Method. Calculates 2^N. * <br>Only valid for N >= 0. * * @param power * @return 2^N */ private static BigInteger calculateTwoToPowerOf(int power) { if (power <= 0) { return BigInteger.ZERO; } BigInteger total = BigInteger.ONE; for (int count = 1; count <= power; count++) { total = total.multiply(BigInteger.valueOf(2)); } return total; } /** * Calculates the factorial recursively. * Deprecated as it doesn't scale well. * * @param topFactorial * @return */ @Deprecated private static BigInteger calculateFactorial(int topFactorial) { if (topFactorial == 1) { return BigInteger.ONE; } else { return BigInteger.valueOf(topFactorial).multiply( calculateFactorial(topFactorial - 1)); } } /** * Helper method. Calculates !N iteratively as the recursive method didn't * scale well. * * @param topFactorial the N in !N * @return the answer to !N */ private static BigInteger calculateFactorialIteratively(int topFactorial) { BigInteger total = BigInteger.ONE; for (int count = 1; count <= topFactorial; count++) { total = total.multiply(BigInteger.valueOf(count)); } return total; } /** * Helper method sums the digits in a number. * * @param number * @return the sum of the individual digits in a number. */ private static int sumDigitsInNumber(BigInteger number) { String numberString = number.toString(); int total = 0; Integer currentNumber; for (int count = 0; count < numberString.length(); count++) { String num = numberString.charAt(count) + ""; currentNumber = Integer.parseInt(num); total += currentNumber; } return total; } }
import static org.junit.Assert.*; import org.junit.Test; public class LengthOfStringTest { @Test public void testLength() { StringThings sT = new StringThings(); assertEquals(sT.getLength("William"), 7); } @Test public void testAlphabetical() { StringThings sT = new StringThings(); assertTrue(sT.isAfter("banana","apple")); assertFalse(sT.isAfter("apple","apple")); assertFalse(sT.isAfter("apple","banana")); } @Test public void testCapitalize(){ StringThings sT = new StringThings(); assertEquals("William Apple", sT.capitalize("william", "apple")); } }
package test; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import pojo.Book; import utils.DbUtils; public class Program { public static void main(String[] args) { try( Connection connection = DbUtils.getConnection(); PreparedStatement statement = connection.prepareStatement("update BookTable set book_name=?, author_name=? where book_id=?")) { String bookName = "Design of Unix OS"; statement.setString(1, bookName); String authorName = "Moris J Batch"; statement.setString(2, authorName); int bookId = 1012; statement.setInt(3, bookId); int rowsAffected = statement.executeUpdate( ); System.out.println(rowsAffected+" row(s) affected"); } catch (SQLException e) { e.printStackTrace(); } } }
package com.soldevelo.vmi.udp; import com.soldevelo.vmi.communication.params.TestRequestParams; import com.soldevelo.vmi.udp.communication.UdpReverseResults; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; @Service public class UdpReverseRequests { private Map<String, TestRequestParams> requests = new HashMap<String, TestRequestParams>(); private Map<String, UdpReverseResults> results = new HashMap<String, UdpReverseResults>(); public Map<String, TestRequestParams> getUdpReverseRequests() { return requests; } public void addRequest(TestRequestParams request) { requests.put(request.getAddress(), request); } public void dropRequest(TestRequestParams request) { requests.remove(request.getAddress()); } public void clear() { requests.clear(); } public boolean authentication(String address) { return requests.containsKey(address); } public TestRequestParams findUdpRequest(String address) { return requests.get(address); } public UdpReverseResults getResults(String address) { return results.get(address); } public void addResults(String address, UdpReverseResults udpReverseResults) { results.put(address, udpReverseResults); } public UdpReverseResults popResults(String address) { return results.remove(address); } }
package com.esum.comp.dbm.util.sql; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.esum.comp.dbm.dbxml.DBRecordParser; import com.esum.comp.dbm.template.Template; /** * Copyright(c) eSum Technologies., inc. All rights reserved. */ public class ScriptUtil { private static Logger log = LoggerFactory.getLogger(ScriptUtil.class); public synchronized static final String getScript(DBRecordParser parser, Template template, String srcQuery, int idx) throws Exception { StringBuffer targetBuffer = new StringBuffer(); int pos = 0; while (true) { int index = srcQuery.indexOf("$", pos); if (index == -1){ if (targetBuffer.length() == 0) targetBuffer.append(srcQuery); else { if (pos != srcQuery.length()) targetBuffer.append(srcQuery.substring(pos)); } break; } targetBuffer.append(srcQuery.substring(pos, index)); int lastPos = srcQuery.indexOf(")", index+1); if (lastPos == -1) throw new Exception("Invalid Script Syntax : End Tag(')') not found."); String scriptStr = srcQuery.substring(index+2, lastPos); String result = ""; log.debug("Parsing SQL!! Source Script String : " + scriptStr); if(scriptStr.startsWith(ScriptConstants.CURRENT_DATE)) { /** * SQL자체에 대한 Parsing을 통해 다양한 스크립트를 제공한다. */ result = new DateParser().parse(scriptStr); } else { /** * 이미 가져온 Record에 대한 Parsing을 제공한다. */ result = new ScriptParser(scriptStr, idx).parse(template, parser.getCashedRecord()); } log.debug("Parsed SQL!! Result Script String : " + result); targetBuffer.append(result); pos = lastPos+1; } if(log.isDebugEnabled()) log.debug("Completed the rebuilding SQL. SQL : " + targetBuffer.toString()); return targetBuffer.toString(); } }
package app.com.thetechnocafe.eventos.DataSync; import android.content.Context; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.JsonRequest; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Date; import java.util.List; import app.com.thetechnocafe.eventos.Database.EventsDatabaseHelper; import app.com.thetechnocafe.eventos.Models.EventsModel; import app.com.thetechnocafe.eventos.Utils.SharedPreferencesUtils; import static app.com.thetechnocafe.eventos.DataSync.StringUtils.JSON_DATA; public abstract class RequestUtils { private static final String SERVER_ADDRESS = "http://192.168.0.7:55555"; private static final String LINK_EVENT_REQUEST = SERVER_ADDRESS + "/api/events"; private static final String SIGN_UP_REQUEST_ADDRESS = SERVER_ADDRESS + "/api/signup"; private static final String SIGN_IN_REQUEST_ADDRESS = SERVER_ADDRESS + "/api/login"; private static final String UPDATE_ACCOUNT_REQUEST_ADDRESS = SERVER_ADDRESS + "/api/user/update"; private static final String GET_SUBMITTED_EVENTS_REQUEST_ADDRESS = SERVER_ADDRESS + "/api/submitted-events"; private static final String SUBMIT_COMMENT_REQUEST_ADDRESS = SERVER_ADDRESS + "/api/events/comment"; private static final String RATE_EVENT_REQUEST_POST = SERVER_ADDRESS + "/api/events/rating"; private static final String INCREASE_DECREASE_PARTICIPATION_EVENT = SERVER_ADDRESS + "/api/events/interested/"; //JSON keys for submitted events private static final String JSON_EVENT_TITLE = "title"; private static final String JSON_EVENT_DESCRIPTION = "description"; private static final String JSON_EVENT_DATE = "date"; private static final String JSON_EVENT_VENUE = "venue"; private static final String JSON_EVENT_IMAGE = "image"; private static final String JSON_EVENT_AVATAR_ID = "avatar_id"; private static final String JSON_EVENT_ID = "_id"; private static final String JSON_EVENT_REQUIREMENTS = "requirements"; private static final String JSON_EVENT_VERIFIED = "verified"; private static final String JSON_EVENT_SUBMIITED_BY = "submitted_by"; private static final String JSON_EVENT_PEOPLE_INTERESTED = "people_interested"; private static final String JSON_OUTSIDE_EVENT = "outside_event"; public EventsDatabaseHelper mEventsDatabaseHelper; public abstract void isRequestSuccessful(boolean isSuccessful, String message); /** * Submit forum to network * requires */ public void submitForumToServer(Context context, final JSONObject jsonObject) { //Create new JSON Object Request JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, LINK_EVENT_REQUEST, jsonObject, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { //Check if response if not null if (response != null) { //Check for success try { if (response.getString(StringUtils.JSON_STATUS).equals(StringUtils.JSON_SUCCESS)) { isRequestSuccessful(true, null); } else { isRequestSuccessful(false, null); } } catch (JSONException e) { isRequestSuccessful(false, null); } } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //Notify error isRequestSuccessful(false, null); } }) { @Override public byte[] getBody() { return jsonObject.toString().getBytes(); } }; //Add request to queue VolleyQueue.getInstance(context).getRequestQueue().add(request); } /** * Sign up Request */ public void signUp(Context context, final JSONObject jsonObject) { //Create new json object request JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, SIGN_UP_REQUEST_ADDRESS, jsonObject, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { if (response.getString(StringUtils.JSON_STATUS).equals(StringUtils.JSON_SUCCESS)) { isRequestSuccessful(true, response.getString(JSON_DATA)); } else { isRequestSuccessful(false, response.getString(JSON_DATA)); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { isRequestSuccessful(false, error.toString()); } }); //Add request to queue VolleyQueue.getInstance(context).getRequestQueue().add(request); } /** * Sign in request */ public void signIn(final Context context, JSONObject jsonObject) { //Create new json object request JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, SIGN_IN_REQUEST_ADDRESS, jsonObject, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { if (response.getString(StringUtils.JSON_STATUS).equals(StringUtils.JSON_SUCCESS)) { isRequestSuccessful(true, response.getString(JSON_DATA)); JSONObject object = response.getJSONArray(JSON_DATA).getJSONObject(0); SharedPreferencesUtils.setFullName(context, object.getString(StringUtils.JSON_FULL_NAME)); SharedPreferencesUtils.setPassword(context, object.getString(StringUtils.JSON_PASSWORD)); SharedPreferencesUtils.setUsername(context, object.getString(StringUtils.JSON_EMAIL)); SharedPreferencesUtils.setPhoneNumber(context, object.getString(StringUtils.JSON_PHONE)); } else { isRequestSuccessful(false, response.getString(JSON_DATA)); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { isRequestSuccessful(false, error.toString()); } }); //Add request to queue VolleyQueue.getInstance(context).getRequestQueue().add(request); } /** * Update user account details */ public void updateAccountDetails(Context context, JSONObject object) { //Create new json request JsonRequest request = new JsonObjectRequest(Request.Method.PUT, UPDATE_ACCOUNT_REQUEST_ADDRESS, object, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { if (response.getString(StringUtils.JSON_STATUS).equals(StringUtils.JSON_SUCCESS)) { isRequestSuccessful(true, response.getString(JSON_DATA)); } else { isRequestSuccessful(false, response.getString(JSON_DATA)); } } catch (JSONException e) { e.printStackTrace(); isRequestSuccessful(false, null); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); //Add to volley queue VolleyQueue.getInstance(context).getRequestQueue().add(request); } public void increaseDecreaseParticipationEvent(final Context context, String id, int num) { JSONObject object = new JSONObject(); try { object.put(StringUtils.JSON_EVENT_INCREASE_DECREASE, num); } catch (JSONException e) { e.printStackTrace(); } JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, INCREASE_DECREASE_PARTICIPATION_EVENT + id, object, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { if (response.getString(StringUtils.JSON_STATUS).equals(StringUtils.JSON_SUCCESS)) { isRequestSuccessful(true, response.getString(JSON_DATA)); } } catch (JSONException e) { e.printStackTrace(); isRequestSuccessful(false, null); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { isRequestSuccessful(false, null); } }); VolleyQueue.getInstance(context).getRequestQueue().add(request); } /** * Get all the events submitted by the specified user */ public void getSubmittedEvents(final Context context, String email) { //Create a JSON Object JSONObject object = new JSONObject(); try { object.put(StringUtils.SUBMITTED_BY, email); } catch (JSONException e) { e.printStackTrace(); } final JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, GET_SUBMITTED_EVENTS_REQUEST_ADDRESS, object, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { if (response.getString(StringUtils.JSON_STATUS).equals(StringUtils.JSON_SUCCESS)) { isRequestSuccessful(true, response.getString(JSON_DATA)); mEventsDatabaseHelper = new EventsDatabaseHelper(context); //Delete all the events that have been delete from server List<String> idList = new ArrayList<>(); //Retrieve data from JSON object JSONArray eventsJSONArray = response.getJSONArray(JSON_DATA); //Loop over the array and store data in SQLite database for (int i = 0; i < eventsJSONArray.length(); i++) { //Get json object at position i JSONObject eventJSONobject = eventsJSONArray.getJSONObject(i); //Create new event object EventsModel event = new EventsModel(); //Insert the details into event object if (insertSubmittedEventDetails(event, eventJSONobject)) { //Add id to list idList.add(event.getId()); } if (!mEventsDatabaseHelper.doesSubmittedEventAlreadyExists(event.getId())) { mEventsDatabaseHelper.insertNewSubmittedEvent(event); } else { mEventsDatabaseHelper.deleteFromSubmittedEvents(event.getId()); mEventsDatabaseHelper.insertNewSubmittedEvent(event); } mEventsDatabaseHelper.removeSpecificSubmittedEventsFromDB(idList); mEventsDatabaseHelper.close(); } } else { isRequestSuccessful(false, response.getString(JSON_DATA)); } } catch (JSONException e) { e.printStackTrace(); isRequestSuccessful(false, null); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { isRequestSuccessful(false, null); } }); //Add to volley queue VolleyQueue.getInstance(context).getRequestQueue().add(request); } private boolean insertSubmittedEventDetails(EventsModel event, JSONObject object) { try { event.setTitle(object.getString(JSON_EVENT_TITLE)); event.setDescription(object.getString(JSON_EVENT_DESCRIPTION)); event.setImage(object.getString(JSON_EVENT_IMAGE)); event.setVenue(object.getString(JSON_EVENT_VENUE)); event.setId(object.getString(JSON_EVENT_ID)); event.setAvatarId(object.getString(JSON_EVENT_AVATAR_ID)); event.setDate(new Date(object.getLong(StringUtils.JSON_DATE))); event.setRequirements(object.getString(JSON_EVENT_REQUIREMENTS)); event.setSubmittedBy(object.getString(JSON_EVENT_SUBMIITED_BY)); event.setVerified(object.getBoolean(JSON_EVENT_VERIFIED)); event.setNumOfPeopleInterested(object.getInt(JSON_EVENT_PEOPLE_INTERESTED)); event.setOutsideEvent(object.getBoolean(JSON_OUTSIDE_EVENT)); } catch (JSONException e) { e.printStackTrace(); return false; } return true; } /** * Submite a comment for a particular event */ public void submitCommentForEvent(Context context, JSONObject object) { JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, SUBMIT_COMMENT_REQUEST_ADDRESS, object, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { if (response.getString(StringUtils.JSON_STATUS).equals(StringUtils.JSON_SUCCESS)) { isRequestSuccessful(true, response.getString(JSON_DATA)); } else { isRequestSuccessful(false, response.getString(JSON_DATA)); } } catch (JSONException e) { e.printStackTrace(); isRequestSuccessful(false, null); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { isRequestSuccessful(false, null); } }); //Add to volley queue VolleyQueue.getInstance(context).getRequestQueue().add(request); } //Submit Rating for a particular Event public void setRateEventRequestPost(Context context, JSONObject object) { JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, RATE_EVENT_REQUEST_POST, object, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { if (response.getString(StringUtils.JSON_STATUS).equals(StringUtils.JSON_SUCCESS)) { isRequestSuccessful(true, response.getString(JSON_DATA)); } else { isRequestSuccessful(false, response.getString(JSON_DATA)); } } catch (JSONException e) { e.printStackTrace(); isRequestSuccessful(false, null); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { isRequestSuccessful(false, null); } }); //Add to volley queue VolleyQueue.getInstance(context).getRequestQueue().add(request); } }
package com.lounge.esports.webapps.website.security.token; import com.lounge.esports.webapps.website.security.authentication.UserAuthentication; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.User; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; /** * When a user successfully logs into the web application, the first public method of this class will be called to * create a token for that user. * * @author afernandez */ @Service public class TokenAuthenticationService { @Autowired private TokenHandler tokenHandler; public String generateToken(User user) { return tokenHandler.createTokenForUser(user); } public Authentication getAuthentication(HttpServletRequest request) { final String token = request.getHeader(HttpHeaders.AUTHORIZATION); if (StringUtils.isNotEmpty(token) && token.startsWith("Bearer")) { final User user = tokenHandler.parseUserFromToken(token.split(" ")[1]); if (user != null) { return new UserAuthentication(user); } } return null; } }
package com.eegeo.mapapi.services.routing; import com.eegeo.mapapi.geometry.LatLng; /** * Directions information for a RouteStep of a Route. */ public class RouteDirections { /** * The type of motion to make at this step. For example, "turn". */ public final String type; /** * A modification to the type. For example, "sharp right". */ public final String modifier; /** * The LatLng this direction applies at. */ public final LatLng location; /** * The bearing in degrees relative to north before taking this direction. */ public final double bearingBefore; /** * The bearing in degrees relative to north after taking this direction. */ public final double bearingAfter; RouteDirections( final String type, final String modifier, final LatLng location, final double bearingBefore, final double bearingAfter) { this.type = type; this.modifier = modifier; this.location = location; this.bearingBefore = bearingBefore; this.bearingAfter = bearingAfter; } }
/*46. Implement a java program to find the area of a) Circle b) Rectangle c) Square d) trapezoid e)rhombus f) triangle*/ class Area{ public static void main(String args[]){ double circle,radius = 10; circle = radius*radius*Math.PI; System.out.println("Area of Circle is "+ circle); double triangle,triheight = 5,tribase = 2; triangle = 0.5 * triheight * tribase; System.out.println("Area of triangle is "+ triangle); double square, side = 5; square = side*side; System.out.println("Area of square is "+ square); double rectangle, length =3,breadth =4; rectangle = length*breadth; System.out.println("Area of rectangle is "+ rectangle); double rhombus, rhombase =4, rhomheight =7; rhombus = rhombase * rhomheight; System.out.println("Area of rhombus is "+ rhombus); double trapezoid, base1 =2, base2 = 3, trapheight = 6; trapezoid = ((base1 + base2)/2)*trapheight; System.out.println("Area of trapezoid is "+ trapezoid); } }
package com.amazon.pages; import com.pnt.base.TestBase; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.FindBy; import org.testng.Assert; public class AmazonHomePage extends TestBase { //**** For Sign IN @FindBy(id = "nav-link-accountList-nav-line-1") private WebElement searchLogin; @FindBy(xpath = "//input[@id='ap_email']") private WebElement searchBox; @FindBy(xpath = "//input[@id='continue']") private WebElement signInButton; @FindBy(xpath = "//input[@id='ap_password']") private WebElement inputPassword; @FindBy(xpath = "//input[@id='signInSubmit']") private WebElement signInClick; public void clickLogin() { searchLogin.click(); } public void typeEmail(String email) { searchBox.sendKeys(email); } public void clickOnSignInButton() { signInButton.click(); } public void enterPassword(String password){ inputPassword.sendKeys(password); } public void clickSignIn(){ signInClick.click(); } // Sign Out @FindBy(xpath = "//*[@id='nav-link-accountList']") private WebElement searchSignOut; @FindBy(xpath = "//*[@id='nav-item-signout']") private WebElement signOutClick; public void clkSignOut(){ WebElement item = searchSignOut; Actions actions= new Actions(driver); actions.moveToElement(item).build().perform(); } public void clickSignOut(){ signOutClick.click(); } // Search Item and Verify @FindBy(id = "twotabsearchtextbox") private WebElement searchTextBox; @FindBy(id = "nav-search-submit-button") private WebElement searchButton; @FindBy(xpath ="//span[@class='a-color-state a-text-bold']" ) private WebElement actuText; public void typeOnSearchBar(String text) { searchTextBox.sendKeys(text); } public void clickOnSearchButton() { searchButton.click(); } public void findText(String expect){ Assert.assertTrue(actuText.getText().contains(expect), "Hi, Tex Not Match"); } // Browse products & use shooping cart @FindBy(xpath = "//input[@id='twotabsearchtextbox']") private WebElement checkBox; @FindBy(xpath = "//input[@id='nav-search-submit-button']") private WebElement checkButton; @FindBy(xpath = "//*[@id='search']/div[1]/div/div[1]/div/span[3]/div[2]/div[5]/div/span/div/div/div[2]/div[2]/div/div/div[1]/h2/a/span") private WebElement product; @FindBy(xpath = "//input[@id='add-to-cart-button']") private WebElement addToCart; @FindBy(xpath = "//input[@aria-labelledby='attachSiNoCoverage-announce']") private WebElement noThanks; @FindBy(xpath = "//*[@id='attach-sidesheet-checkout-button']/span/input") private WebElement checkOut; public void checkBox(String item){ checkBox.sendKeys(item); } public void checkButton(){ checkButton.click(); } public void product(){ product.click(); } public void addToCart(){ addToCart.click(); } public void noThanks(){ noThanks.click(); } public void checkOut(){ checkOut.click(); } }
package comp303.fivehundred.model; import static org.junit.Assert.*; import static comp303.fivehundred.util.AllCards.*; import org.junit.Before; import org.junit.Test; import comp303.fivehundred.util.AllCards; import comp303.fivehundred.util.Card.Suit; /** * @author Ioannis Fytilis 260482744 * This is the test class for Bid */ public class TestTrick { Bid passBid; Bid lowBid; Bid highBid; Bid mediumBid; @Before public void init(){ lowBid = new Bid(0);// six spades highBid = new Bid(24); // ten no trump mediumBid = new Bid(7);// seven diamonds } @Test public void basicInfo(){ Trick lowTrick = new Trick(lowBid); assertTrue(lowTrick.getTrumpSuit()==Suit.SPADES); assertNull(lowTrick.getSuitLed()); lowTrick.add(a4C); assertTrue(lowTrick.getTrumpSuit()==Suit.SPADES); assertTrue(lowTrick.getSuitLed()==Suit.CLUBS); assertFalse(lowTrick.jokerLed()); Trick highTrick = new Trick(highBid); assertNull(highTrick.getTrumpSuit()); assertNull(highTrick.getSuitLed()); highTrick.add(aLJo); assertNull(highTrick.getTrumpSuit()); assertNull(highTrick.getSuitLed()); assertTrue(highTrick.jokerLed()); Trick medTrick = new Trick(mediumBid); assertTrue(medTrick.getTrumpSuit()==Suit.DIAMONDS); assertNull(medTrick.getSuitLed()); medTrick.add(a8C); assertTrue(medTrick.getTrumpSuit().equals(Suit.DIAMONDS)); assertTrue(medTrick.getSuitLed().equals(Suit.CLUBS)); assertFalse(medTrick.jokerLed()); } @Test public void testCardLed2(){ Trick aTrick1 = new Trick(lowBid); aTrick1.add(a4C); aTrick1.add(aAD); assertEquals(aTrick1.cardLed(),a4C); Trick aTrick2 = new Trick(lowBid); aTrick2.add(aLJo); aTrick2.add(aHJo); assertEquals(aTrick2.cardLed(),aLJo); } @Test public void testHighest2(){ Trick aTrick1 = new Trick(lowBid); aTrick1.add(aAD); aTrick1.add(a4C); assertEquals(aTrick1.highest(),aAD); assertEquals(aTrick1.winnerIndex(), 0); aTrick1.add(aLJo); assertEquals(aTrick1.highest(),aLJo); assertEquals(aTrick1.winnerIndex(), 2); Trick aTrick2 = new Trick(highBid); aTrick2.add(a5D); aTrick2.add(aKC); aTrick2.add(aJS); assertEquals(aTrick2.highest(),a5D); assertEquals(aTrick2.winnerIndex(), 0); aTrick2.add(aHJo); assertEquals(aTrick2.highest(),aHJo); aTrick1 = new Trick(new Bid(0)); aTrick1.add(aJH); aTrick1.add(aJC); aTrick1.add(aJD); aTrick1.add(aJS); assertEquals(aTrick1.highest(), aJS); assertEquals(aTrick1.winnerIndex(), 3); aTrick1 = new Trick(new Bid(3)); aTrick1.add(aHJo); aTrick1.add(a4H); aTrick1.add(aLJo); aTrick1.add(aJH); assertEquals(aTrick1.highest(), aHJo); assertEquals(aTrick1.winnerIndex(), 0); aTrick1 = new Trick(new Bid(24)); aTrick1.add(aAH); aTrick1.add(aAD); aTrick1.add(aAC); aTrick1.add(aAS); assertEquals(aTrick1.highest(), aAH); assertEquals(aTrick1.winnerIndex(), 0); assertEquals(aTrick1.winnerIndex(), 0); aTrick1 = new Trick(new Bid(24)); aTrick1.add(aAC); aTrick1.add(aAD); aTrick1.add(aAH); aTrick1.add(aAS); assertEquals(aTrick1.highest(), aAC); assertEquals(aTrick1.winnerIndex(), 0); Trick a = new Trick (lowBid);// 6 Spades a.add(a9C); a.add(a9D); a.add(aTH); a.add(aTD); assertEquals(a.highest(),a9C); assertEquals(aTrick1.winnerIndex(), 0); Trick b = new Trick(highBid); assertFalse(b.jokerLed()); b.add(aHJo); b.add(aAH); b.add(aQD); b.add(aLJo); assertEquals(b.highest(),aHJo); assertEquals(b.winnerIndex(), 0); Trick c = new Trick(new Bid(2)); // diamonds c.add(aJH); c.add(a4D); c.add(a8D); c.add(aAD); assertEquals(c.highest(),aJH); assertEquals(c.winnerIndex(), 0); b = new Trick(highBid); b.add(aHJo); b.add(aAH); b.add(aQD); b.add(aLJo); assertEquals(b.highest(),aHJo); assertTrue(b.jokerLed()); assertEquals(b.winnerIndex(), 0); b = new Trick(new Bid(0)); b.add(aQS); b.add(aJC); b.add(aJS); b.add(aAH); assertEquals(b.highest(),aJS); assertFalse(b.jokerLed()); assertEquals(b.winnerIndex(), 2); b = new Trick(new Bid(24)); b.add(a6S); b.add(a8D); b.add(a7S); b.add(aJC); assertEquals(b.winnerIndex(), 2); assertEquals(b.highest(),a7S); b = new Trick(new Bid(24)); b.add(a7C); b.add(aHJo); b.add(aLJo); b.add(aAC); assertEquals(b.highest(),aHJo); assertEquals(b.winnerIndex(), 1); b = new Trick(new Bid(0)); b.add(a8S); b.add(aJC); b.add(aAS); b.add(aJS); assertEquals(b.highest(),aJS); assertEquals(b.winnerIndex(), 3); b = new Trick(new Bid(0)); b.add(aAS); b.add(aJC); b.add(aAS); b.add(a6H); assertEquals(b.highest(),aJC); assertEquals(b.winnerIndex(), 1); b = new Trick(new Bid(0)); b.add(aAS); b.add(aJS); b.add(aAS); b.add(a6H); assertEquals(b.highest(),aJS); assertEquals(b.winnerIndex(), 1); b = new Trick(new Bid(0)); b.add(a4S); b.add(aJC); b.add(aAH); b.add(a6H); assertEquals(b.highest(),aJC); assertEquals(b.winnerIndex(),1); b = new Trick(new Bid(2)); b.add(a4D); b.add(aJH); b.add(aAH); b.add(a6H); assertEquals(b.highest(),aJH); assertEquals(b.winnerIndex(), 1); b = new Trick(new Bid(0)); b.add(a7C); b.add(a6S); b.add(aAC); b.add(a8S); assertEquals(b.highest(),a8S); assertEquals(b.winnerIndex(), 3); b = new Trick(new Bid(0)); b.add(a8D); b.add(aJC); b.add(aAD); b.add(a8S); assertEquals(b.highest(),aJC); assertEquals(b.winnerIndex(), 1); } Trick emptyTrick; Trick nonEmptyTrick; Trick nonTrumpTrick; Trick jokerLHTrick; Trick lowJokerFirstTrick; Trick highJokerFirstTrick; Trick firstjackTrick; @Before public void setUp() throws Exception { Bid contract = new Bid(8, Suit.CLUBS); emptyTrick = new Trick(contract); nonEmptyTrick = new Trick(contract); nonEmptyTrick.add(AllCards.aQH); nonEmptyTrick.add(AllCards.a7C); nonTrumpTrick = new Trick(new Bid(9, null)); nonTrumpTrick.add(AllCards.a7D); nonTrumpTrick.add(AllCards.aKD); nonTrumpTrick.add(AllCards.a6S); nonTrumpTrick.add(AllCards.aJH); jokerLHTrick = new Trick(new Bid(9, Suit.DIAMONDS)); jokerLHTrick.add(AllCards.aLJo); jokerLHTrick.add(AllCards.aKD); jokerLHTrick.add(AllCards.a7H); jokerLHTrick.add(AllCards.aHJo); lowJokerFirstTrick = new Trick(new Bid(9, Suit.HEARTS)); lowJokerFirstTrick.add(AllCards.aLJo); lowJokerFirstTrick.add(AllCards.aKD); lowJokerFirstTrick.add(AllCards.aQH); lowJokerFirstTrick.add(AllCards.a8H); highJokerFirstTrick = new Trick(new Bid(9, Suit.HEARTS)); highJokerFirstTrick.add(AllCards.aHJo); highJokerFirstTrick.add(AllCards.aKD); highJokerFirstTrick.add(AllCards.aQH); highJokerFirstTrick.add(AllCards.aLJo); firstjackTrick = new Trick(new Bid(9, Suit.SPADES)); firstjackTrick.add(AllCards.aJC); } @Test public void testGetTrumpSuit() { assertTrue(Suit.CLUBS.equals(emptyTrick.getTrumpSuit())); assertTrue(Suit.CLUBS.equals(nonEmptyTrick.getTrumpSuit())); assertTrue(nonTrumpTrick.getTrumpSuit() == null); } @Test public void testGetSuitLed() { assertTrue(nonEmptyTrick.getSuitLed().equals(Suit.HEARTS)); assertTrue(nonTrumpTrick.getSuitLed().equals(Suit.DIAMONDS)); assertTrue(lowJokerFirstTrick.getSuitLed().equals(Suit.HEARTS)); assertTrue(highJokerFirstTrick.getSuitLed().equals(Suit.HEARTS)); assertTrue(firstjackTrick.getSuitLed().equals(Suit.SPADES)); } @Test public void testJokerLed() { assertTrue(!nonEmptyTrick.jokerLed()); assertTrue(!nonTrumpTrick.jokerLed()); assertTrue(lowJokerFirstTrick.jokerLed()); assertTrue(highJokerFirstTrick.jokerLed()); } @Test public void testCardLed() { assertTrue(nonEmptyTrick.cardLed().equals(AllCards.aQH)); assertTrue(nonTrumpTrick.cardLed().equals(AllCards.a7D)); assertTrue(lowJokerFirstTrick.cardLed().equals(AllCards.aLJo)); assertTrue(highJokerFirstTrick.cardLed().equals(AllCards.aHJo)); } @Test public void testHighest() { assertTrue(nonEmptyTrick.highest().equals(AllCards.a7C)); assertTrue(nonTrumpTrick.highest().equals(AllCards.aKD)); assertTrue(jokerLHTrick.highest().equals(AllCards.aHJo)); assertTrue(lowJokerFirstTrick.highest().equals(AllCards.aLJo)); assertTrue(highJokerFirstTrick.highest().equals(AllCards.aHJo)); } @Test public void testWinnerIndex() { assertTrue(nonTrumpTrick.winnerIndex() == 1); assertTrue(jokerLHTrick.winnerIndex() == 3); assertTrue(lowJokerFirstTrick.winnerIndex() == 0); assertTrue(highJokerFirstTrick.winnerIndex() == 0); } }
/* package com.soft1851.spring.web.entity; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.sql.Timestamp; */ /** * @author CRQ *//* @Data @Builder @AllArgsConstructor @NoArgsConstructor public class Post { private Integer postId; private Integer forumId; private String title; private String content; private byte[] thumbnail; private Timestamp postTime; } */
package com.unimelb.comp90015.Server.Dictionary; /** * Xulin Yang, 904904 * * @create 2020-4-12 22:11:36 * description: the factory to create dictionary instance **/ public class DictionaryFactory { /** * the singleton instance */ private static DictionaryFactory ourInstance = new DictionaryFactory(); /** * @return the singleton factory instance */ public static DictionaryFactory getInstance() { return ourInstance; } private DictionaryFactory() { } /** * @param dictionaryFilePath dictionary file's path * @return the created SimpleDictionary instance */ public SimpleDictionary createSimpleDictionary(String dictionaryFilePath) { return new SimpleDictionary(dictionaryFilePath); } }