text
stringlengths
10
2.72M
import java.util.Random; public class Cidadao extends Personagem { private Personagem alvo; private int lin, col; public Cidadao(int linInicial, int colInicial) { super(10, "Cidadao", linInicial, colInicial); } private Personagem defineAlvo(){ //System.out.println("Procurando zumbi"); for(int l=0;l<Jogo.NLIN;l++){ for(int c=0;c<Jogo.NCOL;c++){ Personagem p = Jogo.getInstance().getCelula(l, c).getPersonagem(); if (p != null && p instanceof Zumbi) { if ( (Math.abs(this.getCelula().getLinha() - l) <= 3) && (Math.abs(this.getCelula().getColuna() - c) <= 3) ) { alvo = p; System.out.println("Zumbi encontrado: l= "+alvo.getCelula().getLinha() +", c= "+alvo.getCelula().getColuna()); return p; } } } } return null; } private void testaLimites() { if (lin < 0) lin = Jogo.NLIN-1; if (lin >= Jogo.NLIN) lin = 0; if (col < 0) col = Jogo.NCOL-1; if (col >= Jogo.NCOL) col = 0; } private void testaCelulaOcupada(int oldLin, int oldCol) { if (Jogo.getInstance().getCelula(lin, col).getPersonagem() != null) { int dirLin = Jogo.getInstance().aleatorio(3)-1; int dirCol = Jogo.getInstance().aleatorio(3)-1; lin = oldLin + dirLin; col = oldCol + dirCol; testaLimites(); } } @Override public void atualizaPosicao() { if (this.infectado()) return; // Caso esteja infectado, não se move if (alvo == null) { alvo = defineAlvo(); //return; } // Pega posicao atual do Cidadao int oldLin = this.getCelula().getLinha(); int oldCol = this.getCelula().getColuna(); // Pega a posicao do Zumbi if (alvo != null) { int linAlvo = alvo.getCelula().getLinha(); int colAlvo = alvo.getCelula().getColuna(); // Calcula o deslocamento lin = oldLin; col = oldCol; if (lin < linAlvo) lin--; if (lin > linAlvo) lin++; if (col < colAlvo) col--; if (col > colAlvo) col++; } else { // Se o alvo é nulo, movimenta-se aleatoriamente int dirLin = Jogo.getInstance().aleatorio(3)-1; int dirCol = Jogo.getInstance().aleatorio(3)-1; lin = oldLin + dirLin; col = oldCol + dirCol; } // Verifica se não saiu dos limites do tabuleiro testaLimites(); // Se a celula esta ocupada, se move aleatoriamente testaCelulaOcupada(oldLin, oldCol); // Limpa celula atual Jogo.getInstance().getCelula(oldLin, oldCol).setPersonagem(null); // Coloca personagem na nova posição Jogo.getInstance().getCelula(lin, col).setPersonagem(this); } @Override public void infecta(){ if (this.infectado()){ return; } super.infecta(); this.setImage("Cidadao_Infectado"); this.getCelula().setImageFromPersonagem(); } @Override public void cura(){ super.cura(); this.setImage("Cidadao"); this.getCelula().setImageFromPersonagem(); } @Override public void influenciaVizinhos() { // Não influencia ninguém } @Override public void verificaEstado() { // Se esta morto retorna if (!this.estaVivo()){ return; } // Se esta infectado perde energia a cada passo if (this.infectado()) { diminuiEnergia(2); // Se não tem mais energia morre if (this.getEnergia() == 0) { Random chance = new Random(); boolean aux = chance.nextBoolean(); if(aux == true){ this.setImage("Morto"); this.getCelula().setImageFromPersonagem(); } else if(aux == false){ // Pega a celula atual int lin = this.getCelula().getLinha(); int col = this.getCelula().getColuna(); // Remove cidadao Jogo.getInstance().getCelula(lin, col).setPersonagem(null); Jogo.getInstance().removeCidadao(this); // Coloca zumbi na nova posicao Jogo.getInstance().addZumbi(lin, col); } } } } }
package br.com.ecommerce.tests.retaguarda.cadastros; import org.junit.Test; import br.com.ecommerce.config.BaseTest; import br.com.ecommerce.pages.retaguarda.cadastros.unidades.PageEditarUnidade; import br.com.ecommerce.pages.retaguarda.cadastros.unidades.PageIncluirUnidade; import br.com.ecommerce.pages.retaguarda.cadastros.unidades.PageUnidade; import br.com.ecommerce.pages.retaguarda.dashboard.PageMenu; import br.com.ecommerce.util.Utils; /** * * Classe de testes com cenários relacionados ao Cadastros >> Tipos de Conta * @author Jarbas * * */ public class TestCadastrosUnidades extends BaseTest{ PageMenu pageMenu = new PageMenu(); PageUnidade pageUnidade = new PageUnidade(); PageEditarUnidade pageEditarUnidade = new PageEditarUnidade(); PageIncluirUnidade pageIncluirUnidade = new PageIncluirUnidade(); @Test public void cadastrarUnidadeTesteComSucesso(){ String unidade = "Unidade Teste " + Utils.geraSigla(4); String abreviacao = "Abreviação " + unidade; pageMenu.acessarMenuCadastrosUnidades(); pageUnidade.verificarOrtografiaPageUnidade(); pageUnidade.navegarParaPaginaIncluirUnidade(); pageIncluirUnidade.verificarOrtografiaPageIncluirUnidade(); pageIncluirUnidade.incluirUnidade(unidade, abreviacao); pageUnidade.validaMsgSucessoInclusao(); pageMenu.acessarMenuCadastrosUnidades(); pageUnidade.verificarOrtografiaPageUnidade(); pageUnidade.validarUnidadeInseridaAtivada(unidade, abreviacao); } @Test public void alterarAtivandoUnidadeTesteComSucesso(){ String unidadeAtual = null; String novaUnidade = "Unidade Teste " + Utils.geraSigla(4); String abreviacao = null; pageMenu.acessarMenuCadastrosUnidades(); pageUnidade.verificarOrtografiaPageUnidade(); if (!pageUnidade.existsUnidadeTeste()) { unidadeAtual = "Unidade Teste " + Utils.geraSigla(3); abreviacao = "Abreviação " + unidadeAtual; pageUnidade.navegarParaPaginaIncluirUnidade(); pageIncluirUnidade.incluirUnidade(unidadeAtual, abreviacao); pageUnidade.validaMsgSucessoInclusao(); pageMenu.acessarMenuCadastrosUnidades(); pageUnidade.verificarOrtografiaPageUnidade(); pageUnidade.validarUnidadeInseridaAtivada(unidadeAtual, abreviacao); }else{ unidadeAtual = pageUnidade.getUnidadeTeste(); abreviacao = "Abreviação " + novaUnidade; } if (!pageUnidade.isAtiva(unidadeAtual)) { pageUnidade.ativarUnidadeTeste(unidadeAtual); } pageUnidade.navegarParaPaginaEdicaoUnidade(unidadeAtual); pageEditarUnidade.verificarOrtografiaPageEditarUnidade(); pageEditarUnidade.alterarUnidade(novaUnidade, abreviacao); pageUnidade.validaMsgSucessoAlteracao(); pageMenu.acessarMenuCadastrosUnidades(); pageUnidade.verificarOrtografiaPageUnidade(); pageUnidade.validarUnidadeInseridaAtivada(novaUnidade, abreviacao); } @Test public void removerUnidadeTesteComSucesso(){ String unidade = null; String abreviacao = null; pageMenu.acessarMenuCadastrosUnidades(); pageUnidade.verificarOrtografiaPageUnidade(); if (!pageUnidade.existsUnidadeTeste()) { unidade = "Unidade Teste " + Utils.geraSigla(3); abreviacao = "Abreviação " + unidade; pageUnidade.navegarParaPaginaIncluirUnidade(); pageIncluirUnidade.incluirUnidade(unidade, abreviacao); pageUnidade.validaMsgSucessoInclusao(); pageMenu.acessarMenuCadastrosUnidades(); pageUnidade.verificarOrtografiaPageUnidade(); pageUnidade.validarUnidadeInseridaDesativada(unidade, abreviacao); }else{ unidade = pageUnidade.getUnidadeTeste(); } pageUnidade.removerUnidade(unidade); pageMenu.acessarMenuCadastrosUnidades(); pageUnidade.verificarOrtografiaPageUnidade(); pageUnidade.validarUnidadeRemovida(unidade); } @Test public void ativarUnidadeTesteComSucesso(){ String unidade = null; String abreviacao = null; pageMenu.acessarMenuCadastrosUnidades(); pageUnidade.verificarOrtografiaPageUnidade(); if (!pageUnidade.existsUnidadeTeste()) { unidade = "Unidade Teste " + Utils.geraSigla(3); abreviacao = "Abreviação " + unidade; pageUnidade.navegarParaPaginaIncluirUnidade(); pageIncluirUnidade.incluirUnidade(unidade, abreviacao); pageUnidade.validaMsgSucessoInclusao(); pageMenu.acessarMenuCadastrosUnidades(); pageUnidade.verificarOrtografiaPageUnidade(); pageUnidade.validarUnidadeInseridaAtivada(unidade, abreviacao); }else{ unidade = pageUnidade.getUnidadeTeste(); abreviacao = pageUnidade.getAbreviacaoTeste(unidade); } if (pageUnidade.isAtiva(unidade)) { pageUnidade.desativarUnidadeTeste(unidade); } pageUnidade.ativarUnidadeTeste(unidade); pageMenu.acessarMenuCadastrosUnidades(); pageUnidade.verificarOrtografiaPageUnidade(); pageUnidade.validarUnidadeInseridaAtivada(unidade, abreviacao); } @Test public void desativarUnidadeTesteComSucesso(){ String unidade = null; String abreviacao = null; pageMenu.acessarMenuCadastrosUnidades(); pageUnidade.verificarOrtografiaPageUnidade(); if (!pageUnidade.existsUnidadeTeste()) { unidade = "Unidade Teste " + Utils.geraSigla(3); abreviacao = "Abreviação " + unidade; pageUnidade.navegarParaPaginaIncluirUnidade(); pageIncluirUnidade.incluirUnidade(unidade, abreviacao); pageUnidade.validaMsgSucessoInclusao(); pageMenu.acessarMenuCadastrosUnidades(); pageUnidade.verificarOrtografiaPageUnidade(); pageUnidade.validarUnidadeInseridaDesativada(unidade, abreviacao); }else{ unidade = pageUnidade.getUnidadeTeste(); abreviacao = pageUnidade.getAbreviacaoTeste(unidade); } if (!pageUnidade.isAtiva(unidade)) { pageUnidade.ativarUnidadeTeste(unidade); } pageUnidade.desativarUnidadeTeste(unidade); pageMenu.acessarMenuCadastrosUnidades(); pageUnidade.verificarOrtografiaPageUnidade(); pageUnidade.validarUnidadeInseridaDesativada(unidade, abreviacao); } }
package com.tencent.wecall.talkroom.model; import com.tencent.pb.talkroom.sdk.MultiTalkGroup; import com.tencent.wecall.talkroom.model.g.a; class g$21 implements Runnable { final /* synthetic */ int esz; final /* synthetic */ MultiTalkGroup ltO; final /* synthetic */ g vyO; g$21(g gVar, int i, MultiTalkGroup multiTalkGroup) { this.vyO = gVar; this.esz = i; this.ltO = multiTalkGroup; } public final void run() { synchronized (this.vyO.cWy) { for (a a : this.vyO.cWy) { a.a(this.esz, this.ltO); } } } }
import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class SpaceShip extends JPanel implements Runnable { double width, height; double x = width / 2, y = height / 2, dx = 1.618034 * 3, dy = 3; // 初期値は変更しても良いようになっていること Thread thread = null; public SpaceShip() { setPreferredSize(new Dimension(200, 200)); startThread(); } public void startThread() { if (thread == null) { thread = new Thread(this); thread.start(); } } public void stopThread() { thread = null; } @Override public void run() { Thread me = Thread.currentThread(); while (thread == me) { x += dx; y += dy; if (x > 200) x -= 200; else if (x < 0) x += 200; if (y > 200) y -= 200; else if (y < 0) y += 200; repaint(); try { Thread.sleep(40); } catch (InterruptedException e) { } } } @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.GREEN); g.fillOval((int)x, (int)y, 10, 10); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame("SpaceShip!"); frame.add(new SpaceShip()); frame.pack(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }); } }
package cn.ouyangnengda.dubbo.DemoService; import org.apache.dubbo.config.annotation.Reference; /** * @Description: * @Author: 欧阳能达 * @Created: 2019年09月08日 15:22:00 **/ public class DemoServiceImpl { @Reference private DemoService demoService; public String sayHello(String s) { return demoService.sayHello(s); } }
package com.tencent.mm.plugin.webview.ui.tools; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; class SDKOAuthUI$1 implements OnMenuItemClickListener { final /* synthetic */ SDKOAuthUI pWs; SDKOAuthUI$1(SDKOAuthUI sDKOAuthUI) { this.pWs = sDKOAuthUI; } public final boolean onMenuItemClick(MenuItem menuItem) { SDKOAuthUI.a(this.pWs); this.pWs.finish(); return true; } }
package br.com.utfpr.eventos.controller; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import br.com.utfpr.eventos.dao.EventDAO; import br.com.utfpr.eventos.models.Event; import br.com.utfpr.eventos.models.Search; import br.com.utfpr.eventos.validation.SearchValidation; @Controller @RequestMapping("/search") public class SearchController { @Autowired private EventDAO eventDAO; @InitBinder public void initBinder(WebDataBinder binder){ binder.addValidators(new SearchValidation()); } @RequestMapping(method=RequestMethod.POST) public ModelAndView search(@Valid Search search, BindingResult result, RedirectAttributes redirectAttributes) { ModelAndView modelAndView = new ModelAndView("event/list"); if(result.hasErrors()) { return new ModelAndView("redirect:events"); } List<Event> listEventByName = eventDAO.getEventsByName(search.getSearch()); if(listEventByName.isEmpty()) { modelAndView.addObject("emptySet", true); } modelAndView.addObject("events", listEventByName); return modelAndView; } }
package com.tencent.mm.pluginsdk; public interface s { Object cbm(); Object cbn(); }
package org.dmonix.util; /** * <p> * Class for getting System parameters. * </p> * The class includes convenient methods for extracting System properties. * <p> * Copyright: Copyright (c) 2003 * </p> * <p> * Company: dmonix.org * </p> * * @author Peter Nerg * @since 1.0 */ public abstract class SystemPropertyHandler { /** */ public static final String FILE_SEPARATOR = "file.separator"; /** */ public static final String JAVA_CLASS_PATH = "java.class.path"; /** */ public static final String JAVA_HOME = "java.home"; /** */ public static final String JAVA_LIB_PATH = "java.library.path"; /** */ public static final String JAVA_RUNTIME_NAME = "java.runtime.name"; /** */ public static final String JAVA_RUNTIME_VERSION = "java.runtime.version"; /** */ public static final String JAVA_VENDOR_URL = "java.vendor.url"; /** */ public static final String JAVA_VERSION = "java.version"; /** */ public static final String JAVA_VM_VENDOR = "java.vm.vendor"; /** */ public static final String JAVA_VM_VERSION = "java.vm.version"; /** */ public static final String LINE_SEPARATOR = "line.separator"; /** */ public static final String OS_NAME = "os.name"; /** */ public static final String PATH_SEPARATOR = "path.separator"; /** */ public static final String USER_COUNTRY = "user.country"; /** */ public static final String USER_HOME = "user.home"; /** */ public static final String USER_NAME = "user.name"; /** * Prints out all System properties to System.out. */ public static void debug() { SystemPropertyHandler.debug(System.out); } /** * Prints out all System properties. * * @param ostream * The stream to write to */ public static void debug(java.io.PrintStream ostream) { System.getProperties().list(ostream); } /** * Get the System property <code>file separator</code>. * * @return The property, null if not found */ public static String getFileSeparator() { return SystemPropertyHandler.getProperty(SystemPropertyHandler.FILE_SEPARATOR); } /** * Get the System property <code>Java home</code>. * * @return The property, null if not found */ public static String getJavaHome() { return SystemPropertyHandler.getProperty(SystemPropertyHandler.JAVA_HOME); } /** * Get the System property <code>Java lib path</code>. * * @return The property, null if not found */ public static String getJavaLibPath() { return SystemPropertyHandler.getProperty(SystemPropertyHandler.JAVA_LIB_PATH); } /** * Get the System property <code>Java runtime name</code>. * * @return The property, null if not found */ public static String getJavaRuntimeName() { return SystemPropertyHandler.getProperty(SystemPropertyHandler.JAVA_RUNTIME_NAME); } /** * Get the System property <code>Java runtime version</code>. * * @return The property, null if not found */ public static String getJavaRuntimeVersion() { return SystemPropertyHandler.getProperty(SystemPropertyHandler.JAVA_RUNTIME_VERSION); } /** * Get the System property <code>Java vendor url</code>. * * @return The property, null if not found */ public static String getJavaVendorUrl() { return SystemPropertyHandler.getProperty(SystemPropertyHandler.JAVA_VENDOR_URL); } /** * Get the System property <code>Java version</code>. * * @return The property, null if not found */ public static String getJavaVersion() { return SystemPropertyHandler.getProperty(SystemPropertyHandler.JAVA_VERSION); } /** * Get the System property <code>Java VM vendor</code>. * * @return The property, null if not found */ public static String getJavaVMVendor() { return SystemPropertyHandler.getProperty(SystemPropertyHandler.JAVA_VM_VENDOR); } /** * Get the System property <code>Java VM version</code>. * * @return The property, null if not found */ public static String getJavaVMVersion() { return SystemPropertyHandler.getProperty(SystemPropertyHandler.JAVA_VM_VERSION); } /** * Get the System property <code>line separator</code>. * * @return The property, null if not found */ public static String getLineSeparator() { return SystemPropertyHandler.getProperty(SystemPropertyHandler.LINE_SEPARATOR); } /** * Get the System property <code>OS name</code>. * * @return The property, null if not found */ public static String getOSName() { return SystemPropertyHandler.getProperty(SystemPropertyHandler.OS_NAME); } /** * Get the System property <code>Path separator</code>. * * @return The property, null if not found */ public static String getPathSeparator() { return SystemPropertyHandler.getProperty(SystemPropertyHandler.PATH_SEPARATOR); } /** * Get the System property <code>user country</code>. * * @return The property, null if not found */ public static String getUserCountry() { return SystemPropertyHandler.getProperty(SystemPropertyHandler.USER_COUNTRY); } /** * Get the System property <code>user name</code>. * * @return The property, null if not found */ public static String getUserName() { return SystemPropertyHandler.getProperty(SystemPropertyHandler.USER_NAME); } /** * Get the System property <code>user home</code>. * * @return The property, null if not found */ public static String getUserHome() { return SystemPropertyHandler.getProperty(SystemPropertyHandler.USER_HOME); } /** * Get the requested system property. * * @param property * The property to get * @return The property, null if not found */ public static String getProperty(String property) { return System.getProperty(property); } public static void main(String[] param) { SystemPropertyHandler.debug(System.out); } }
package toolkit; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.JTableHeader; import java.sql.ResultSet; import java.util.Vector; import java.sql.ResultSetMetaData; import java.sql.SQLException; /** * Tabel table = new Tabel(resultset) * table.jt * table.jsp1 * table.columnName * table.rowcount */ public class Table{ private ResultSet res; private ResultSetMetaData rmd; private Vector rowData = new Vector(); private Vector columnName = new Vector(); public int rowcount; public int columncount; public JTable jt; private JTableHeader head; public JScrollPane jsp1=null; public Table(ResultSet res_in) throws SQLException { res = res_in; rmd = res.getMetaData(); get_column(); get_content(); jt = generate_table(); jsp1 = new JScrollPane(this.jt); } private void get_column() throws SQLException { columncount = rmd.getColumnCount(); for(int i=1;i<=columncount;i++) { columnName.add(rmd.getColumnName(i)); } } private void get_content() throws SQLException { while(res.next()) { rowcount+=1; Vector hang = new Vector(); for (int i=1;i<=columncount;i++) { hang.add(res.getString(i)); } rowData.add(hang); } } private JTable generate_table() { JTable jt = new JTable(rowData,columnName){ public boolean isCellEditable(int row, int column) {return false;} }; return jt; } }
package scriptinterface.defaulttypes; import graphloaders.FileFormat; import scriptinterface.ScriptType; import scriptinterface.execution.returnvalues.ExecutionResult; import java.io.File; /** * Script type wrapper for File. */ public class GFile extends ExecutionResult<File> implements TextHolder { private final static ScriptType TYPE = new ScriptType("File", "File"); protected File value; protected FileFormat format; public GFile(File value) { this.value = value; this.format = FileFormat.AUTO; } public GFile(File value, FileFormat format) { this.value = value; this.format = format; } public GFile() { this(null); } @Override public File getValue() { return value; } @Override public void setValue(File value) { this.value = value; } public FileFormat getFormat() { return format; } public void setFormat(FileFormat format) { this.format = format; } @Override public ScriptType getType() { return TYPE; } @Override public GFile clone() { return new GFile(value); } @Override public String getText() { return value.getAbsolutePath(); } @Override public String getStringRepresentation() { return value.getAbsolutePath(); } @Override public String getScriptConstantRepresentation() { return "\"" + this.getStringRepresentation() + "\""; } }
package level1; import java.util.*; // https://school.programmers.co.kr/learn/courses/30/lessons/12906 public class 같은_숫자는_싫어 { public class Solution { public int[] solution(int[] arr) { // HashSet<Integer> set = new HashSet<>(); // Arrays.stream(arr).forEach(it -> set.add(it)); // int[] answer = new int[set.size()]; // int index = 0; //// answer = set.toArray(new Integer[set.size()]); // for (Integer integer : set) { // answer[index] = integer; // index++; // } // // return answer; int[] answer; Stack<Integer> stack = new Stack<>(); for (int i : arr) { stack.push(i); if (stack.size() >= 2) { if (stack.get(stack.size() - 2).equals(stack.get(stack.size() - 1))) { // integer 자료형이므로 equals 사용 가능 stack.pop(); } } } answer = new int[stack.size()]; int index = 0; for (Integer stackEl : stack) { answer[index++] = stackEl; } return answer; } } } /** * * int : 자료형(primitive type) * 산술 연산 가능함 * null 로 초기화 불가 * * Integer : 래퍼 클래스 (Wrapper class) * 객체 간 비교하고 싶을 때 ex) equals() * 기본형 값이 아닌 객체로 저장하고 싶을 때 * Unboxing 하지 않을 시 산술 연산 불가능함 * null 값 처리 가능 */
package br.com.isidrocorp.pibank.model; public class ContaEspecial extends Conta{ private double limite; public ContaEspecial(int numConta, String titular, String cpf, double saldo, double limite) { super(numConta, titular, cpf, saldo); this.limite = limite; } @Override public boolean debitar(double valor) { if (valor <= super.saldo + this.limite) { super.saldo -= valor; return true; } else { return false; } } public double getLimite() { return limite; } public void setLimite(double limite) { this.limite = limite; } public String toString() { return "E:"+super.numConta+" "+super.titular+" ("+super.cpf+") R$ " +super.saldo+" R$ "+this.limite; } }
package info.czajkowska.spring.implemantation; import info.czajkowska.spring.api.Logger; import info.czajkowska.spring.api.UsersRepository; import info.czajkowska.spring.domain.User; public class UsersRepositoryImpl implements UsersRepository { private Logger logger;// zmienna przechowująca loggera public User createUser(String name) { logger.log("Tworzenie użytkownika " + name); return new User(name); } public void setLogger(Logger logger) { this.logger = logger; } }
package com.bytedance.platform.godzilla.d; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import com.bytedance.platform.godzilla.e.f; import java.lang.reflect.Field; import java.util.HashMap; public final class d { private static volatile Handler a = new Handler(Looper.getMainLooper()); private static HashMap<String, HandlerThread> b = new HashMap<String, HandlerThread>(); public static final class a extends HandlerThread { private volatile boolean a; public a(String param1String, int param1Int1, int param1Int2) { super(param1String, param1Int1); if (param1Int2 != 0) a(param1Int2); } private boolean a(long param1Long) { Field field = com.bytedance.platform.godzilla.e.a.a(HandlerThread.class, "stackSize"); if (field != null) { boolean bool; field.setAccessible(true); if (field != null) { bool = true; } else { bool = false; } if (bool) { try { if (!field.isAccessible()) field.setAccessible(true); if (((Long)field.get(this)).longValue() != param1Long) { field = (Field)f.a(field, "The field must not be null"); if (!field.isAccessible()) field.setAccessible(true); field.set(this, Long.valueOf(param1Long)); return true; } } catch (IllegalAccessException illegalAccessException) { return false; } } else { throw new IllegalArgumentException("The field must not be null"); } } else { return false; } return true; } public final void start() { // Byte code: // 0: aload_0 // 1: monitorenter // 2: aload_0 // 3: getfield a : Z // 6: istore_1 // 7: iload_1 // 8: ifeq -> 14 // 11: aload_0 // 12: monitorexit // 13: return // 14: aload_0 // 15: iconst_1 // 16: putfield a : Z // 19: aload_0 // 20: invokespecial start : ()V // 23: aload_0 // 24: monitorexit // 25: return // 26: astore_2 // 27: aload_0 // 28: monitorexit // 29: aload_2 // 30: athrow // Exception table: // from to target type // 2 7 26 finally // 14 23 26 finally } } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\bytedance\platform\godzilla\d\d.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.duanxr.yith.easy; import com.duanxr.yith.define.listNode.ListNode; import java.util.ArrayList; import java.util.List; /** * @author 段然 2021/3/16 */ public class PalindromeLinkedListLCCI { /** * Implement a function to check if a linked list is a palindrome. * * Example 1: * * Input: 1->2 * Output: false * Example 2: * * Input: 1->2->2->1 * Output: true *   * * Follow up: * Could you do it in O(n) time and O(1) space? * * 编写一个函数,检查输入的链表是否是回文的。 * *   * * 示例 1: * * 输入: 1->2 * 输出: false * 示例 2: * * 输入: 1->2->2->1 * 输出: true *   * * 进阶: * 你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题? * */ class Solution { public boolean isPalindrome(ListNode head) { if (head == null) { return true; } List<Integer> list = new ArrayList<>(); while (head != null) { list.add(head.val); head = head.next; } int l = 0; int r = list.size() - 1; while (l < r) { if (!list.get(l++).equals(list.get(r--))) { return false; } } return true; } } }
package email; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.mail.DefaultAuthenticator; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.SimpleEmail; public class Teste{ public Teste() { } public void enviarEmail(String de, String para, String msg){ System.out.println("para: " + para); System.out.println("msg: " + msg); try { org.apache.commons.mail.Email email = new SimpleEmail(); email.setHostName("smtp.gmail.com"); email.setSmtpPort(587); email.setAuthenticator(new DefaultAuthenticator("gabiateste@gmail.com", "bolodechocolate")); email.setSSLOnConnect(true); email.setFrom("gabriellicorrea7@gmail.com"); email.setSubject(""); email.setMsg(msg); email.addTo(para); email.send(); }catch(EmailException ex) { Logger.getLogger(Teste.class.getName()).log(Level.SEVERE, null, ex); } } }
package fel_1; import java.util.Random; public class Main { public static void main(String[] args) { Bank otp = new Bank("OTP"); otp.addCustomer(new Customer("Hank", "Green")); otp.addCustomer(new Customer("John", "Green")); otp.getCustomer(1).addAccount(new CheckingAccount(500)); otp.getCustomer(1).addAccount(new SavingsAccount(0.1)); otp.getCustomer(2).addAccount(new CheckingAccount(700)); otp.getCustomer(2).addAccount(new SavingsAccount(0.1)); Random rand = new Random(); for (int i = 1; i <= otp.numCustomers(); i++) { String[] accountNumbers = otp.getCustomer(i).getAccountNumbers(); for (String accountNumber : accountNumbers) { otp.getCustomer(i).getAccount(accountNumber).deposit(rand.nextInt(1000)); } } otp.printCustomersToStdout(); } }
package com.service; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.dao.DirectionDao; import com.entity.Curriculum; import com.entity.Direction; @Service @Transactional public class DirectionService { @Resource DirectionDao dd; public List<Direction> queryAll() { return dd.queryAll(); } public void add(Direction d) { dd.add(d); } public void upd(Direction d) { dd.upd(d); } public void del(Integer d_id) { dd.del(d_id); } public List<Curriculum> queryByDirection(String d_name, Integer c_vip, Integer c_level) { return dd.queryByDirection(d_name, c_vip, c_level); } // 分页查询所有技术方向 public List<Direction> queryDirection(Integer page, Integer limit) { return dd.queryDirection(page, limit); } }
package com.rhysnguyen.casestudyjavaweb.dao; import com.rhysnguyen.casestudyjavaweb.entity.Position; import org.springframework.data.jpa.repository.JpaRepository; public interface PositionRepository extends JpaRepository<Position, Long > { }
package htw_berlin.de.totoro_client.Model; import java.util.List; /** * Created by tim on 26.07.16. */ public class Tournament { int id; String name; String modus; int set_count; List<Team> teams; int parent; int max_phase; boolean over; String url; 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 String getModus() { return modus; } public void setModus(String modus) { this.modus = modus; } public int getSet_count() { return set_count; } public void setSet_count(int set_count) { this.set_count = set_count; } public List<Team> getTeams() { return teams; } public void setTeams(List<Team> teams) { this.teams = teams; } public int getParent() { return parent; } public void setParent(int parent) { this.parent = parent; } public int getMax_phase() { return max_phase; } public void setMax_phase(int max_phase) { this.max_phase = max_phase; } public boolean isOver() { return over; } public void setOver(boolean over) { this.over = over; } @Override public String toString() { return name; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.contrib.index.mapred; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.ConcurrentLinkedQueue; import org.apache.hadoop.contrib.index.lucene.RAMDirectoryUtil; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.KeepOnlyLastCommitDeletionPolicy; import org.apache.lucene.index.Term; import org.apache.lucene.store.Directory; import org.apache.lucene.store.RAMDirectory; /** * An intermediate form for one or more parsed Lucene documents and/or * delete terms. It actually uses Lucene file format as the format for * the intermediate form by using RAM dir files. * * Note: If process(*) is ever called, closeWriter() should be called. * Otherwise, no need to call closeWriter(). */ public class IntermediateForm implements Writable { private IndexUpdateConfiguration iconf = null; private final Collection<Term> deleteList; private RAMDirectory dir; private IndexWriter writer; private int numDocs; /** * Constructor * @throws IOException */ public IntermediateForm() throws IOException { deleteList = new ConcurrentLinkedQueue<Term>(); dir = new RAMDirectory(); writer = null; numDocs = 0; } /** * Configure using an index update configuration. * @param iconf the index update configuration */ public void configure(IndexUpdateConfiguration iconf) { this.iconf = iconf; } /** * Get the ram directory of the intermediate form. * @return the ram directory */ public Directory getDirectory() { return dir; } /** * Get an iterator for the delete terms in the intermediate form. * @return an iterator for the delete terms */ public Iterator<Term> deleteTermIterator() { return deleteList.iterator(); } /** * This method is used by the index update mapper and process a document * operation into the current intermediate form. * @param doc input document operation * @param analyzer the analyzer * @throws IOException */ public void process(DocumentAndOp doc, Analyzer analyzer) throws IOException { if (doc.getOp() == DocumentAndOp.Op.DELETE || doc.getOp() == DocumentAndOp.Op.UPDATE) { deleteList.add(doc.getTerm()); } if (doc.getOp() == DocumentAndOp.Op.INSERT || doc.getOp() == DocumentAndOp.Op.UPDATE) { if (writer == null) { // analyzer is null because we specify an analyzer with addDocument writer = createWriter(); } writer.addDocument(doc.getDocument(), analyzer); numDocs++; } } /** * This method is used by the index update combiner and process an * intermediate form into the current intermediate form. More specifically, * the input intermediate forms are a single-document ram index and/or a * single delete term. * @param form the input intermediate form * @throws IOException */ public void process(IntermediateForm form) throws IOException { if (form.deleteList.size() > 0) { deleteList.addAll(form.deleteList); } if (form.dir.sizeInBytes() > 0) { if (writer == null) { writer = createWriter(); } writer.addIndexesNoOptimize(new Directory[] { form.dir }); numDocs++; } } /** * Close the Lucene index writer associated with the intermediate form, * if created. Do not close the ram directory. In fact, there is no need * to close a ram directory. * @throws IOException */ public void closeWriter() throws IOException { if (writer != null) { writer.close(); writer = null; } } /** * The total size of files in the directory and ram used by the index writer. * It does not include memory used by the delete list. * @return the total size in bytes */ public long totalSizeInBytes() throws IOException { long size = dir.sizeInBytes(); if (writer != null) { size += writer.ramSizeInBytes(); } return size; } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append(this.getClass().getSimpleName()); buffer.append("[numDocs="); buffer.append(numDocs); buffer.append(", numDeletes="); buffer.append(deleteList.size()); if (deleteList.size() > 0) { buffer.append("("); Iterator<Term> iter = deleteTermIterator(); while (iter.hasNext()) { buffer.append(iter.next()); buffer.append(" "); } buffer.append(")"); } buffer.append("]"); return buffer.toString(); } private IndexWriter createWriter() throws IOException { IndexWriter writer = new IndexWriter(dir, false, null, new KeepOnlyLastCommitDeletionPolicy()); writer.setUseCompoundFile(false); if (iconf != null) { int maxFieldLength = iconf.getIndexMaxFieldLength(); if (maxFieldLength > 0) { writer.setMaxFieldLength(maxFieldLength); } } return writer; } private void resetForm() throws IOException { deleteList.clear(); if (dir.sizeInBytes() > 0) { // it's ok if we don't close a ram directory dir.close(); // an alternative is to delete all the files and reuse the ram directory dir = new RAMDirectory(); } assert (writer == null); numDocs = 0; } // /////////////////////////////////// // Writable // /////////////////////////////////// /* (non-Javadoc) * @see org.apache.hadoop.io.Writable#write(java.io.DataOutput) */ public void write(DataOutput out) throws IOException { out.writeInt(deleteList.size()); for (Term term : deleteList) { Text.writeString(out, term.field()); Text.writeString(out, term.text()); } String[] files = dir.list(); RAMDirectoryUtil.writeRAMFiles(out, dir, files); } /* (non-Javadoc) * @see org.apache.hadoop.io.Writable#readFields(java.io.DataInput) */ public void readFields(DataInput in) throws IOException { resetForm(); int numDeleteTerms = in.readInt(); for (int i = 0; i < numDeleteTerms; i++) { String field = Text.readString(in); String text = Text.readString(in); deleteList.add(new Term(field, text)); } RAMDirectoryUtil.readRAMFiles(in, dir); } }
import java.net.*; import java.io.*; import java.util.*; import javax.swing.*; import java.awt.BorderLayout; class ClientServer extends Thread { public static int contorClient = 0; private Socket clientSocket = null; public static int Rrandom (){ return (int)Math.floor(Math.random()*10); } public void run() { //informatii despre client InetAddress adresaClient=clientSocket.getInetAddress(); MyFrame.getInstance().addText("Client nou la adresa: "+adresaClient); //System.out.println("Nume client: <Client " + nrClient + ">"); int ei = Rrandom (); //se executa dialogul cu clientul BufferedReader in = null; PrintWriter out = null; try { //fluxul de intrare de la client in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); //System.out.println(in); //fluxul de iesire catre client out = new PrintWriter(clientSocket.getOutputStream(),true); String mesaj; out.println("STart joc. Scrieti numarul"); while((mesaj = in.readLine())!= null){ int nrclient = Integer.parseInt(mesaj); //raspuns="<Client " + nrClient + "> : " + mesaj; if (nrclient==ei) { out.println("Adevarat! Doresti sa joci din nou? (Y/N)"); if(in.readLine().equalsIgnoreCase("Y")){//continua sa joace ei=Rrandom (); out.println("Numarul ales trebuie sa fie intre 1 si 10"); }else break; } else if (nrclient>=ei) out.println("Nu ai ghicit! Incearca un numar mai mic! "); else if(nrclient <= ei) out.println("Nu ai ghicit! Incearca un numar mai mare!"); } } catch(EOFException e){} catch (IOException e) {} finally { MyFrame.getInstance().addText(adresaClient+" deconecatat"); MyFrame.getInstance().setNrOfPlayers(--contorClient); try { if (in != null) in.close(); if (out != null) out.close(); if (clientSocket != null) clientSocket.close(); } catch (IOException e) {System.err.println(e);} } } public ClientServer(Socket s){ clientSocket = s; MyFrame.getInstance().setNrOfPlayers(++contorClient); } } class Server{ public static int Rrandom (int a){ Random r = new Random(); int ei = r.nextInt(a); return ei; } public static void main(String[] args) throws IOException { int PORT = 4567; ServerSocket serverSocket = new ServerSocket(PORT); MyFrame.getInstance(); while(true){ Socket sochet = serverSocket.accept(); ClientServer ss=new ClientServer(sochet); ss.start(); } } } class MyFrame extends JFrame { private JTextArea text; private JLabel clientiinjoc; private static MyFrame instance; private MyFrame(){ super("Server"); this.text=new JTextArea(30,50); text.setEditable(false); this.text.append("Server start\n"); this.getContentPane().add(new JScrollPane(text)); this.clientiinjoc=new JLabel("Clienti in joc:0"); this.getContentPane().add(clientiinjoc, BorderLayout.NORTH); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.pack(); } public static MyFrame getInstance(){ if(instance==null) instance=new MyFrame(); return instance; } public static void addText(String text){ instance.text.append(text+"\n"); } public static void setNrOfPlayers(int nr){ instance.clientiinjoc.setText("Clienti in joc:"+nr); } }
/** * Copyright (c) 2012, Ben Fortuna * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * o Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * o Neither the name of Ben Fortuna nor the names of any other contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.fortuna.ical4j.vcard; import static junit.framework.Assert.assertEquals; import java.io.File; import java.io.FileFilter; import java.io.FileReader; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collection; import java.util.List; import net.fortuna.ical4j.data.ParserException; import net.fortuna.ical4j.model.ValidationException; import net.fortuna.ical4j.util.CompatibilityHints; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** * Created on: 29/12/2008 * * @author Ben * */ @RunWith(Parameterized.class) public class VCardOutputterTest { private final VCardOutputter outputter; private final VCard card; private final String expectedOutput; /** * @param outputter * @param card * @param expectedOutput */ public VCardOutputterTest(VCardOutputter outputter, VCard card, String expectedOutput) { this.outputter = outputter; this.card = card; this.expectedOutput = expectedOutput; } @Test public void testOutput() throws IOException, ValidationException { StringWriter out = new StringWriter(); outputter.output(card, out); assertEquals(expectedOutput, out.toString().replaceAll("\\r\\n ", "")); } @Parameters public static Collection<Object[]> parameters() throws IOException, ParserException { VCardOutputter outputter = new VCardOutputter(false, 1000); VCardBuilder builder = null; List<Object[]> params = new ArrayList<Object[]>(); File[] testFiles = new File("src/test/resources/samples/valid").listFiles( (FileFilter) VCardFileFilter.INSTANCE); // enable relaxed parsing for non-standard GEO support.. CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true); for (int i = 0; i < testFiles.length; i++) { builder = new VCardBuilder(new FileReader(testFiles[i])); VCard card = builder.build(); params.add(new Object[] {outputter, card, card.toString()}); } CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, false); return params; } }
package com.woting.appengine.accusation.service; import java.util.HashMap; import java.util.Map; import javax.annotation.PostConstruct; import javax.annotation.Resource; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import com.spiritdata.framework.core.dao.mybatis.MybatisDAO; import com.spiritdata.framework.util.SequenceUUID; import com.spiritdata.framework.util.StringUtils; import com.woting.appengine.accusation.persis.po.ContentAccusationPo; import com.woting.cm.core.broadcast.persis.po.BroadcastPo; import com.woting.cm.core.media.MediaType; import com.woting.cm.core.media.persis.po.MediaAssetPo; import com.woting.cm.core.media.persis.po.SeqMediaAssetPo; import com.woting.passport.mobile.MobileUDKey; @Lazy(true) @Service public class AccusationService { @Resource(name="defaultDAO") private MybatisDAO<BroadcastPo> bcDao; @Resource(name="defaultDAO") private MybatisDAO<MediaAssetPo> mediaAssetDao; @Resource(name="defaultDAO") private MybatisDAO<SeqMediaAssetPo> seqMediaAssetDao; @Resource(name="defaultDAO") private MybatisDAO<ContentAccusationPo> accusationPo; @PostConstruct public void initParam() { bcDao.setNamespace("A_BROADCAST"); mediaAssetDao.setNamespace("A_MEDIA"); seqMediaAssetDao.setNamespace("A_MEDIA"); accusationPo.setNamespace("ACCUSATION"); } /** * 喜欢或取消喜欢某个内容 * @param mediaType 内容类型 * @param contentId 内容Id * @param selReasons 选择性原因,用逗号隔开,例:3244e3234e23444352245::侵权,234::违法 * @param inputReason 输入原因,100个汉字以内 * @param mUdk 用户标识,可以是登录用户,也可以是手机设备 * @return 若成功返回1;用户标识为空,返回-1;若内容Id为空返回-2;若mediaType不合法,返回-3;若得不到原因,返回-4;若内容不存在,返回-5;若选择性原因不合法,返回-6 */ public int accuseContent(String mediaType, String contentId, String selReasons, String inputReason, MobileUDKey mUdk) { if (mUdk==null) return -1; if (StringUtils.isNullOrEmptyOrSpace(contentId)) return -2; if (MediaType.buildByTypeName(mediaType.toUpperCase())==MediaType.ERR) return -3; if (StringUtils.isNullOrEmptyOrSpace(selReasons)&&StringUtils.isNullOrEmptyOrSpace(inputReason)) return -4; //检查内容是否存在 Object c=null; switch (MediaType.buildByTypeName(mediaType.toUpperCase())) { case RADIO: c=bcDao.queryForListAutoTranform("getListByWhere", "a.id='"+contentId+"'"); break; case AUDIO: c=mediaAssetDao.getInfoObject("getMaInfoById", contentId); break; case SEQU: c=seqMediaAssetDao.getInfoObject("getSmaInfoById", contentId); break; default: break; } if (c==null) return -5; boolean illegle=false; if (!StringUtils.isNullOrEmptyOrSpace(selReasons)) { String[] sp=selReasons.split(","); for (int i=0; i<sp.length; i++) { if (sp[i].indexOf("::")==-1) { illegle=true; break; } } } if (illegle) return -6; Map<String, Object> param=new HashMap<String, Object>(); param.put("id", SequenceUUID.getPureUUID()); param.put("resTableName", MediaType.buildByTypeName(mediaType.toUpperCase()).getTabName()); param.put("resId", contentId); param.put("selReasons", selReasons); param.put("inputReason", inputReason); param.put("userId", mUdk.isUser()?mUdk.getUserId():"="+mUdk.getDeviceId()); accusationPo.insert(param); return 1; } }
package cn.bs.zjzc.model.impl; import cn.bs.zjzc.App; import cn.bs.zjzc.model.IWithdrawDetailModel; import cn.bs.zjzc.model.callback.HttpTaskCallback; import cn.bs.zjzc.model.response.WithdrawDetailResponse; import cn.bs.zjzc.net.GsonCallback; import cn.bs.zjzc.net.PostHttpTask; import cn.bs.zjzc.net.RequestUrl; /** * Created by Ming on 2016/6/16. */ public class WithdrawDetailModel implements IWithdrawDetailModel { @Override public void getWithdrawDetail(String p, final HttpTaskCallback<WithdrawDetailResponse.DataBean> callback) { String url = RequestUrl.getRequestPath(RequestUrl.SubPaths.withdrawDetail); PostHttpTask<WithdrawDetailResponse> httpTask = new PostHttpTask<>(url); httpTask.addParams("token", App.LOGIN_USER.getToken()) .addParams("page", p) .execute(new GsonCallback<WithdrawDetailResponse>() { @Override public void onFailed(String errorInfo) { callback.onTaskFailed(errorInfo); } @Override public void onSuccess(WithdrawDetailResponse response) { callback.onTaskSuccess(response.data); } }); } }
package views.screen.history; import java.io.IOException; import java.net.URL; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import controller.HomeController; import entity.account.Account; import entity.invoice.Invoice; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.layout.FlowPane; import javafx.stage.Stage; import utils.Configs; import views.screen.BaseScreenHandler; import views.screen.home.HomeScreenHandler; import views.screen.popup.PopupScreen; public class HistoryScreenHandler extends BaseScreenHandler { @FXML private Button homeBtn; @FXML private FlowPane vboxInvoice; private List<HistoryHandler> historyItems; public HistoryScreenHandler(Stage stage, String screenPath) throws IOException { super(stage, screenPath); } @Override public void load() { setHController(new HomeController()); homeScreenHandler.getStage().setOnCloseRequest(e -> { System.out.println("State: " + state); try { if (state == 0) { getHController().updateUsingState(account, false); } else { PopupScreen.warning("Please return bike before exiting"); e.consume(); } } catch (IOException | SQLException e1) { e1.printStackTrace(); } }); homeBtn.setOnMouseClicked(e -> { homeScreenHandler.requestToNewScreen(homeScreenHandler); try { homeScreenHandler.loadAllItems(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }); try { List<Invoice> invoiceList = getHController().getAllInvoices(account); this.historyItems = new ArrayList<>(); System.out.println(invoiceList.size()); for (Object object : invoiceList) { Invoice invoice = (Invoice) object; HistoryHandler h1 = new HistoryHandler(Configs.HISTORY_ITEM_PATH, invoice); h1.load(); this.historyItems.add(h1); } } catch (IOException | SQLException e) { e.printStackTrace(); } addInvoice(this.historyItems); } public void addInvoice(List invoices) { ArrayList invoiceList = (ArrayList)((ArrayList) invoices).clone(); while (!invoiceList.isEmpty()) { HistoryHandler invoice = (HistoryHandler) invoiceList.get(0); vboxInvoice.getChildren().add(invoice.getContent()); invoiceList.remove(invoice); } } @Override public void requestToNewScreen(BaseScreenHandler prevScreen) { System.out.println(homeScreenHandler + " CHECK"); setPreviousScreen(prevScreen); setScreenTitle("History Screen"); setHomeScreenHandler(homeScreenHandler); setAccount(account); show(); } }
import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServlet; import java.io.IOException; import java.io.PrintWriter; public class NewServlet extends HttpServlet { protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { } protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { String name = request.getParameter("name"); String surname = request.getParameter("surname"); // ?name=Tom&surname=Stivenson PrintWriter pw = response.getWriter(); pw.println("<html>"); pw.println("<h1> HELLO, " + name + " " + surname + " </h1>"); pw.println("</html>"); // redirect // response.sendRedirect("/testJsp.jsp"); // forward RequestDispatcher dispatcher = request.getRequestDispatcher("/testJsp.jsp"); dispatcher.forward(request, response); } }
package OCP; /** * @Author:Jack * @Date: 2021/8/22 - 1:24 * @Description: OCP * @Version: 1.0 */ public class OffNovelBooks extends NovelBooks{ public OffNovelBooks(String bName, double bPrice, String bAuthor) { super(bName, bPrice, bAuthor); } @Override public double getPrice() { double offPrice = super.getPrice()-20; return offPrice; } }
package net.minecraft.client.gui; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.I18n; public class GuiListButton extends GuiButton { private boolean value; private final String localizationStr; private final GuiPageButtonList.GuiResponder guiResponder; public GuiListButton(GuiPageButtonList.GuiResponder responder, int p_i45539_2_, int p_i45539_3_, int p_i45539_4_, String p_i45539_5_, boolean p_i45539_6_) { super(p_i45539_2_, p_i45539_3_, p_i45539_4_, 150, 20, ""); this.localizationStr = p_i45539_5_; this.value = p_i45539_6_; this.displayString = buildDisplayString(); this.guiResponder = responder; } private String buildDisplayString() { return String.valueOf(I18n.format(this.localizationStr, new Object[0])) + ": " + I18n.format(this.value ? "gui.yes" : "gui.no", new Object[0]); } public void setValue(boolean p_175212_1_) { this.value = p_175212_1_; this.displayString = buildDisplayString(); this.guiResponder.setEntryValue(this.id, p_175212_1_); } public boolean mousePressed(Minecraft mc, int mouseX, int mouseY) { if (super.mousePressed(mc, mouseX, mouseY)) { this.value = !this.value; this.displayString = buildDisplayString(); this.guiResponder.setEntryValue(this.id, this.value); return true; } return false; } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\client\gui\GuiListButton.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
/* * 2012-3 Red Hat Inc. and/or its affiliates and other contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.overlord.rtgov.active.collection; import static org.junit.Assert.*; import org.junit.Test; import org.overlord.rtgov.active.collection.AbstractActiveCollectionManager; import org.overlord.rtgov.active.collection.ActiveChangeListener; import org.overlord.rtgov.active.collection.ActiveCollection; import org.overlord.rtgov.active.collection.ActiveCollectionListener; import org.overlord.rtgov.active.collection.ActiveCollectionManager; import org.overlord.rtgov.active.collection.ActiveCollectionSource; import org.overlord.rtgov.active.collection.ActiveList; import org.overlord.rtgov.active.collection.predicate.Predicate; public class AbstractActiveCollectionManagerTest { private static final String DERIVED_AC = "DerivedAC"; private static final String TEST_AC="TestActiveCollection"; @Test public void testRegisterACS() { ActiveCollectionManager mgr=new AbstractActiveCollectionManager() {}; ActiveCollectionSource acs=new ActiveCollectionSource(); acs.setName(TEST_AC); try { mgr.register(acs); } catch (Exception e) { fail("Failed to register active collection source: "+e); } // Check that the active collection for this source has been created if (acs.getActiveCollection() == null) { fail("Active collection on source has not been set"); } if (mgr.getActiveCollection(TEST_AC) == null) { fail("Unable to obtain active collection from manager"); } } @Test public void testNetworkListenerNotified() { ActiveCollectionManager mgr=new AbstractActiveCollectionManager() {}; ActiveCollectionSource acs=new ActiveCollectionSource(); acs.setName(TEST_AC); TestActiveCollectionListener l=new TestActiveCollectionListener(); mgr.addActiveCollectionListener(l); if (l._registered.size() != 0) { fail("No active collections should be registered"); } if (l._unregistered.size() != 0) { fail("No active collections should be unregistered"); } try { mgr.register(acs); // Forces creation of active collection which is instantiated // lazily by the mgr mgr.getActiveCollection(acs.getName()); } catch (Exception e) { fail("Failed to register active collection source: "+e); } if (l._registered.size() != 1) { fail("1 active collection should be registered: "+l._registered.size()); } if (l._unregistered.size() != 0) { fail("Still no active collections should be unregistered"); } try { mgr.unregister(acs); } catch (Exception e) { fail("Failed to unregister active collection source: "+e); } if (l._registered.size() != 1) { fail("Still 1 active collection should be registered: "+l._registered.size()); } if (l._unregistered.size() != 1) { fail("1 active collection should be unregistered: "+l._unregistered.size()); } } @Test public void testAlreadyRegisteredACS() { ActiveCollectionManager mgr=new AbstractActiveCollectionManager() {}; ActiveCollectionSource acs=new ActiveCollectionSource(); acs.setName(TEST_AC); try { mgr.register(acs); } catch (Exception e) { fail("Failed to register active collection source: "+e); } try { mgr.register(acs); fail("Should have thrown exception as already registered"); } catch (Exception e) { // Ignore } } @Test public void testRegisterACSWithDerived() { ActiveCollectionManager mgr=new AbstractActiveCollectionManager() {}; ActiveCollectionSource acs=new ActiveCollectionSource(); acs.setName(TEST_AC); ActiveCollectionSource.DerivedDefinition dd=new ActiveCollectionSource.DerivedDefinition(); dd.setName(DERIVED_AC); acs.getDerived().add(dd); try { mgr.register(acs); } catch (Exception e) { fail("Failed to register active collection source: "+e); } // Check that the active collection for this source has been created if (acs.getActiveCollection() == null) { fail("Active collection on source has not been set"); } if (mgr.getActiveCollection(TEST_AC) == null) { fail("Unable to obtain active collection from manager"); } if (mgr.getActiveCollection(DERIVED_AC) == null) { fail("Unable to obtain derived active collection from manager"); } } @Test public void testUnregisterACS() { ActiveCollectionManager mgr=new AbstractActiveCollectionManager() {}; ActiveCollectionSource acs=new ActiveCollectionSource(); acs.setName(TEST_AC); try { mgr.register(acs); } catch (Exception e) { fail("Failed to register active collection source: "+e); } if (mgr.getActiveCollection(TEST_AC) == null) { fail("Unable to obtain active collection from manager"); } try { mgr.unregister(acs); } catch (Exception e) { fail("Failed to unregister active collection source: "+e); } if (mgr.getActiveCollection(TEST_AC) != null) { fail("Should not be able to obtain active collection from manager"); } } @Test public void testUnregisterACSWithDerived() { ActiveCollectionManager mgr=new AbstractActiveCollectionManager() {}; ActiveCollectionSource acs=new ActiveCollectionSource(); acs.setName(TEST_AC); ActiveCollectionSource.DerivedDefinition dd=new ActiveCollectionSource.DerivedDefinition(); dd.setName(DERIVED_AC); acs.getDerived().add(dd); try { mgr.register(acs); } catch (Exception e) { fail("Failed to register active collection source: "+e); } if (mgr.getActiveCollection(TEST_AC) == null) { fail("Unable to obtain active collection from manager"); } if (mgr.getActiveCollection(DERIVED_AC) == null) { fail("Unable to obtain derived active collection from manager"); } try { mgr.unregister(acs); } catch (Exception e) { fail("Failed to unregister active collection source: "+e); } if (mgr.getActiveCollection(TEST_AC) != null) { fail("Should not be able to obtain active collection from manager"); } if (mgr.getActiveCollection(DERIVED_AC) != null) { fail("Should not be able to obtain derived active collection from manager"); } } @Test public void testAlreadyUnregisteredACS() { ActiveCollectionManager mgr=new AbstractActiveCollectionManager() {}; ActiveCollectionSource acs=new ActiveCollectionSource(); acs.setName(TEST_AC); try { mgr.register(acs); } catch (Exception e) { fail("Failed to register active collection source: "+e); } try { mgr.unregister(acs); } catch (Exception e) { fail("Failed to unregister active collection source: "+e); } try { mgr.unregister(acs); fail("Should have thrown exception as already unregistered"); } catch (Exception e) { // Ignore } } @Test public void testCreateAndRemoveDerivedCollection() { ActiveCollectionManager mgr=new AbstractActiveCollectionManager() {}; ActiveCollectionSource acs=new ActiveCollectionSource(); acs.setName(TEST_AC); try { mgr.register(acs); } catch (Exception e) { fail("Failed to register active collection source: "+e); } ActiveCollection parent=mgr.getActiveCollection(TEST_AC); if (parent == null) { fail("Failed to get parent collection"); } Predicate predicate=new Predicate() { public boolean evaluate(ActiveCollectionContext context, Object item) { return true; } }; mgr.create(DERIVED_AC, parent, predicate, null); if (mgr.getActiveCollection(DERIVED_AC) == null) { fail("Failed to retrieve derived ac"); } mgr.remove(DERIVED_AC); if (mgr.getActiveCollection(DERIVED_AC) != null) { fail("Derived ac should no longer exist"); } } @Test public void testRegisterACSWithHighWaterMark() { AbstractActiveCollectionManager mgr=new AbstractActiveCollectionManager() {}; ActiveCollectionSource acs=new ActiveCollectionSource(); acs.setName(TEST_AC); acs.setHighWaterMark(10); try { mgr.register(acs); } catch (Exception e) { fail("Failed to register active collection source: "+e); } // Check that the active collection for this source has been created if (acs.getActiveCollection() == null) { fail("Active collection on source has not been set"); } ActiveCollection ac=mgr.getActiveCollection(TEST_AC); if (ac == null) { fail("Unable to obtain active collection from manager"); } if (ac.getHighWaterMarkWarningIssued()) { fail("Warning should not have been issued yet"); } for (int i=0; i < 12; i++) { ac.doInsert(null, new String("Object "+i)); } mgr.cleanup(); if (!ac.getHighWaterMarkWarningIssued()) { fail("Warning should have been issued"); } ac.doRemove(0, null); ac.doRemove(0, null); ac.doRemove(0, null); // Perform cleanup again - which should cause the warning flag to be removed mgr.cleanup(); if (ac.getHighWaterMarkWarningIssued()) { fail("Warning should no longer have be issued"); } } @Test public void testActiveCollectionUnregisteredBeforeSource() { ActiveCollectionSource acs=new ActiveCollectionSource(); ActiveList list=new ActiveList("Test"); list.addActiveChangeListener(new ActiveChangeListener() { public void inserted(Object key, Object value) { } public void updated(Object key, Object value) { } public void removed(Object key, Object value) { } }); acs.setActiveCollection(list); TestActiveCollectionListener l=new TestActiveCollectionListener(); l.setCheckListenerRegistered(true); AbstractActiveCollectionManager mgr=new AbstractActiveCollectionManager() {}; mgr.addActiveCollectionListener(l); try { // Required to register the source with the manager mgr.register(acs); // Need to overwrite the active collection with one that has a listener acs.setActiveCollection(list); mgr.unregister(acs); } catch (Exception e) { fail("Failed to unregister: "+e); } } public class TestActiveCollectionListener implements ActiveCollectionListener { protected java.util.List<ActiveCollection> _registered=new java.util.ArrayList<ActiveCollection>(); protected java.util.List<ActiveCollection> _unregistered=new java.util.ArrayList<ActiveCollection>(); protected boolean _checkListenerRegistered=false; public void setCheckListenerRegistered(boolean b) { _checkListenerRegistered = b; } public void registered(ActiveCollection ac) { _registered.add(ac); } public void unregistered(ActiveCollection ac) { _unregistered.add(ac); if (_checkListenerRegistered && ac.getActiveChangeListeners().size() == 0) { fail("No active change listeners registered"); } } } }
package snd; import java.nio.ByteBuffer; import helper.Logger; public class SProtocol extends Protocol { static int id = 102; String msg; public SProtocol(String m) { msg = m; } @Override public RawData toRawData() { ByteBuffer bf = ByteBuffer.allocate(4+msg.length()); bf.putInt(id); bf.put(msg.getBytes()); return RawData.newRawData(bf); } @Override public void process() { Logger.log("I got msg from Server: [" + msg + "]"); } }
class InsertionSort{ private int[] data; public int[] sorting(int[] d){ data = d; int length = data.length; for(int i=1; i<length; i++){ int tmp = data[i]; for(int j=i; j<0; j--){ if(data[j-1] > tmp){ data[j] = data[j-1]; // keep scanning down the array till reaching the right position for tmp }else continue; // return to the outer loop data[j] = tmp; // set tmp in right position, where now data[j-1] is not greater than it } } return data; } }
package com.cloudera.CachingTest; import java.io.UnsupportedEncodingException; import org.apache.commons.codec.binary.Hex; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Person implements CachedObject { private final String firstName; private final String lastName; private String password; private final String email; private final int age; private final byte[] hash; public Person(String firstName, String lastName, int age, String email) throws NoSuchAlgorithmException, UnsupportedEncodingException { this.firstName = firstName; this.lastName = lastName; this.age = age; this.email = email; // Generate hash used for lookups MessageDigest digester = MessageDigest.getInstance("MD5"); this.hash = digester.digest((email).getBytes("UTF-8")); } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getEmail() { return email; } public int getAge() { return age; } public void setPassword(String password) throws UnsupportedEncodingException, NoSuchAlgorithmException { MessageDigest digester = MessageDigest.getInstance("MD5"); this.password = new String(Hex.encodeHex(digester.digest((password).getBytes("UTF-8")))); } public void setHashedPassword(String hash) { this.password = hash; } public String getPassword() { return this.password; } public boolean checkPassword(String password) throws UnsupportedEncodingException, NoSuchAlgorithmException { MessageDigest digester = MessageDigest.getInstance("MD5"); String challenger = new String(Hex.encodeHex(digester.digest((password).getBytes("UTF-8")))); return this.password.equals(challenger); } public String getKey() { return new String(Hex.encodeHex(hash)); } public static String getKey(String email) throws NoSuchAlgorithmException, UnsupportedEncodingException { return new Person(null, null, 0, email).getKey(); } }
/* Generated SBE (Simple Binary Encoding) message codec */ package sbe.msg.marketData; import uk.co.real_logic.sbe.codec.java.CodecUtil; import uk.co.real_logic.agrona.DirectBuffer; @SuppressWarnings("all") public class BestBidOfferDecoder { public static final int BLOCK_LENGTH = 29; public static final int TEMPLATE_ID = 26; public static final int SCHEMA_ID = 1; public static final int SCHEMA_VERSION = 0; private final BestBidOfferDecoder parentMessage = this; private DirectBuffer buffer; protected int offset; protected int limit; protected int actingBlockLength; protected int actingVersion; public int sbeBlockLength() { return BLOCK_LENGTH; } public int sbeTemplateId() { return TEMPLATE_ID; } public int sbeSchemaId() { return SCHEMA_ID; } public int sbeSchemaVersion() { return SCHEMA_VERSION; } public String sbeSemanticType() { return ""; } public int offset() { return offset; } public BestBidOfferDecoder wrap( final DirectBuffer buffer, final int offset, final int actingBlockLength, final int actingVersion) { this.buffer = buffer; this.offset = offset; this.actingBlockLength = actingBlockLength; this.actingVersion = actingVersion; limit(offset + actingBlockLength); return this; } public int encodedLength() { return limit - offset; } public int limit() { return limit; } public void limit(final int limit) { buffer.checkLimit(limit); this.limit = limit; } public static int messageTypeId() { return 1; } public static String messageTypeMetaAttribute(final MetaAttribute metaAttribute) { switch (metaAttribute) { case EPOCH: return "unix"; case TIME_UNIT: return "nanosecond"; case SEMANTIC_TYPE: return ""; } return ""; } public MessageTypeEnum messageType() { return MessageTypeEnum.get(CodecUtil.charGet(buffer, offset + 0)); } public static int instrumentIdId() { return 2; } public static String instrumentIdMetaAttribute(final MetaAttribute metaAttribute) { switch (metaAttribute) { case EPOCH: return "unix"; case TIME_UNIT: return "nanosecond"; case SEMANTIC_TYPE: return ""; } return ""; } public static long instrumentIdNullValue() { return 4294967294L; } public static long instrumentIdMinValue() { return 0L; } public static long instrumentIdMaxValue() { return 4294967293L; } public long instrumentId() { return CodecUtil.uint32Get(buffer, offset + 1, java.nio.ByteOrder.LITTLE_ENDIAN); } public static int bidId() { return 3; } public static String bidMetaAttribute(final MetaAttribute metaAttribute) { switch (metaAttribute) { case EPOCH: return "unix"; case TIME_UNIT: return "nanosecond"; case SEMANTIC_TYPE: return ""; } return ""; } private final PriceDecoder bid = new PriceDecoder(); public PriceDecoder bid() { bid.wrap(buffer, offset + 5); return bid; } public static int bidQuantityId() { return 4; } public static String bidQuantityMetaAttribute(final MetaAttribute metaAttribute) { switch (metaAttribute) { case EPOCH: return "unix"; case TIME_UNIT: return "nanosecond"; case SEMANTIC_TYPE: return ""; } return ""; } public static long bidQuantityNullValue() { return 4294967294L; } public static long bidQuantityMinValue() { return 0L; } public static long bidQuantityMaxValue() { return 4294967293L; } public long bidQuantity() { return CodecUtil.uint32Get(buffer, offset + 13, java.nio.ByteOrder.LITTLE_ENDIAN); } public static int offerId() { return 5; } public static String offerMetaAttribute(final MetaAttribute metaAttribute) { switch (metaAttribute) { case EPOCH: return "unix"; case TIME_UNIT: return "nanosecond"; case SEMANTIC_TYPE: return ""; } return ""; } private final PriceDecoder offer = new PriceDecoder(); public PriceDecoder offer() { offer.wrap(buffer, offset + 17); return offer; } public static int offerQuantityId() { return 6; } public static String offerQuantityMetaAttribute(final MetaAttribute metaAttribute) { switch (metaAttribute) { case EPOCH: return "unix"; case TIME_UNIT: return "nanosecond"; case SEMANTIC_TYPE: return ""; } return ""; } public static long offerQuantityNullValue() { return 4294967294L; } public static long offerQuantityMinValue() { return 0L; } public static long offerQuantityMaxValue() { return 4294967293L; } public long offerQuantity() { return CodecUtil.uint32Get(buffer, offset + 25, java.nio.ByteOrder.LITTLE_ENDIAN); } }
package com.project.hadar.AcadeMovie.Activity; import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AlertDialog; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.project.hadar.AcadeMovie.R; import com.project.hadar.AcadeMovie.Model.GifPlayer; import com.project.hadar.AcadeMovie.Model.DetailsValidation; import com.project.hadar.AcadeMovie.Model.UserDetails; import com.project.hadar.AcadeMovie.Analytics.*; import com.facebook.AccessToken; import com.facebook.AccessTokenTracker; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.Profile; import com.facebook.login.LoginResult; import com.facebook.login.widget.LoginButton; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.common.SignInButton; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FacebookAuthProvider; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GoogleAuthProvider; import com.google.firebase.auth.UserInfo; import com.google.firebase.auth.UserProfileChangeRequest; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.firebase.remoteconfig.FirebaseRemoteConfig; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; public class SignInActivity extends Activity { private static final String TAG = "SignInActivity"; private static final String GOOGLE_URL_PATH_TO_REMOVE = "s96-c/photo.jpg"; private static final String GOOGLE_URL_PATH_TO_ADD = "s400-c/photo.jpg"; private String m_sourceActivity = null; private static int GOOGLE_SIGN_IN = 100; private FirebaseAuth m_firebaseAuth; private FirebaseAuth.AuthStateListener m_AuthListener; private EditText m_userEmailEditText; private EditText m_userPasswordEditText; private CallbackManager m_callbackManager; private GoogleSignInClient m_googleSignInClient; private SignInButton m_googleSignInButton; private UserDetails m_userDetails; private GoogleSignInAccount m_googleSignInAccount; private FirebaseUser m_firebaseUser = null; private FirebaseRemoteConfig m_FirebaseRemoteConfig; private LoginButton m_facebookLoginButton; private String m_loginMethod; private AnalyticsManager m_analyticsManager = AnalyticsManager.getInstance(); @Override protected void onCreate(Bundle i_savedInstanceState) { Log.e(TAG, "onCreate() >>"); super.onCreate(i_savedInstanceState); setContentView(R.layout.activity_main); GifPlayer.stopGif(); m_sourceActivity = getIntent().getStringExtra("Source Activity"); m_firebaseAuth = FirebaseAuth.getInstance(); m_FirebaseRemoteConfig = FirebaseRemoteConfig.getInstance(); findViews(); facebookLoginInit(); googleSignInInit(); firebaseAuthenticationInit(); Log.e(TAG, "onCreate() <<"); } @Override protected void onStart() { Log.e(TAG, "onStart() >>"); super.onStart(); m_firebaseAuth.addAuthStateListener(m_AuthListener); Log.e(TAG, "onStart() <<"); } @Override protected void onStop() { Log.e(TAG, "onStop() >>"); super.onStop(); if (m_AuthListener != null) { m_firebaseAuth.removeAuthStateListener(m_AuthListener); } Log.e(TAG, "onStop() <<"); } public static void setUserEmailToFacebookUser(UserDetails i_userDetails, FirebaseUser i_firebaseUser) { Log.e(TAG, "setUserEmailToFacebookUser() >>"); for (UserInfo userInfo: i_firebaseUser.getProviderData()) { if(userInfo.getProviderId().equals("facebook.com")) { i_userDetails.setUserEmail(userInfo.getEmail()); } } Log.e(TAG, "setUserEmailToFacebookUser() <<"); } public static void changeUserDetailsPictureUrlForFacebook(UserDetails i_userDetails) { Log.e(TAG, "changeUserDetailsPictureUrlForFacebook() >>"); Profile facebookProfile = Profile.getCurrentProfile(); if(facebookProfile != null) { String newPicturePath = facebookProfile.getProfilePictureUri(500, 500).toString(); i_userDetails.setUserPictureUrl(newPicturePath); } Log.e(TAG, "changeUserDetailsPictureUrlForFacebook() <<"); } public static void changeUserDetailsPictureUrlForGoogle(UserDetails i_userDetails) { Log.e(TAG, "changeUserDetailsPictureUrlForGoogle() >>"); String userDetailsPictureUrl = i_userDetails.getUserPictureUrl(); if(userDetailsPictureUrl != null) { String newPicturePath = userDetailsPictureUrl.replace(GOOGLE_URL_PATH_TO_REMOVE, GOOGLE_URL_PATH_TO_ADD); i_userDetails.setUserPictureUrl(newPicturePath); } Log.e(TAG, "changeUserDetailsPictureUrlForGoogle() <<"); } @Override public void onBackPressed() { Log.e(TAG, "onBackPressed() >>"); if(("AskForSignInActivity").equals(m_sourceActivity)) { goBackToAskForSignInActivity(); } else { showExitAppDialog(); } Log.e(TAG, "onBackPressed() <<"); } private void goBackToAskForSignInActivity() { Log.e(TAG, "goBackToAskForSignInActivity() >>"); super.onBackPressed(); finish(); Log.e(TAG, "goBackToAskForSignInActivity() <<"); } private void showExitAppDialog() { Log.e(TAG, "showExitAppDialog() >>"); new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert) .setTitle("Exit App") .setMessage("Are you sure you want to exit?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface i_dialogInterface, int i_num) { Intent exitIntent = new Intent(Intent.ACTION_MAIN); exitIntent.addCategory(Intent.CATEGORY_HOME); exitIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(exitIntent); finishAffinity(); } }) .setNegativeButton("No", null) .show(); Log.e(TAG, "showExitAppDialog() <<"); } @Override public void onActivityResult(int i_requestCode, int i_resultCode, Intent i_dataIntent) { Log.e(TAG, "onActivityResult() >>"); super.onActivityResult(i_requestCode, i_resultCode, i_dataIntent); m_callbackManager.onActivityResult(i_requestCode, i_resultCode, i_dataIntent); if (i_requestCode == GOOGLE_SIGN_IN) { Task<GoogleSignInAccount> googleSignInTask = GoogleSignIn.getSignedInAccountFromIntent(i_dataIntent); handleGoogleSignInResult(googleSignInTask); } Log.e(TAG, "onActivityResult() <<"); } @SuppressWarnings("ConstantConditions") public void onSignInClick(View i_view) { Log.e(TAG, "onSignInClick() >>"); DetailsValidation detailsValidation = new DetailsValidation(); try { detailsValidation.verifyEmail(m_userEmailEditText.getText().toString()); detailsValidation.verifyPassword(m_userPasswordEditText.getText().toString()); String email = m_userEmailEditText.getText().toString(); String pass = m_userPasswordEditText.getText().toString(); //Email / Password sign-in Task<AuthResult> authResult = m_firebaseAuth.signInWithEmailAndPassword(email, pass); authResult.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> i_completedTask) { Log.e(TAG, "Email/Pass Auth: onComplete() >> " + i_completedTask.isSuccessful()); if (i_completedTask.isSuccessful()) { if (m_firebaseAuth.getCurrentUser().isEmailVerified()) { //checkAndUploadUserImageToStorage(m_firebaseAuth.getCurrentUser().getPhotoUrl(), m_firebaseAuth.getCurrentUser().getEmail()); Log.e(TAG, "calling updateUI 5"); handleAllSignInSuccess("EmailPassword"); } else { showWaitingForEmailVerificationDialog(); m_firebaseAuth.signOut(); } } else { Toast.makeText(SignInActivity.this, i_completedTask.getException().getMessage(), Toast.LENGTH_LONG).show(); } Log.e(TAG, "Email/Pass Auth: onComplete() <<"); } }); } catch (Exception exception) { Log.e(TAG, "emailAndPasswordValidation"+ exception.getMessage()); Toast.makeText(this, exception.getMessage(), Toast.LENGTH_LONG).show(); } Log.e(TAG, "onSignInClick() <<"); } @SuppressWarnings("ConstantConditions") public void OnForgotPasswordClick(View i_view) { Log.e(TAG, "OnForgotPasswordClick() >> "); String emailStr = m_userEmailEditText.getText().toString(); if(emailStr.isEmpty()) { Toast.makeText(SignInActivity.this, "Please type an email address in order to reset your password.", Toast.LENGTH_LONG).show(); } else { m_firebaseAuth.sendPasswordResetEmail(emailStr) .addOnCompleteListener(this, new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> i_completedTask) { Log.e(TAG, "OnForgotPasswordClick: onComplete() >> " + i_completedTask.isSuccessful()); if (i_completedTask.isSuccessful()) { showPasswordResetWasSentDialog(); } else { Toast.makeText(SignInActivity.this, i_completedTask.getException().getMessage(), Toast.LENGTH_LONG).show(); } Log.e(TAG, "OnForgotPasswordClick: onComplete() << " + i_completedTask.isSuccessful()); } }); } Log.e(TAG, "OnForgotPasswordClick() << "); } public void onSignInAnonymouslyClick(View i_view) { Log.e(TAG, "onSignInAnonymouslyClick() >>"); GifPlayer.setAnonymousSignIn(true); GifPlayer.playGif(); long cacheExpiration = 0; m_FirebaseRemoteConfig.fetch(cacheExpiration) .addOnCompleteListener(this, new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { m_FirebaseRemoteConfig.activateFetched(); if (m_FirebaseRemoteConfig.getBoolean("allow_anonymous_user")) { signInAnonymously(); } else { Toast.makeText(SignInActivity.this, "Anonymous sign in is not allowed right now.", Toast.LENGTH_LONG).show(); GifPlayer.stopGif(); } } else { Log.e(TAG, "Fetch Failed", task.getException()); Toast.makeText(SignInActivity.this, "Fetch Failed", Toast.LENGTH_LONG).show(); GifPlayer.stopGif(); } } }); Log.e(TAG, "onSignInAnonymouslyClick() <<"); } public void onSignUpClick(View i_view) { Log.e(TAG, "onSignUpClick() >>"); Intent regIntent = new Intent(getApplicationContext(), RegistrationActivity.class); regIntent.putExtra("Email", m_userEmailEditText.getText().toString()); regIntent.putExtra("MAIN_CALL", true); startActivity(regIntent); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); finish(); Log.e(TAG, "onSignUpClick() <<"); } private void findViews() { Log.e(TAG, "findViews() >>"); GifPlayer.s_LoadingBar =findViewById(R.id.load_bar); m_userEmailEditText = findViewById(R.id.editTextEmail); m_userPasswordEditText = findViewById(R.id.editTextPassword); m_googleSignInButton = findViewById(R.id.google_sign_in_button); m_facebookLoginButton = findViewById(R.id.buttonFacebook); TextView signInAnonymous = findViewById(R.id.textViewSignUpAnonymously); checkAndHideSkipTextView(signInAnonymous); Log.e(TAG, "findViews() <<"); } private void checkAndHideSkipTextView(final TextView i_signInAnonymous) { FirebaseRemoteConfig.getInstance().fetch(0); FirebaseRemoteConfig.getInstance().activateFetched(); String anonymousStatus = FirebaseRemoteConfig.getInstance().getString("allow_anonymous_user"); if(anonymousStatus.equals("false")) { i_signInAnonymous.setClickable(false); i_signInAnonymous.setVisibility(TextView.GONE); } } private void googleSignInInit() { Log.e(TAG, "googleSignInInit() >>"); GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestProfile() .requestEmail() .build(); m_googleSignInClient = GoogleSignIn.getClient(this, gso); m_googleSignInButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View i_view) { GifPlayer.setGoogleSignIn(true); GifPlayer.playGif(); onClickGoogleButton(); } }); Log.e(TAG, "googleSignInInit() <<"); } private void onClickGoogleButton() { Log.e(TAG, "onClickGoogleButton() >>"); Intent signInIntent = m_googleSignInClient.getSignInIntent(); GifPlayer.playGif(); startActivityForResult(signInIntent, GOOGLE_SIGN_IN); Log.e(TAG, "onClickGoogleButton() <<"); } private void handleGoogleSignInResult(Task<GoogleSignInAccount> i_completedTask) { Log.e(TAG, "handleSignInResult() >>"); try { m_googleSignInAccount = i_completedTask.getResult(ApiException.class); Log.e(TAG, "firebase <= google"); firebaseAuthWithGoogle(m_googleSignInAccount); } catch (ApiException e) { GifPlayer.stopGif(); Log.e(TAG, "unsuccessful sign in to google"); } Log.e(TAG, "handleSignInResult() <<"); } @SuppressWarnings("ConstantConditions") private void firebaseAuthWithGoogle(final GoogleSignInAccount i_googleSignInAccount) { Log.e(TAG, "firebaseAuthWithGoogle() >>, id = " + i_googleSignInAccount.getId()); AuthCredential credential = GoogleAuthProvider.getCredential(i_googleSignInAccount.getIdToken(), null); m_firebaseAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> i_completedTask) { if (i_completedTask.isSuccessful()) { Log.e(TAG, "calling updateUI 2 " + m_firebaseAuth.getCurrentUser().getEmail()); Toast.makeText(SignInActivity.this, "Google sign in success!", Toast.LENGTH_SHORT).show(); handleAllSignInSuccess("Google"); } else { Toast.makeText(SignInActivity.this, "Google sign in error :(", Toast.LENGTH_SHORT).show(); } } }); Log.e(TAG, "firebaseAuthWithGoogle() <<"); } private void updateUIAndMoveToCinemaMainActivity() { Log.e(TAG, "updateUIAndMoveToCinemaMainActivity() >>"); DatabaseReference userRef = FirebaseDatabase.getInstance().getReference("Users") .child(FirebaseAuth.getInstance().getCurrentUser().getUid()); userRef.child("userEmail").setValue(m_userDetails.getUserEmail()); userRef.child("userName").setValue(m_userDetails.getUserName()); if(m_firebaseUser != null) { Intent CinemaMainIntent = new Intent(getApplicationContext(), CinemaMainActivity.class); GifPlayer.stopGif(); startActivity(CinemaMainIntent); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); finish(); } Log.e(TAG, "updateUIAndMoveToCinemaMainActivity() <<"); } private void checkAndUploadUserImageToStorage(final Uri i_internalPhotoUri, String i_email) { Log.e(TAG,"checkAndUploadUserImageToStorage >>"); FirebaseStorage firebaseStorage = FirebaseStorage.getInstance(); StorageReference storageReferenceProfilePic = firebaseStorage.getReference(); final StorageReference storageImageRef = storageReferenceProfilePic.child("Users Profile Picture/"+ i_email + ".jpg"); storageImageRef.getDownloadUrl() .addOnFailureListener(new OnFailureListener() { //Image is not in storage, uploading it. @Override public void onFailure(@NonNull Exception e) { Log.e(TAG,"==> Image search failed, uploaded a new image"); uploadImageToStorage(storageImageRef, i_internalPhotoUri); } }); Log.e(TAG,"checkAndUploadUserImageToStorage <<"); } @SuppressWarnings("ConstantConditions") private void uploadImageToStorage(StorageReference i_storageImageRef, Uri i_internalPhotoUri) { Log.e(TAG,"uploadImageToStorage >>"); final DatabaseReference userRef = FirebaseDatabase.getInstance().getReference("Users"); i_storageImageRef.putFile(i_internalPhotoUri) .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { String storagePhotoURL = taskSnapshot.getDownloadUrl().toString(); m_userDetails.setUserPictureUrl(storagePhotoURL); userRef.child(m_firebaseUser.getUid()).child("userPictureUrl").setValue(storagePhotoURL); Log.e(TAG,"Upload image success"); //Toast.makeText(SignInActivity.this, "Upload User Image Succsses",Toast.LENGTH_LONG).show(); } }); Log.e(TAG,"uploadImageToStorage <<"); } private void handleAllSignInSuccess(String i_loginMethod) { Log.e(TAG,"handleAllSignInSuccess >>"); m_loginMethod = i_loginMethod; m_firebaseUser = m_firebaseAuth.getCurrentUser(); ifNewUserAddToDBAndUpdateUI(); Log.e(TAG,"handleAllSignInSuccess <<"); } @SuppressWarnings("ConstantConditions") private void overrideUserDetailsInformation(String i_loginMethod) { Log.e(TAG,"overrideUserDetailsInformation >>"); switch (i_loginMethod) { case "Google": changeUserDetailsPictureUrlForGoogle(m_userDetails); m_userDetails.setUserEmail(m_googleSignInAccount.getEmail()); break; case "Facebook": changeUserDetailsPictureUrlForFacebook(m_userDetails); setUserEmailToFacebookUser(m_userDetails, m_firebaseUser); break; case "EmailPassword": checkAndUploadUserImageToStorage(m_firebaseAuth.getCurrentUser().getPhotoUrl(), m_firebaseAuth.getCurrentUser().getEmail()); break; } Log.e(TAG,"overrideUserDetailsInformation <<"); } @SuppressWarnings("ConstantConditions") private void ifNewUserAddToDBAndUpdateUI() { Log.e(TAG,"ifNewUserAddToDBAndUpdateUI >>"); m_userDetails = new UserDetails(m_firebaseUser); overrideUserDetailsInformation(m_loginMethod); analyticsSignUpEvent(); if(m_firebaseUser != null) { FirebaseDatabase.getInstance().getReference("Users") .child(FirebaseAuth.getInstance().getCurrentUser().getUid()) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { if (!snapshot.exists()) //user not exists in DB { DatabaseReference userRef = FirebaseDatabase.getInstance().getReference("Users"); userRef.child(m_firebaseUser.getUid()).setValue(m_userDetails); } updateUIAndMoveToCinemaMainActivity(); } @Override public void onCancelled(DatabaseError firebaseError) { } }); } Log.e(TAG,"ifNewUserAddToDBAndUpdateUI <<"); } private void facebookLoginInit() { Log.e(TAG, "facebookLoginInit() >>"); m_callbackManager = CallbackManager.Factory.create(); m_facebookLoginButton.setReadPermissions("email", "public_profile"); m_facebookLoginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View i_view) { GifPlayer.setFacebookSignIn(true); GifPlayer.playGif(); } }); m_facebookLoginButton.registerCallback(m_callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult i_loginResult) { Toast.makeText(SignInActivity.this, "Facebook sign in success!", Toast.LENGTH_SHORT).show(); handleFacebookAccessToken(i_loginResult.getAccessToken()); } @Override public void onCancel() { GifPlayer.stopGif(); Toast.makeText(SignInActivity.this, "Facebook sign in canceled", Toast.LENGTH_SHORT).show(); } @Override public void onError(FacebookException i_facebookException) { Toast.makeText(SignInActivity.this, "Facebook sign in error :(", Toast.LENGTH_SHORT).show(); } }); new AccessTokenTracker() { @Override protected void onCurrentAccessTokenChanged(AccessToken i_oldAccessToken, AccessToken i_currentAccessToken) { if (i_currentAccessToken == null) { m_firebaseAuth.signOut(); } Log.e(TAG, "onCurrentAccessTokenChanged() >> currentAccessToken=" + (i_currentAccessToken != null ? i_currentAccessToken.getToken() : "Null") + " ,oldAccessToken=" + (i_oldAccessToken != null ? i_oldAccessToken.getToken() : "Null")); } }; Log.e(TAG, "facebookLoginInit() <<"); } @SuppressWarnings("ConstantConditions") private void handleFacebookAccessToken(AccessToken i_accessToken) { Log.e(TAG, "handleFacebookAccessToken () >>" + i_accessToken.getToken()); AuthCredential credential = FacebookAuthProvider.getCredential(i_accessToken.getToken()); m_firebaseAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> i_completedTask) { Log.e(TAG, "Facebook: onComplete() >> " + i_completedTask.isSuccessful()); if (i_completedTask.isSuccessful()) { handleAllSignInSuccess("Facebook"); } else { GifPlayer.stopGif(); Log.e(TAG, "unsuccessful sign in to google"); Toast.makeText(SignInActivity.this, i_completedTask.getException().getMessage(), Toast.LENGTH_SHORT).show(); } Log.e(TAG, "Facebook: onComplete() <<"); } }); Log.e(TAG, "handleFacebookAccessToken () <<"); } private void firebaseAuthenticationInit() { Log.e(TAG, "firebaseAuthenticationInit() >>"); //Obtain reference to the current authentication m_firebaseAuth = FirebaseAuth.getInstance(); m_AuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth i_firebaseAuth) { } }; Log.e(TAG, "firebaseAuthenticationInit() <<"); } private void showWaitingForEmailVerificationDialog() { Log.e(TAG,"showWaitingForEmailVerificationDialog >>"); new AlertDialog.Builder(this) .setMessage("Waiting for email verification.\nPlease verify your account and sign in again.\n") .setCancelable(false) .setPositiveButton("OK", null) .show(); Log.e(TAG,"showWaitingForEmailVerificationDialog <<"); } private void showPasswordResetWasSentDialog() { Log.e(TAG,"showPasswordResetWasSentDialog >>"); new AlertDialog.Builder(this) .setMessage("A password reset request has been sent to:\n" + m_userEmailEditText.getText().toString()) .setCancelable(false) .setPositiveButton("OK", null) .show(); Log.e(TAG,"showPasswordResetWasSentDialog <<"); } private void signInAnonymously() { Log.e(TAG,"signInAnonymously >>"); m_firebaseAuth.signInAnonymously() .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { Log.d(TAG, "signInAnonymously: success"); updateProfile(); } else { Log.w(TAG, "signInAnonymously: failure", task.getException()); } } }); Log.e(TAG,"signInAnonymously <<"); } @SuppressWarnings("ConstantConditions") private void updateProfile() { Log.e(TAG,"updateProfile >>"); UserProfileChangeRequest updateProfile = new UserProfileChangeRequest.Builder() .setDisplayName("Anonymous") .build(); m_firebaseAuth.getCurrentUser().updateProfile(updateProfile) .addOnCompleteListener(this, new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> i_completedTask) { if(i_completedTask.isSuccessful()) { handleAllSignInSuccess("Anonymously"); } } }); Log.e(TAG,"updateProfile <<"); } private void analyticsSignUpEvent() { m_analyticsManager.trackSignupEvent(m_loginMethod); m_analyticsManager.setUserID(m_firebaseUser.getUid()); m_analyticsManager.setUserProperty(m_userDetails); } }
package OrientacaoObjetos; public class Player { //por ser uma classe apenas de funções, não é necessário um void main public void IniciarJogador() { System.out.println("Jogador Iniciado!"); } public static void main(String[]args) { System.out.println("Entrou no main Player"); } }
package net.crunchdroid.dao; import net.crunchdroid.model.Abonne; import net.crunchdroid.model.Abonnement; import net.crunchdroid.model.AbonnementFacture; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface AbonnementFactureDao extends JpaRepository<AbonnementFacture, Long> { List<AbonnementFacture> findAllByAbonne(Abonne abonne); AbonnementFacture findAllByAbonnement(Abonnement abonnement); }
package com.worker.framework.internalapi; import java.util.List; import com.worker.shared.WorkMessage; public interface Worker { public boolean supportsTask(String taskName); public List<WorkMessage> execute(WorkMessage input) throws Exception; }
package com.elvarg.world.model; import com.elvarg.world.entity.Entity; public class GroundItem extends Entity { public GroundItem(Item item, Position pos, String owner, boolean isGlobal, int showDelay, boolean goGlobal, int globalTimer) { super(pos); this.setItem(item); this.owner = owner; this.fromIP = ""; this.isGlobal = isGlobal; this.showDelay = showDelay; this.goGlobal = goGlobal; this.globalTimer = globalTimer; } public GroundItem(Item item, Position pos, String owner, String fromIP, boolean isGlobal, int showDelay, boolean goGlobal, int globalTimer) { super(pos); this.setItem(item); this.owner = owner; this.fromIP = fromIP; this.isGlobal = isGlobal; this.showDelay = showDelay; this.goGlobal = goGlobal; this.globalTimer = globalTimer; } private Item item; private String owner, fromIP; private boolean isGlobal; private int showDelay; private boolean goGlobal; private int globalTimer; private boolean hasBeenPickedUp; private boolean refreshNeeded; private boolean shouldProcess = true; public Item getItem() { return item; } public void setItem(Item item) { this.item = item; } public void setOwner(String owner) { this.owner = owner; } public String getOwner() { return this.owner; } public void setFromIP(String IP) { this.fromIP = IP; } public String getFromIP() { return this.fromIP; } public void setGlobalStatus(boolean l) { this.isGlobal = l; } public boolean isGlobal() { return this.isGlobal; } public void setShowDelay(int l) { this.showDelay = l; } public int getShowDelay() { return this.showDelay; } public void setGoGlobal(boolean l) { this.goGlobal = l; } public boolean shouldGoGlobal() { return this.goGlobal; } public void setGlobalTimer(int l) { this.globalTimer = l; } public int getGlobalTimer() { return this.globalTimer; } public void setPickedUp(boolean s) { this.hasBeenPickedUp = s; } public boolean hasBeenPickedUp() { return this.hasBeenPickedUp; } public void setRefreshNeeded(boolean s) { this.refreshNeeded = s; } public boolean isRefreshNeeded() { return this.refreshNeeded; } public boolean shouldProcess() { return shouldProcess; } public void setShouldProcess(boolean shouldProcess) { this.shouldProcess = shouldProcess; } }
package com.podarbetweenus.Activities; import android.app.Activity; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.podarbetweenus.BetweenUsConstant.Constant; import com.podarbetweenus.Entity.LoginDetails; import com.podarbetweenus.R; import com.podarbetweenus.Services.DataFetchService; import org.json.JSONObject; /** * Created by Administrator on 9/25/2015. */ public class ForgotPasswordActivity extends Activity implements View.OnClickListener { //UI Variables //Button Button btn_submit; //Linear Layout LinearLayout lay_back_investment; //Edit Text EditText ed_mobile_no,ed_emailid; //ProgressDialog ProgressDialog progressDialog; //TextView TextView tv_error_msg; //LayoutEntities HeaderControler header; DataFetchService dft; LoginDetails login_details; String mobile_number,email_id,type; String ForgotPassword_Method_Name = "ForgotPassword"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.forgot_password); findViews(); init(); } private void init() { btn_submit.setOnClickListener(this); lay_back_investment.setOnClickListener(this); header = new HeaderControler(this,true,false,"Forgot Password"); dft = new DataFetchService(this); login_details = new LoginDetails(); progressDialog = Constant.getProgressDialog(this); } private void findViews() { //Button btn_submit = (Button) findViewById(R.id.btn_submit); //Linear Layout lay_back_investment = (LinearLayout) findViewById(R.id.lay_back_investment); //Edit Text ed_mobile_no = (EditText) findViewById(R.id.ed_mobile_no); ed_emailid = (EditText) findViewById(R.id.ed_emailid); //TextView tv_error_msg = (TextView) findViewById(R.id.tv_error_msg); } @Override public void onClick(View v) { if(v==btn_submit) { tv_error_msg.setVisibility(View.GONE); forgotPassword(); } else if(v==lay_back_investment) { finish(); } } private void forgotPassword() { mobile_number = ed_mobile_no.getText().toString(); email_id = ed_emailid.getText().toString(); if(mobile_number.equalsIgnoreCase("") && email_id.equalsIgnoreCase("")) { tv_error_msg.setVisibility(View.VISIBLE); tv_error_msg.setText("Please Enter Either Mobile Number or Email Id"); } else if(mobile_number.matches("[0-9]+")){ type = "M"; tv_error_msg.setVisibility(View.GONE); callWebserviceGetForgotPassword(mobile_number, type); } else { type = "E"; callWebserviceGetForgotPassword(email_id, type); } } private void callWebserviceGetForgotPassword(String credential, String type) { if(dft.isInternetOn()==true) { if (!progressDialog.isShowing()) { progressDialog.show(); } } else{ progressDialog.dismiss(); } dft.forgotPassword(credential, type, ForgotPassword_Method_Name, Request.Method.POST, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { if (progressDialog.isShowing()) { progressDialog.dismiss(); } try { login_details = (LoginDetails) dft.GetResponseObject(response, LoginDetails.class); if (login_details.Status.equalsIgnoreCase("1")) { Constant.showOkPopup(ForgotPasswordActivity.this, login_details.StatusMsg, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent i = new Intent(ForgotPasswordActivity.this, LoginActivity.class); startActivity(i); dialog.dismiss(); } }); } else{ Constant.showOkPopup(ForgotPasswordActivity.this, login_details.StatusMsg, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); tv_error_msg.setVisibility(View.VISIBLE); tv_error_msg.setText(login_details.StatusMsg); } } catch (Exception e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //Show error or whatever... Log.d("ForgotPasswordActivity", "ERROR.._---" + error.getCause()); } }); } @Override public void onBackPressed() { // TODO Auto-generated method stub //super.onBackPressed(); finish(); } }
package com.example.ahmed.octopusmart.Model.ServiceModels.Home; import com.example.ahmed.octopusmart.Model.ServiceModels.ProductModel; import java.io.Serializable; import java.util.ArrayList; /** * Created by sotra on 12/19/2017. */ public class HomeSortingProducts extends HomeBase implements Serializable{ ArrayList<ProductModel> data ; public ArrayList<ProductModel> getData() { return data; } public void setData(ArrayList<ProductModel> data) { this.data = data; } }
package com.mycompany.app; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Map; import org.apache.storm.spout.SpoutOutputCollector; import org.apache.storm.task.TopologyContext; import org.apache.storm.topology.OutputFieldsDeclarer; import org.apache.storm.topology.base.BaseRichSpout; import org.apache.storm.tuple.Fields; import org.apache.storm.tuple.Values; import org.apache.storm.utils.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ReadFile extends BaseRichSpout { private static final long serialVersionUID = 1L; private static final Logger LOG = LoggerFactory.getLogger(ReadFile.class); SpoutOutputCollector collector; private FileReader fileReader; BufferedReader br; private String fileName = "/home/ubuntu/StormData.txt"; private boolean completed = false; public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) { try { fileReader = new FileReader(fileName); br = new BufferedReader(fileReader); } catch (FileNotFoundException e) { e.printStackTrace(); } this.collector = collector; WordCountTopology.emitCounter = context.registerCounter("emitCounter"); WordCountTopology.ackCounter = context.registerCounter("ackCounter"); } public void nextTuple() { if (completed) { Utils.sleep(300000); return; } String line; try { if ((line = br.readLine()) != null) { LOG.debug("Emitting tuple: {}", line); this.collector.emit(new Values(line)); WordCountTopology.emitCounter.inc(); } else { System.out.print("complete!--------------------"); completed = true; } } catch (IOException e) { e.printStackTrace(); } } public void ack(Object id) { } public void fail(Object id) { } public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("sentence")); } }
/** * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved. * * The contents of this file are subject to the terms of the Liferay Enterprise * Subscription License ("License"). You may not use this file except in * compliance with the License. You can obtain a copy of the License by * contacting Liferay, Inc. See the License for the specific language governing * permissions and limitations under the License, including but not limited to * distribution rights of the Software. * * * */ package com.everis.formacion.model; import com.liferay.portal.kernel.util.Validator; import com.liferay.portal.model.ModelWrapper; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * <p> * This class is a wrapper for {@link Fabricante}. * </p> * * @author dmartici * @see Fabricante * @generated */ public class FabricanteWrapper implements Fabricante, ModelWrapper<Fabricante> { public FabricanteWrapper(Fabricante fabricante) { _fabricante = fabricante; } @Override public Class<?> getModelClass() { return Fabricante.class; } @Override public String getModelClassName() { return Fabricante.class.getName(); } @Override public Map<String, Object> getModelAttributes() { Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put("fabricanteId", getFabricanteId()); attributes.put("companyId", getCompanyId()); attributes.put("groupId", getGroupId()); attributes.put("userId", getUserId()); attributes.put("nombre", getNombre()); attributes.put("email", getEmail()); attributes.put("web", getWeb()); attributes.put("telefono", getTelefono()); attributes.put("fechaAlta", getFechaAlta()); attributes.put("mailPersonaContacto", getMailPersonaContacto()); attributes.put("numeroEmpleados", getNumeroEmpleados()); return attributes; } @Override public void setModelAttributes(Map<String, Object> attributes) { Long fabricanteId = (Long)attributes.get("fabricanteId"); if (fabricanteId != null) { setFabricanteId(fabricanteId); } Long companyId = (Long)attributes.get("companyId"); if (companyId != null) { setCompanyId(companyId); } Long groupId = (Long)attributes.get("groupId"); if (groupId != null) { setGroupId(groupId); } Long userId = (Long)attributes.get("userId"); if (userId != null) { setUserId(userId); } String nombre = (String)attributes.get("nombre"); if (nombre != null) { setNombre(nombre); } String email = (String)attributes.get("email"); if (email != null) { setEmail(email); } String web = (String)attributes.get("web"); if (web != null) { setWeb(web); } String telefono = (String)attributes.get("telefono"); if (telefono != null) { setTelefono(telefono); } Date fechaAlta = (Date)attributes.get("fechaAlta"); if (fechaAlta != null) { setFechaAlta(fechaAlta); } String mailPersonaContacto = (String)attributes.get( "mailPersonaContacto"); if (mailPersonaContacto != null) { setMailPersonaContacto(mailPersonaContacto); } Long numeroEmpleados = (Long)attributes.get("numeroEmpleados"); if (numeroEmpleados != null) { setNumeroEmpleados(numeroEmpleados); } } /** * Returns the primary key of this fabricante. * * @return the primary key of this fabricante */ @Override public long getPrimaryKey() { return _fabricante.getPrimaryKey(); } /** * Sets the primary key of this fabricante. * * @param primaryKey the primary key of this fabricante */ @Override public void setPrimaryKey(long primaryKey) { _fabricante.setPrimaryKey(primaryKey); } /** * Returns the fabricante ID of this fabricante. * * @return the fabricante ID of this fabricante */ @Override public long getFabricanteId() { return _fabricante.getFabricanteId(); } /** * Sets the fabricante ID of this fabricante. * * @param fabricanteId the fabricante ID of this fabricante */ @Override public void setFabricanteId(long fabricanteId) { _fabricante.setFabricanteId(fabricanteId); } /** * Returns the company ID of this fabricante. * * @return the company ID of this fabricante */ @Override public long getCompanyId() { return _fabricante.getCompanyId(); } /** * Sets the company ID of this fabricante. * * @param companyId the company ID of this fabricante */ @Override public void setCompanyId(long companyId) { _fabricante.setCompanyId(companyId); } /** * Returns the group ID of this fabricante. * * @return the group ID of this fabricante */ @Override public long getGroupId() { return _fabricante.getGroupId(); } /** * Sets the group ID of this fabricante. * * @param groupId the group ID of this fabricante */ @Override public void setGroupId(long groupId) { _fabricante.setGroupId(groupId); } /** * Returns the user ID of this fabricante. * * @return the user ID of this fabricante */ @Override public long getUserId() { return _fabricante.getUserId(); } /** * Sets the user ID of this fabricante. * * @param userId the user ID of this fabricante */ @Override public void setUserId(long userId) { _fabricante.setUserId(userId); } /** * Returns the user uuid of this fabricante. * * @return the user uuid of this fabricante * @throws SystemException if a system exception occurred */ @Override public java.lang.String getUserUuid() throws com.liferay.portal.kernel.exception.SystemException { return _fabricante.getUserUuid(); } /** * Sets the user uuid of this fabricante. * * @param userUuid the user uuid of this fabricante */ @Override public void setUserUuid(java.lang.String userUuid) { _fabricante.setUserUuid(userUuid); } /** * Returns the nombre of this fabricante. * * @return the nombre of this fabricante */ @Override public java.lang.String getNombre() { return _fabricante.getNombre(); } /** * Sets the nombre of this fabricante. * * @param nombre the nombre of this fabricante */ @Override public void setNombre(java.lang.String nombre) { _fabricante.setNombre(nombre); } /** * Returns the email of this fabricante. * * @return the email of this fabricante */ @Override public java.lang.String getEmail() { return _fabricante.getEmail(); } /** * Sets the email of this fabricante. * * @param email the email of this fabricante */ @Override public void setEmail(java.lang.String email) { _fabricante.setEmail(email); } /** * Returns the web of this fabricante. * * @return the web of this fabricante */ @Override public java.lang.String getWeb() { return _fabricante.getWeb(); } /** * Sets the web of this fabricante. * * @param web the web of this fabricante */ @Override public void setWeb(java.lang.String web) { _fabricante.setWeb(web); } /** * Returns the telefono of this fabricante. * * @return the telefono of this fabricante */ @Override public java.lang.String getTelefono() { return _fabricante.getTelefono(); } /** * Sets the telefono of this fabricante. * * @param telefono the telefono of this fabricante */ @Override public void setTelefono(java.lang.String telefono) { _fabricante.setTelefono(telefono); } /** * Returns the fecha alta of this fabricante. * * @return the fecha alta of this fabricante */ @Override public java.util.Date getFechaAlta() { return _fabricante.getFechaAlta(); } /** * Sets the fecha alta of this fabricante. * * @param fechaAlta the fecha alta of this fabricante */ @Override public void setFechaAlta(java.util.Date fechaAlta) { _fabricante.setFechaAlta(fechaAlta); } /** * Returns the mail persona contacto of this fabricante. * * @return the mail persona contacto of this fabricante */ @Override public java.lang.String getMailPersonaContacto() { return _fabricante.getMailPersonaContacto(); } /** * Sets the mail persona contacto of this fabricante. * * @param mailPersonaContacto the mail persona contacto of this fabricante */ @Override public void setMailPersonaContacto(java.lang.String mailPersonaContacto) { _fabricante.setMailPersonaContacto(mailPersonaContacto); } /** * Returns the numero empleados of this fabricante. * * @return the numero empleados of this fabricante */ @Override public long getNumeroEmpleados() { return _fabricante.getNumeroEmpleados(); } /** * Sets the numero empleados of this fabricante. * * @param numeroEmpleados the numero empleados of this fabricante */ @Override public void setNumeroEmpleados(long numeroEmpleados) { _fabricante.setNumeroEmpleados(numeroEmpleados); } @Override public boolean isNew() { return _fabricante.isNew(); } @Override public void setNew(boolean n) { _fabricante.setNew(n); } @Override public boolean isCachedModel() { return _fabricante.isCachedModel(); } @Override public void setCachedModel(boolean cachedModel) { _fabricante.setCachedModel(cachedModel); } @Override public boolean isEscapedModel() { return _fabricante.isEscapedModel(); } @Override public java.io.Serializable getPrimaryKeyObj() { return _fabricante.getPrimaryKeyObj(); } @Override public void setPrimaryKeyObj(java.io.Serializable primaryKeyObj) { _fabricante.setPrimaryKeyObj(primaryKeyObj); } @Override public com.liferay.portlet.expando.model.ExpandoBridge getExpandoBridge() { return _fabricante.getExpandoBridge(); } @Override public void setExpandoBridgeAttributes( com.liferay.portal.model.BaseModel<?> baseModel) { _fabricante.setExpandoBridgeAttributes(baseModel); } @Override public void setExpandoBridgeAttributes( com.liferay.portlet.expando.model.ExpandoBridge expandoBridge) { _fabricante.setExpandoBridgeAttributes(expandoBridge); } @Override public void setExpandoBridgeAttributes( com.liferay.portal.service.ServiceContext serviceContext) { _fabricante.setExpandoBridgeAttributes(serviceContext); } @Override public java.lang.Object clone() { return new FabricanteWrapper((Fabricante)_fabricante.clone()); } @Override public int compareTo(com.everis.formacion.model.Fabricante fabricante) { return _fabricante.compareTo(fabricante); } @Override public int hashCode() { return _fabricante.hashCode(); } @Override public com.liferay.portal.model.CacheModel<com.everis.formacion.model.Fabricante> toCacheModel() { return _fabricante.toCacheModel(); } @Override public com.everis.formacion.model.Fabricante toEscapedModel() { return new FabricanteWrapper(_fabricante.toEscapedModel()); } @Override public com.everis.formacion.model.Fabricante toUnescapedModel() { return new FabricanteWrapper(_fabricante.toUnescapedModel()); } @Override public java.lang.String toString() { return _fabricante.toString(); } @Override public java.lang.String toXmlString() { return _fabricante.toXmlString(); } @Override public void persist() throws com.liferay.portal.kernel.exception.SystemException { _fabricante.persist(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof FabricanteWrapper)) { return false; } FabricanteWrapper fabricanteWrapper = (FabricanteWrapper)obj; if (Validator.equals(_fabricante, fabricanteWrapper._fabricante)) { return true; } return false; } /** * @deprecated As of 6.1.0, replaced by {@link #getWrappedModel} */ public Fabricante getWrappedFabricante() { return _fabricante; } @Override public Fabricante getWrappedModel() { return _fabricante; } @Override public void resetOriginalValues() { _fabricante.resetOriginalValues(); } private Fabricante _fabricante; }
package com.wallet.buddyWallet; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.wallet.buddyWallet.enitites.Account; import com.wallet.buddyWallet.enitites.Beneficiary; import com.wallet.buddyWallet.enitites.Mails; import com.wallet.buddyWallet.enitites.BuddyTransactions; import com.wallet.buddyWallet.exceptions.AccountBlockedException; import com.wallet.buddyWallet.exceptions.InsufficientBalanceException; import com.wallet.buddyWallet.exceptions.InvalidBeneficiaryException; import com.wallet.buddyWallet.exceptions.InvalidLoginCredentialsException; import com.wallet.buddyWallet.exceptions.InvalidTransactionPasswordException; import com.wallet.buddyWallet.exceptions.ResourceNotFoundException; import com.wallet.buddyWallet.exceptions.UnknownErrorException; import com.wallet.buddyWallet.exceptions.UserNameExistsException; import com.wallet.buddyWallet.service.WalletServiceImpl; @CrossOrigin("http://localhost:4200") @RestController @RequestMapping("/api") public class WalletController{ @Autowired WalletServiceImpl service; /* Method:getAllUsers * Type: GetMapping * Description: Called from admin page to view all the existing account details * @param: none * @return List<Account>: a List of all the existing accounts * @throws ResourceNotFoundException: It is raised when no data found */ @GetMapping("/getAllUsers") public List<Account> getAllUsers() throws ResourceNotFoundException { return service.getAllUsers(); } /* Method:login * Description: Called from login page to access one's account by logging in * Type: GetMapping * @param String: userName- user name of that account * @param String: password- password of that account * @return long: respective Account Number if credentials are correct so that it is possible for further references * @throws ResourceNotFoundException: It is raised when no data found * @throws InvalidLoginCredentialsException: It is raised when an user enters an incorrect user name or password * @throws AccountBlockedException: It is raised when an user account is blocked by admin and that user tries to login */ @GetMapping("/login/{userName}/{password}") public long login(@PathVariable String userName,@PathVariable String password) throws AccountBlockedException,ResourceNotFoundException,InvalidLoginCredentialsException { return service.login(userName, password); } /* Method:getAccountDetails * Type: GetMapping * Description: Used to know an account details using it's account number * @param long: Account number of the account about which details need to get * @return Account: an Account object containing all the details is returned * @throws ResourceNotFoundException: It is raised when no data found */ @GetMapping("/getAccountDetails/{accNum}") public Account getAccountDetails(@PathVariable long accNum) throws ResourceNotFoundException { return service.getAccountDetails(accNum); } /* Method:deposit * Type: PutMapping * Description: Called from deposit page to add money into wallet * @param long: Account number into which amount is to be added * @param String: Transaction Password to verify whether transaction done by correct user or not * @param double: Amount to be deposited * @return char[]: A message of 'amount successfully deposited' is returned if transaction successful * @throws ResourceNotFoundException: It is raised when no data found * @throws UnknownErrorException: It is raised when some unexpected error or exception occurs during the process * @throws InvalidTransactionPasswordException: It is raised when an user enters an incorrect Transaction Password */ @PutMapping("/deposit/{accNum}/{tranPassword}") public char[] deposit(@PathVariable long accNum,@PathVariable String tranPassword,@RequestBody double amount) throws ResourceNotFoundException,InvalidTransactionPasswordException,UnknownErrorException { return service.deposit(accNum,tranPassword,amount).toCharArray(); } /* Method:withdraw * Type:PutMapping * Description: Called from withdraw page to withdraw money from wallet * @param long: Account number from which amount is to be withdrawn * @param String: Transaction Password to verify whether transaction done by correct user or not * @param double: Amount to be withdrawn * @return char[]: A message of 'amount successfully withdrawn' is returned if transaction successful * @throws ResourceNotFoundException: It is raised when no data found * @throws UnknownErrorException: It is raised when some unexpected error or exception occurs during the process * @throws InvalidTransactionPasswordException: It is raised when an user enters an incorrect Transaction Password * @throws InsufficientBalanceException: It is raised when user tries to withdraw money more than existing balance in wallet */ @PutMapping("/withdraw/{accNum}/{tranPassword}") public char[] withdraw(@PathVariable long accNum,@PathVariable String tranPassword,@RequestBody double amount) throws ResourceNotFoundException,InsufficientBalanceException,InvalidTransactionPasswordException,UnknownErrorException { return service.withdraw(accNum,tranPassword,amount).toCharArray(); } /*Method:fundTransfer * Type: PutMapping * Description: Called from fundTransfer page to transfer money from one to another wallet * @param long: Account number from which amount is to be transferred * @param String: Transaction Password to verify whether transaction done by correct user or not * @param int: BeneficiaryId to get details about beneficiary * @param double: Amount to be withdrawn * @param char[]: Message- a description about why that transfer is made * @return String: A message of 'amount successfully transferred' is returned if transaction successful * @throws ResourceNotFoundException: It is raised when no data found * @throws UnknownErrorException: It is raised when some unexpected error or exception occurs during the process * @throws InvalidTransactionPasswordException: It is raised when an user enters an incorrect Transaction Password * @throws InsufficientBalanceException: It is raised when user tries to transfer money more than existing balance in wallet * @throws InvalidBeneficiaryException: It is raised when user tries to transfer money to an incorrect account Number or beneficiary */ @PutMapping("/fundTransfer/{accNum}/{tranPassword}/{beneficiaryId}/{amount}") public char[] fundTransfer(@PathVariable long accNum,@PathVariable String tranPassword,@PathVariable int beneficiaryId,@PathVariable double amount,@RequestBody String message) throws ResourceNotFoundException,InvalidTransactionPasswordException,InsufficientBalanceException,InvalidBeneficiaryException,UnknownErrorException { return service.fundTransfer(accNum,tranPassword, beneficiaryId, amount, message).toCharArray(); } /*Method:eStatement * Type: GetMapping * Description: Called from e-statement page to view the transaction history from that wallet * @param long: Account number about which transactions need to be returned * @return List<Transactions>: a List of all the transactions made from that wallet * @throws ResourceNotFoundException: It is raised when no data found */ @GetMapping("/eStatement/{accNum}") public List<BuddyTransactions> eStatement(@PathVariable long accNum) throws ResourceNotFoundException { return service.printTransactions(accNum); } /*Method:updateMyAccount * Type: PutMapping * Description: Used in editProfile page & admin-editAcnt page to update profile details * @param Account: an Account object containing all the new or changed details * @return boolean: boolean 'true' is returned if account is updated successfully else 'false' * @throws ResourceNotFoundException: It is raised when no data found */ @PutMapping("/updateMyAccount") public boolean updateMyAccount(@RequestBody Account updatedAccount) throws ResourceNotFoundException { return service.updateMyAccount(updatedAccount); } /* Method:signUp * Type: PostMapping * Description: Called from signup page to create a new account * @param Account: an Account object filled with new customer details * @return boolean: if account is added successfully, boolean 'true' is returned else false; * @throws ResourceNotFoundException: It is raised when no data found * @throws UnknownErrorException: It is raised when some unexpected error or exception occurs during the process * @throws UserNameExistsException: It is raised when an username exists and new customer wanna use the same */ @PostMapping("/signUp") public boolean signUp(@RequestBody Account acnt) throws UserNameExistsException,UnknownErrorException,ResourceNotFoundException { return service.createAccount(acnt); } /* Method:addBeneficiary * Type: PostMapping * Description: Called from addBenficiary page to link a new beneficiary to an account * @param Beneficiary: a Beneficiary Object containing all the details of new beneficiary * @return boolean: boolean 'true' is returned if beneficiary is added successfully else 'false'0 * @throws ResourceNotFoundException: It is raised when no data found * @throws UnknownErrorException: It is raised when some unexpected error or exception occurs during the process */ @PostMapping("/addBeneficiary/{accNum}") public boolean addBeneficiary(@PathVariable long accNum, @RequestBody Beneficiary beneficiary) throws ResourceNotFoundException,UnknownErrorException { return service.addBeneficiary(accNum, beneficiary); } /* Method:updateBeneficiary * Type: PostMapping * Description: Called from editBenficiary page to edit and update an existing beneficiary linked to that account * @param Beneficiary: a Beneficiary Object containing all the new or changed details of beneficiary * @return boolean: boolean 'true' is returned if beneficiary is updated successfully else 'false'0 * @throws ResourceNotFoundException: It is raised when no data found * @throws UnknownErrorException: It is raised when some unexpected error or exception occurs during the process */ @PutMapping("/updateBeneficiary/{accNum}/{index}") public boolean updateBeneficiary(@PathVariable long accNum,@PathVariable int index, @RequestBody Beneficiary beneficiary) throws ResourceNotFoundException,UnknownErrorException { return service.updateBeneficiary(accNum,index,beneficiary); } /* Method:getAllBeneficiaries * Type: GetMapping * Description: Called from manageBeneficiary page & fundTransfer page to view all the beneficiaries existing with that account * @param long: Account number of that account whose beneficiaries need to be viewed * @return List<Beneficiary>: a List of all beneficiaries linked to that account is returned * @throws ResourceNotFoundException: It is raised when no data found */ @GetMapping("/getAllBeneficiaries/{accNum}") public List<Beneficiary> getAllBeneficiaries(@PathVariable long accNum) throws ResourceNotFoundException { return service.getAllBeneficiaries(accNum); } /* Method:deleteBeneficiary * Type:DeleteMapping * Description: Called from manageBenficiary page to delete an existing beneficiary linked to that account * @param int: beneficiaryId which is to be deleted * @return boolean: boolean 'true' is returned if beneficiary is deleted successfully else 'false'0 * @throws ResourceNotFoundException: It is raised when no data found * @throws UnknownErrorException: It is raised when some unexpected error or exception occurs during the process */ @DeleteMapping("/deleteBeneficiary/{beneficiaryId}") public boolean deleteBeneficiary(@PathVariable int beneficiaryId) throws ResourceNotFoundException,UnknownErrorException{ return service.deleteBeneficiary(beneficiaryId); } /* Method:addMail * Type:PostMapping * Description: Used in feedback, contactUs and reportIssue pages to add a new feedback,mail or complaint * @param Mails: a Mails Object containing all the details of new feedback, mail or complaint * @return boolean: boolean 'true' is returned if mail,feedback or complaint is added successfully else 'false'0 * @throws UnknownErrorException: It is raised when some unexpected error or exception occurs during the process */ @PostMapping("/mails/add") public boolean addMail(@RequestBody Mails mail)throws UnknownErrorException { return service.addMail(mail); } /* Method:getAllMails * Type: GetMapping * Description: Used in admin_Mails page to view all the feedbacks, mails and complaints * @param: none * @return List<Mails>: a List of all the existing feedbacks, mails and complaints is returned * @throws ResourceNotFoundException: It is raised when no data found */ @GetMapping("mails/getAll") public List<Mails> getAllMails() throws ResourceNotFoundException{ return service.getAllMails(); } @GetMapping("verifyEmail/{email}") public int verifyEmail(@PathVariable String email) { return service.verifyEmail(email); } //This is for setting profile picture // @PostMapping("/uploadDp/accNum") // public MultipartFile uplaodImage(@RequestParam("imageFile") MultipartFile file, @PathVariable long accNum) throws IOException { // // byte[] img=file.getBytes(); // try // { // service.saveDp(accNum,img); // System.out.println("done"); // return file; // } // catch(Exception e) // { // e.printStackTrace(); // System.out.println("failed"); // return file; // } // } }
package com.csmugene.gridpagerview.view; import android.content.Context; import android.support.v4.app.FragmentManager; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.View; import com.csmugene.gridpagerview.listener.OnItemClickListener; import com.csmugene.gridpagerview.model.GridConfig; /** * Created by ichungseob on 2018. 8. 20.. */ public class GridViewPager extends ViewPager { private GridConfig mGridConfig; private FragmentManager mFragmentManager; private OnItemClickListener mOnItemClickListener; public GridViewPager(Context context) { super(context); } public GridViewPager(Context context, AttributeSet attrs) { super(context, attrs); } public void setGridConfig(GridConfig gridConfig){ mGridConfig = gridConfig; } public void setFragmentManager(FragmentManager fragmentManager){ mFragmentManager = fragmentManager; } public FragmentManager getFragmentManager(){ return mFragmentManager; } public GridConfig getGridConfig(){ return mGridConfig; } @Override public void addOnPageChangeListener(OnPageChangeListener onPageChangeListener){ super.addOnPageChangeListener(onPageChangeListener); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int height = 0; for(int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); int h = child.getMeasuredHeight(); if(h > height) { height = h; } } heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } public void setOnItemClickListener(OnItemClickListener onItemClickListener){ mOnItemClickListener = onItemClickListener; } public OnItemClickListener getOnItemClickListener(){ return mOnItemClickListener; } }
package virtualpetsamok; import static org.junit.Assert.assertEquals; import org.junit.Test; public class OrganicPetTest { @Test public void shouldGetHunger() { OrganicPet underTest = new OrganicPet("", "", 1, 1); int result = underTest.getHunger(); assertEquals(1, result); } @Test public void shouldGetThirst() { OrganicPet underTest = new OrganicPet("", "", 1, 1); int result = underTest.getThirst(); assertEquals(1, result); } @Test public void tickShouldIncreaseHunger() { OrganicPet underTest = new OrganicPet("", "", 1, 1); underTest.organicPetTick(); int result = underTest.getHunger(); assertEquals(11, result); } @Test public void tickShouldIncreaseThirst() { OrganicPet underTest = new OrganicPet("", "", 1, 1); underTest.organicPetTick(); int result = underTest.getThirst(); assertEquals(11, result); } @Test public void highHungerShouldDecreaseHealth() { OrganicPet underTest = new OrganicPet("", "", 100, 1); underTest.organicPetTick(); int result = underTest.getHealth(); assertEquals(90, result); } @Test public void highThirstShouldDecreaseHealth() { OrganicPet underTest = new OrganicPet("", "", 1, 100); underTest.organicPetTick(); int result = underTest.getHealth(); assertEquals(90, result); } @Test public void damageShouldStillReturnToZeroAfterHungerDamage() { OrganicPet underTest = new OrganicPet("", "", 100, 1); underTest.organicPetTick(); int result = underTest.getDamage(); assertEquals(0, result); } @Test public void feedingShouldReduceHunger() { OrganicPet underTest = new OrganicPet("", "", 80, 1); underTest.feed(); int result = underTest.getHunger(); assertEquals(79, result); } @Test public void feedingOneShouldReduceHungerFifteen() { OrganicPet underTest = new OrganicPet("", "", 16, 1); underTest.feed(1); int result = underTest.getHunger(); assertEquals(1, result); } @Test public void feedingTwoShouldReduceHungerThirty() { OrganicPet underTest = new OrganicPet("", "", 31, 1); underTest.feed(2); int result = underTest.getHunger(); assertEquals(1, result); } @Test public void feedingThreeShouldReduceHungerFourtyFive() { OrganicPet underTest = new OrganicPet("", "", 46, 1); underTest.feed(3); int result = underTest.getHunger(); assertEquals(1, result); } @Test public void feedingOneShouldAlsoIncreaseThirstByFive() { OrganicPet underTest = new OrganicPet("", "", 1, 1); underTest.feed(1); int result = underTest.getThirst(); assertEquals(6, result); } @Test public void feedingTwoShouldAlsoIncreaseThirstByTen() { OrganicPet underTest = new OrganicPet("", "", 1, 1); underTest.feed(2); int result = underTest.getThirst(); assertEquals(11, result); } @Test public void feedingThreeShouldAlsoIncreaseThirstByFifteen() { OrganicPet underTest = new OrganicPet("", "", 1, 1); underTest.feed(3); int result = underTest.getThirst(); assertEquals(16, result); } @Test public void wateringShouldReduceThirst() { OrganicPet underTest = new OrganicPet("", "", 1, 80); underTest.water(); int result = underTest.getThirst(); assertEquals(79, result); } @Test public void wateringOneShouldReduceThirstFifteen() { OrganicPet underTest = new OrganicPet("", "", 1, 16); underTest.water(1); int result = underTest.getThirst(); assertEquals(1, result); } @Test public void wateringTwoShouldReduceThirstThirty() { OrganicPet underTest = new OrganicPet("", "", 1, 31); underTest.water(2); int result = underTest.getThirst(); assertEquals(1, result); } @Test public void wateringThreeShouldReduceThirstFourtyFive() { OrganicPet underTest = new OrganicPet("", "", 1, 46); underTest.water(3); int result = underTest.getThirst(); assertEquals(1, result); } }
package com.espendwise.manta.service; import com.espendwise.manta.model.data.BusEntityData; import com.espendwise.manta.model.data.PropertyData; import com.espendwise.manta.model.entity.StoreListEntity; import com.espendwise.manta.model.data.StoreProfileData; import com.espendwise.manta.model.view.StoreIdentView; import com.espendwise.manta.util.criteria.StoreListEntityCriteria; import java.util.List; import java.util.Locale; public interface StoreService { public List<PropertyData> findStoreUiProperties(Long storeId, Locale locale); public List<PropertyData> findStoreProperties(Long storeId, List<String> propertyTypes); public List<StoreListEntity> findListEntity(Long userId, Integer limit); public List<StoreListEntity> findListEntity(Long userId, StoreListEntityCriteria criteria); public List<BusEntityData> findStores(); public List<BusEntityData> findUserStores(Long userId); public List<StoreProfileData> findStoreProfile(Long storeId); public StoreIdentView findStoreIdent(Long storeId); }
package com.xncoding.pos.controller; import cn.hutool.core.date.DateUtil; import net.coobird.thumbnailator.Thumbnails; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.UUID; @Controller public class UploadController { private static final Logger logger = LoggerFactory.getLogger(UploadController.class); @RequestMapping("/") public String demo() { return "index"; } /** * java 上传图片 并压缩图片大小 * https://www.cnblogs.com/miskis/p/5500822.html */ @PostMapping("/upload") @ResponseBody public String upload(@RequestParam("file") MultipartFile imageFile, HttpServletRequest request) { // 校验判断 if (imageFile == null) { // return new BaseResult(false, "imageFile不能为空"); } if (imageFile.getSize() >= 10 * 1024 * 1024) { // return new BaseResult(false, "文件不能大于10M"); } //拼接后台文件名称 String uuid = UUID.randomUUID().toString(); String fileDirectory = DateUtil.format(new Date(), "YYYY-MM-DD"); String pathName = fileDirectory + File.separator + uuid + "." + FilenameUtils.getExtension(imageFile.getOriginalFilename()); // 构建保存文件 String realPath = "d:/upload"; //获取服务器绝对路径 linux 服务器地址 获取当前使用的配置文件配置 String filePathName = realPath + File.separator + pathName; logger.info("图片上传路径:" + filePathName); // 判断文件保存是否存在 File file = new File(filePathName); if (file.getParentFile() != null || !file.getParentFile().isDirectory()) { file.getParentFile().mkdirs(); } InputStream inputStream = null; FileOutputStream fileOutputStream = null; try { inputStream = imageFile.getInputStream(); fileOutputStream = new FileOutputStream(file); //写出文件 //2016-05-12 yangkang 改为增加缓存 // IOUtils.copy(inputStream, fileOutputStream); byte[] buffer = new byte[2048]; IOUtils.copyLarge(inputStream, fileOutputStream, buffer); buffer = null; } catch (IOException e) { filePathName = null; // return new BaseResult(false, "操作失败", e.getMessage()); } finally { try { if (inputStream != null) { inputStream.close(); } if (fileOutputStream != null) { fileOutputStream.flush(); fileOutputStream.close(); } } catch (IOException e) { filePathName = null; // return new BaseResult(false, "操作失败", e.getMessage()); } } // 生成缩略图 String thumbnailPathName = fileDirectory + File.separator + uuid + "small." + FilenameUtils.getExtension(imageFile.getOriginalFilename()); if (thumbnailPathName.contains(".png")) { thumbnailPathName = thumbnailPathName.replace(".png", ".jpg"); } long size = imageFile.getSize(); double scale = 1.0d; if (size >= 200 * 1024) { if (size > 0) { scale = (200 * 1024f) / size; } } // 缩略图路径 String thumbnailFilePathName = realPath + File.separator + thumbnailPathName; try { //added by chenshun 2016-3-22 注释掉之前长宽的方式,改用大小 // Thumbnails.of(filePathName).size(width, height).toFile(thumbnailFilePathName); if (size < 200 * 1024) { Thumbnails.of(filePathName).scale(1f).outputFormat("jpg").toFile(thumbnailFilePathName); } else { Thumbnails.of(filePathName).scale(1f).outputQuality(scale).outputFormat("jpg").toFile(thumbnailFilePathName); } } catch (Exception e) { // return new BaseResult(false, "操作失败", e1.getMessage()); } /** * 缩略图end */ Map<String, Object> map = new HashMap<String, Object>(); // 原图地址 map.put("originalUrl", pathName); // 缩略图地址 map.put("thumbnailUrl", thumbnailPathName); return map.toString(); } }
package com.geekbrains.gwt.client.register; import com.geekbrains.gwt.client.Tabs; import com.geekbrains.gwt.client.api.AuthClient; import com.geekbrains.gwt.client.login.LoginForm; import com.geekbrains.gwt.client.tasks.TasksTableWidget; import com.geekbrains.gwt.client.utils.ErrorUtil; import com.geekbrains.gwt.common.ErrorDto; import com.geekbrains.gwt.common.UserDto; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.json.client.JSONObject; import com.google.gwt.json.client.JSONParser; import com.google.gwt.json.client.JSONString; import com.google.gwt.json.client.JSONValue; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.uibinder.client.UiTemplate; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.*; import org.fusesource.restygwt.client.Defaults; import org.fusesource.restygwt.client.Method; import org.fusesource.restygwt.client.MethodCallback; import java.util.HashMap; import java.util.Map; public class RegisterForm extends Composite { @UiField TextBox textUsername; @UiField PasswordTextBox textPassword; @UiField TextBox textName; @UiField Button btnRegister; @UiTemplate("RegisterForm.ui.xml") interface RegisterFormBinder extends UiBinder<Widget, RegisterForm> { } private TasksTableWidget tasksTableWidget; private TabLayoutPanel tabPanel; private AuthClient client; private static RegisterFormBinder uiBinder = GWT.create(RegisterFormBinder.class); public RegisterForm(TabLayoutPanel tabPanel, TasksTableWidget tasksTableWidget) { this.initWidget(uiBinder.createAndBindUi(this)); this.tasksTableWidget = tasksTableWidget; this.tabPanel = tabPanel; client = GWT.create(AuthClient.class); } @UiHandler("btnRegister") public void submitClick(ClickEvent event) { if (textName.getValue() == "" || textUsername.getValue() == "" || textPassword.getValue() == "") { Window.alert("Заполните все поля"); return; } UserDto userDto = new UserDto(textName.getValue(), textUsername.getValue(), textPassword.getValue()); client.register(userDto, new MethodCallback<Void>() { @Override public void onFailure(Method method, Throwable throwable) { Window.alert((String) ErrorUtil.getError(method).get("message")); } @Override public void onSuccess(Method method, Void result) { Window.alert("Регистрация успешна. Пожалуйста, авторизуйтесь"); tabPanel.selectTab(Tabs.TAB_LOGIN.value()); } }); } }
package de.jmda.app.uml.shape; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import org.junit.Before; import org.junit.Test; import de.jmda.app.uml.shape.Back; import javafx.geometry.Point2D; public class JUTBackMovedX10 { private Back back; @Before public void before() { back = new Back(0,0); back.moveToX(10); } @Test public void backXIs10() { assertThat(back.getX(), is(10.0)); } @Test public void backYIs0() { assertThat(back.getY(), is( 0.0)); } @Test public void backPointIs_10_0() { assertThat(back.getPoint(), equalTo(new Point2D(10,0))); } }
package com.baidu.camera; import android.os.Bundle; import android.util.Log; import android.view.View; import com.badlogic.gdx.backends.android.AndroidApplication; import com.baidu.camera.template.TemplateController; import com.baidu.camera.template.db.SceneElementManager; import com.baidu.camera.template.db.TemplateElemeteManager; import com.baidu.camera.template.db.TemplateSceneManager; import com.baidu.camera.template.gdx.GdxApp; import com.baidu.camera.template.module.SceneElement; import com.baidu.camera.template.module.TemplateElement; import com.baidu.camera.template.module.TemplateScene; import com.example.ormliteMTMtest.R; import java.sql.SQLException; import java.util.List; /** * Created by yangmengrong on 14-9-3. */ public class GdxActivity extends AndroidApplication { private static final String TAG = "GdxActivity"; private TemplateController mTemplateController; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.gdx_layout); //addTest(TemplateSceneManager.getInstance(),TemplateElemeteManager.getInstance(),SceneElementManager.getInstance()); mTemplateController = TemplateController.getInstance(this, (android.view.ViewGroup) findViewById(R.id.gdx_layout)); mTemplateController.open(); } private void addTest(TemplateSceneManager templateSceneDaoManager, TemplateElemeteManager templateElemeteManager, SceneElementManager sceneElementManager) { try { TemplateScene t = new TemplateScene(); t.setSceneType("aaa"); t.setTitle("bbb"); templateSceneDaoManager.add(t); TemplateElement templateElement = new TemplateElement(); templateElement.setTitle("templateElement1"); templateElement.setElementType("templateElement1"); templateElement.setPath("test.png"); templateElement.setY(10); templateElemeteManager.add(templateElement); sceneElementManager.add(new SceneElement(t,templateElement)); templateElement.setX(50); sceneElementManager.add(new SceneElement(t,templateElement)); templateElement.setX(100); sceneElementManager.add(new SceneElement(t,templateElement)); templateElement.setX(200); sceneElementManager.add(new SceneElement(t,templateElement)); List<SceneElement> sceneElementByScene = sceneElementManager.findSceneElementByScene(t); for (SceneElement sceneElement : sceneElementByScene) { Log.v(TAG, "sceneElement.element = " + sceneElement.getElement().getTitle()); } } catch (SQLException e) { e.printStackTrace(); } } }
package org.newdawn.slick.util.pathfinding.navmesh; public class Link { private float px; private float py; private Space target; public Link(float px, float py, Space target) { this.px = px; this.py = py; this.target = target; } public float distance2(float tx, float ty) { float dx = tx - this.px; float dy = ty - this.py; return dx * dx + dy * dy; } public float getX() { return this.px; } public float getY() { return this.py; } public Space getTarget() { return this.target; } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\newdawn\slic\\util\pathfinding\navmesh\Link.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package com.tencent.mm.plugin.offline; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import com.tencent.mm.plugin.offline.h.1; import com.tencent.mm.ui.MMActivity; class h$1$3 implements OnClickListener { final /* synthetic */ MMActivity gdk; final /* synthetic */ 1 lJc; h$1$3(1 1, MMActivity mMActivity) { this.lJc = 1; this.gdk = mMActivity; } public final void onClick(DialogInterface dialogInterface, int i) { this.lJc.lJb.a(this.gdk, 0, h.n(this.lJc.lJb)); } }
package com.learn.learn.bassis.broadcast; /** * Created by Administrator on 2018/8/25 0025. */ import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; /** * 类 名: MsgService<br> * 说 明:<br> * 创建日期:2018/8/25 0025<br> * 作 者:蒋委员长<br> * 功 能:<br> * 注 意:<br> * 待做事情: */ public class MsgService extends Service { /** * 进度条的最大值 */ public static final int MAX_PROGRESS = 100; /** * 进度条的进度值 */ private int progress = 0; private Intent intent = new Intent("com.wyt.communication.RECEIVER"); /** * 模拟下载任务,每秒钟更新一次 */ public void startDownLoad(){ new Thread(new Runnable() { @Override public void run() { while(progress < MAX_PROGRESS){ progress += 5; Log.i("service---->",progress+""); //发送Action为com.example.communication.RECEIVER的广播 intent.putExtra("progress", progress); sendBroadcast(intent); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { progress = 0; startDownLoad(); return super.onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent intent) { return null; } }
package com.uwetrottmann.trakt5.services; import com.uwetrottmann.trakt5.entities.Comment; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.DELETE; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.PUT; import retrofit2.http.Path; import java.util.List; public interface Comments { /** * <b>OAuth Required</b> * * <p> Add a new comment to a movie, show, episode, or list. If you add a review, it needs to be at least 200 words. * Also make sure to allow and encourage spoilers to be indicated in your app. * * @param comment A {@link Comment} with either a movie, show or episode set, plus comment and spoiler or review * flags. */ @POST("comments") Call<Comment> post( @Body Comment comment ); /** * <b>OAuth Required</b> * * <p> Returns a single comment and indicates how many replies it has. Use GET /comments/:id/replies to get the * actual replies. * * @param id A specific comment ID. Example: 417. */ @GET("comments/{id}") Call<Comment> get( @Path("id") int id ); /** * <b>OAuth Required</b> * * <p> Update a single comment created within the last hour. The OAuth user must match the author of the comment in * order to update it. * * @param id A specific comment ID. Example: 417. * @param comment A {@link Comment} with comment and spoiler or review flags. */ @PUT("comments/{id}") Call<Comment> update( @Path("id") int id, @Body Comment comment ); /** * <b>OAuth Required</b> * * <p> Delete a single comment created within the last hour. This also effectively removes any replies this comment * has. The OAuth user must match the author of the comment in order to delete it. * * @param id A specific comment ID. Example: 417. */ @DELETE("comments/{id}") Call<Void> delete( @Path("id") int id ); /** * <b>OAuth Required</b> * * <p> Returns all replies for a comment. It is possible these replies could have replies themselves, so in that * case you would just call GET /comment/:id/replies again with the new comment_id. * * @param id A specific comment ID. Example: 417. */ @GET("comments/{id}/replies") Call<List<Comment>> replies( @Path("id") int id ); /** * <b>OAuth Required</b> * * <p> Add a new reply to an existing comment. Also make sure to allow and encourage spoilers to be indicated in * your app. * * @param id A specific comment ID. Example: 417. * @param comment A {@link Comment} with comment and spoiler or review flags. */ @POST("comments/{id}/replies") Call<Comment> postReply( @Path("id") int id, @Body Comment comment ); }
package com.wat.interfaces; public class TestInterface { public static void main(String[] args) { Humain h=new Femme(); h.dormir(); } }
package boj; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; public class testing { private static List<Pair>[] graph; public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int V = Integer.parseInt(st.nextToken()); int E = Integer.parseInt(st.nextToken()); graph = new ArrayList[V]; for (int i = 0; i < V; i++) { graph[i] = new ArrayList<>(); } for (int i = 0; i <E; i++) { st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken())-1; int b = Integer.parseInt(st.nextToken())-1; int w = Integer.parseInt(st.nextToken()); Pair p1 = new Pair(b, w); Pair p2 = new Pair(a, w); graph[a].add(p1); graph[b].add(p2); } boolean[] visited= new boolean[V]; int[] key = new int[V]; int[] p = new int[V]; Arrays.fill(key, Integer.MAX_VALUE); key[0] = 0; p[0] = -1; for (int i = 0; i < V-1; i++) { int min = Integer.MAX_VALUE; int index = -1; // 키가 최소인 인덱스와 키값 찾기 for (int j = 0; j < V; j++) { if(!visited[j] && key[j] < min) { index = j; min = key[j]; } } visited[index] = true; for (Pair p1: graph[index]) { int ca = p1.a; int cw = p1.w; if(!visited[ca] && cw <key[ca]) { p[ca] = index; key[ca] = cw; } } } int result = 0; for (int i = 0; i < V; i++) { result += key[i]; } System.out.println(result); } public static class Pair{ int a; int w; public Pair(int a, int w) { super(); this.a = a; this.w = w; } @Override public String toString() { return "Pair [a=" + a + ", w=" + w + "]"; } } }
package com.tuitaking.binary_search_algorithm; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; /** * 350. 两个数组的交集 II * 给定两个数组,编写一个函数来计算它们的交集。 * * * * 示例 1: * * 输入:nums1 = [1,2,2,1], nums2 = [2,2] * 输出:[2,2] * 示例 2: * * 输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4] * 输出:[4,9] * * * 说明: * * 输出结果中每个元素出现的次数,应与元素在两个数组中出现次数的最小值一致。 * 我们可以不考虑输出结果的顺序。 * 进阶: * * 如果给定的数组已经排好序呢?你将如何优化你的算法? * 如果 nums1 的大小比 nums2 小很多,哪种方法更优? * 如果 nums2 的元素存储在磁盘上,内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办? * https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/ */ public class Intersect_350 { /** * 该方法没有用到题目中提到顺序无关的,可以现排序然后在对比 * @param nums1 * @param nums2 * @return */ public int[] intersect(int[] nums1, int[] nums2) { int len1=nums1.length; int len2=nums2.length; if(len1<len2){ // 保证nums1的长度是长的那个 return intersect(nums2,nums1); } HashMap<Integer,Integer> count=new HashMap<>(); for(int i:nums2){ Integer num=count.get(i); if(num==null){ num=1; }else { num++; } count.put(i,num); } List<Integer> res=new ArrayList<Integer>(); for(Integer i:nums1){ if(count.get(i)!=null&& count.get(i)>0){ res.add(i); count.put(i,count.get(i)-1); } } int[] result=new int[res.size()]; int j=0; for(int i:res){ result[j]=i; j++; } return result; } public int[] intersect_v1(int[] nums1, int[] nums2) { Arrays.sort(nums1); Arrays.sort(nums2); int count = 0; for( int i =0,j =0;i<nums1.length &&j<nums2.length;){ if(nums1[i] == nums2[j]){ nums1[count++] =nums1[i++]; j++; }else if(nums1[i]<nums2[j]){ i++;} else{ j++;} } return Arrays.copyOfRange(nums1,0,count); } public static void main(String[] args) { int[] nums1 = {1,2,2,1}, nums2 = {2,2}; Intersect_350 intersect_350=new Intersect_350(); int[] res=intersect_350.intersect(nums1,nums2); for(int i :res){ System.out.println(i); } } }
package com.mitelcel.pack.ui; import android.content.Intent; import android.os.Bundle; import android.support.annotation.IdRes; import android.support.v7.app.ActionBar; import android.view.MenuItem; import android.view.View; import com.afollestad.materialdialogs.MaterialDialog; import com.jirbo.adcolony.AdColony; import com.jirbo.adcolony.AdColonyAd; import com.jirbo.adcolony.AdColonyAdAvailabilityListener; import com.jirbo.adcolony.AdColonyAdListener; import com.jirbo.adcolony.AdColonyVideoAd; import com.mitelcel.pack.Config; import com.mitelcel.pack.MiApp; import com.mitelcel.pack.R; import com.mitelcel.pack.api.MiApiClient; import com.mitelcel.pack.bean.api.request.BeanRechargeAccount; import com.mitelcel.pack.bean.api.response.BeanRechargeAccountResponse; import com.mitelcel.pack.ui.fragment.FragmentCommunicate; import com.mitelcel.pack.ui.fragment.FragmentVideoAd; import com.mitelcel.pack.ui.listener.OnDialogListener; import com.mitelcel.pack.utils.FragmentHandler; import com.mitelcel.pack.utils.MiLog; import com.mitelcel.pack.utils.MiUtils; import javax.inject.Inject; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; public class CommunicateActivity extends BaseActivity implements OnDialogListener, FragmentCommunicate.OnCommunicateFragmentInteractionListener, FragmentVideoAd.OnCommunicateFragmentInteractionListener, AdColonyAdAvailabilityListener, AdColonyAdListener { private static final String TAG = CommunicateActivity.class.getName(); MaterialDialog dialog; @Inject MiApiClient miApiClient; private AdColonyVideoAd ad; private boolean watchClick = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_generic); if (savedInstanceState == null) { FragmentHandler.addFragmentInBackStack(getSupportFragmentManager(), null, FragmentCommunicate.TAG, FragmentCommunicate.newInstance(), R.id.container); AdColony.setDeviceID(MiUtils.MiAppPreferences.getToken()); String client_options = "version:"+ com.mitelcel.pack.BuildConfig.VERSION_NAME + ",store:google"; AdColony.configure(this, client_options, Config.ADCOLONY_APP_ID, Config.ADCOLONY_ZONE_ID); } ActionBar actionBar = getSupportActionBar(); if(actionBar != null) actionBar.setDisplayHomeAsUpEnabled(true); dialog = new MaterialDialog.Builder(this) .content(R.string.please_wait) .progress(true, 0) .build(); ((MiApp)getApplication()).getAppComponent().inject(this); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == android.R.id.home) { super.onBackPressed(); return true; } return super.onOptionsItemSelected(item); } @Override public void onResume() { super.onResume(); AdColony.resume(this); ad = new AdColonyVideoAd(Config.ADCOLONY_ZONE_ID).withListener(this); AdColony.addAdAvailabilityListener(this); } @Override public void onPause() { super.onPause(); AdColony.removeAdAvailabilityListener(this); AdColony.pause(); } @Override public void onStartVideoClick(View view){ MiLog.i(TAG, "onStartVideoClick event"); FragmentHandler.addFragmentInBackStack(getSupportFragmentManager(), TAG, FragmentVideoAd.TAG, FragmentVideoAd.newInstance(), R.id.container); } @Override public void onWatchVideoClick(){ MiLog.i(TAG, "onWatchVideoClick event"); watchClick = true; if(ad.isReady()){ dialog.hide(); ad.show(); ad = new AdColonyVideoAd(Config.ADCOLONY_ZONE_ID).withListener(this); } else dialog.show(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); MiLog.i(TAG, "onActivityResult: requestCode " + requestCode + " resultCode " + resultCode); } @Override public void showDialogErrorCall(String content, String btnTex, @IdRes int resId, int requestCode) { if (requestCode == DialogActivity.APP_REQ) { MiUtils.showDialogError(this, content, btnTex, resId, DialogActivity.APP_ERROR_CALL); } } public void showDialogSuccessCall(String content, String btnTex, @IdRes int resId) { MiUtils.showDialogSuccess(this, content, btnTex, resId, DialogActivity.APP_RES); } @Override public void onAdColonyAdAvailabilityChange( final boolean available, String zone_id ) { runOnUiThread(() -> { MiLog.i(TAG, "onAdColonyAdAvailabilityChange with " + available); FragmentVideoAd videoAd = (FragmentVideoAd) getSupportFragmentManager().findFragmentByTag(FragmentVideoAd.TAG); if (available) { if(dialog.isShowing()) { dialog.hide(); if(watchClick) { ad.show(); } } else if (videoAd != null) { videoAd.enableWatch(); } } else { dialog.show(); if (videoAd != null) { videoAd.disableWatch(); } } }); } @Override public void onAdColonyAdAttemptFinished( AdColonyAd ad ) { //Can use the ad object to determine information about the ad attempt: //ad.shown(); //ad.notShown(); //ad.canceled(); //ad.noFill(); //ad.skipped(); if(ad.shown()){ MiLog.i(TAG, "onAdColonyAdAttemptFinished ad shown call started"); MiUtils.MiAppPreferences.setVideoDelay(System.currentTimeMillis()); FragmentVideoAd videoAd = (FragmentVideoAd) getSupportFragmentManager().findFragmentByTag(FragmentVideoAd.TAG); if(videoAd != null){ videoAd.disableWatchWithDelay(); } float amount = 0.25f; BeanRechargeAccount beanRechargeAccount = new BeanRechargeAccount(amount); miApiClient.recharge_account(beanRechargeAccount, new Callback<BeanRechargeAccountResponse>() { @Override public void success(BeanRechargeAccountResponse beanRechargeAccountResponse, Response response) { dialog.dismiss(); if(beanRechargeAccountResponse != null) { if (beanRechargeAccountResponse.getError().getCode() == Config.SUCCESS) { MiLog.i(TAG, "Recharge API response " + beanRechargeAccountResponse.toString()); MiUtils.MiAppPreferences.setSessionId(beanRechargeAccountResponse.getResult().getSessionId()); MiUtils.MiAppPreferences.setCurrentBalance(MiUtils.MiAppPreferences.getCurrentBalance() + amount); showDialogSuccessCall(getString(R.string.communicate_success, MiUtils.MiAppPreferences.getCurrencySymbol(), amount), getString(R.string.close), DialogActivity.DIALOG_HIDDEN_ICO); } else { MiLog.i(TAG, "Video bonus recharge API Error response " + beanRechargeAccountResponse.toString()); // showDialogErrorCall(getString(R.string.something_is_wrong), getString(R.string.retry), DialogActivity.DIALOG_HIDDEN_ICO, DialogActivity.APP_REQ); } } else { MiLog.i(TAG, "Video bonus recharge API NULL response"); // showDialogErrorCall(getString(R.string.something_is_wrong), getString(R.string.retry), DialogActivity.DIALOG_HIDDEN_ICO, DialogActivity.APP_REQ); } } @Override public void failure(RetrofitError error) { dialog.dismiss(); MiLog.i(TAG, "Video bonus API failure " + error.toString()); // showDialogErrorCall(getString(R.string.something_is_wrong), getString(R.string.retry), DialogActivity.DIALOG_HIDDEN_ICO, DialogActivity.APP_REQ); } }); } } @Override public void onAdColonyAdStarted( AdColonyAd ad ) { //Called when the ad has started playing watchClick = false; } }
package com.example.test.gpucamera; import android.hardware.Camera; import android.hardware.Camera.CameraInfo; import android.hardware.Camera.Parameters; import android.opengl.GLSurfaceView; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import com.example.test.R; import com.example.test.gpucamera.utils.CameraHelper; import com.example.test.gpucamera.utils.CameraHelper.CameraInfo2; import jp.co.cyberagent.android.gpuimage.GPUImage; import jp.co.cyberagent.android.gpuimage.GPUImageWhiteBalanceFilter; public class CameraActivity extends AppCompatActivity { private GPUImage mGPUImage; private CameraHelper mCameraHelper; private CameraLoader mCamera; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_camera); mGPUImage = new GPUImage(this); mGPUImage.setGLSurfaceView((GLSurfaceView) findViewById(R.id.surfaceView)); mCameraHelper = new CameraHelper(this); mCamera = new CameraLoader(); mGPUImage.setFilter(new GPUImageWhiteBalanceFilter()); } @Override protected void onResume() { super.onResume(); mCamera.onResume(); } @Override protected void onPause() { mCamera.onPause(); super.onPause(); } private class CameraLoader { private int mCurrentCameraId = 0; private Camera mCameraInstance; public void onResume() { setUpCamera(mCurrentCameraId); } public void onPause() { releaseCamera(); } public void switchCamera() { releaseCamera(); mCurrentCameraId = (mCurrentCameraId + 1) % mCameraHelper.getNumberOfCameras(); setUpCamera(mCurrentCameraId); } private void setUpCamera(final int id) { mCameraInstance = getCameraInstance(id); Parameters parameters = mCameraInstance.getParameters(); // TODO adjust by getting supportedPreviewSizes and then choosing // the best one for screen size (best fill screen) if (parameters.getSupportedFocusModes().contains( Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) { parameters.setFocusMode(Parameters.FOCUS_MODE_CONTINUOUS_PICTURE); } mCameraInstance.setParameters(parameters); int orientation = mCameraHelper.getCameraDisplayOrientation( CameraActivity.this, mCurrentCameraId); CameraInfo2 cameraInfo = new CameraInfo2(); mCameraHelper.getCameraInfo(mCurrentCameraId, cameraInfo); boolean flipHorizontal = cameraInfo.facing == CameraInfo.CAMERA_FACING_FRONT; mGPUImage.setUpCamera(mCameraInstance, orientation, flipHorizontal, false); } /** A safe way to get an instance of the Camera object. */ private Camera getCameraInstance(final int id) { Camera c = null; try { c = mCameraHelper.openCamera(id); } catch (Exception e) { e.printStackTrace(); } return c; } private void releaseCamera() { mCameraInstance.setPreviewCallback(null); mCameraInstance.release(); mCameraInstance = null; } } }
package org.sacc.SaccHome.exception; import lombok.Data; import lombok.EqualsAndHashCode; import org.sacc.SaccHome.enums.ResultCode; /** * @author: 風楪fy * @create: 2021-07-18 04:24 * * 认证异常 **/ @EqualsAndHashCode(callSuper = true) @Data public class AuthenticationException extends RuntimeException { private ResultCode resultCode; public AuthenticationException(ResultCode resultCode) { super(resultCode.getMessage()); this.resultCode = resultCode; } }
package fr.umlv.escape.wave; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Objects; import fr.umlv.escape.ship.Ship; /** * Class that represent a wave of {@link Ship}. */ public class Wave { private final String name; private final List<Ship> shipList; /** * Constructor. * @param name The name of the wave. */ public Wave(String name){ Objects.requireNonNull(name); this.name=name; this.shipList=new LinkedList<>(); } /** * Active and launch all {@link Ship} containing in the wave. */ public void startWave(){ Iterator<Ship> iterShip=this.shipList.iterator(); while(iterShip.hasNext()){ Ship ship=iterShip.next(); ship.getBody().setActive(true); ship.move(); } } /** * Get the list of {@link Ship} that compose the wave. * @return The */ public List<Ship> getShipList() { return shipList; } @Override public String toString(){ String res=this.name; Iterator<Ship> iterShip=this.shipList.iterator(); while(iterShip.hasNext()){ res+=" "+iterShip.next().toString(); } return res; } }
package com.google.firebase.example.appindexing; import android.content.Context; import android.content.Intent; import androidx.annotation.NonNull; import androidx.core.app.JobIntentService; import com.google.firebase.appindexing.FirebaseAppIndex; import com.google.firebase.appindexing.Indexable; import com.google.firebase.appindexing.builders.Indexables; import com.google.firebase.example.appindexing.model.Note; import com.google.firebase.example.appindexing.model.Recipe; import java.util.ArrayList; import java.util.Collections; import java.util.List; // [START appindexing_update_service] public class AppIndexingUpdateService extends JobIntentService { // Job-ID must be unique across your whole app. private static final int UNIQUE_JOB_ID = 42; public static void enqueueWork(Context context) { enqueueWork(context, AppIndexingUpdateService.class, UNIQUE_JOB_ID, new Intent()); } @Override protected void onHandleWork(@NonNull Intent intent) { // TODO Insert your Indexable objects — for example, the recipe notes look as follows: ArrayList<Indexable> indexableNotes = new ArrayList<>(); for (Recipe recipe : getAllRecipes()) { Note note = recipe.getNote(); if (note != null) { Indexable noteToIndex = Indexables.noteDigitalDocumentBuilder() .setName(recipe.getTitle() + " Note") .setText(note.getText()) .setUrl(recipe.getNoteUrl()) .build(); indexableNotes.add(noteToIndex); } } if (indexableNotes.size() > 0) { Indexable[] notesArr = new Indexable[indexableNotes.size()]; notesArr = indexableNotes.toArray(notesArr); // batch insert indexable notes into index FirebaseAppIndex.getInstance().update(notesArr); } } // [START_EXCLUDE] private List<Recipe> getAllRecipes() { return Collections.emptyList(); } // [END_EXCLUDE] } // [END appindexing_update_service]
package model.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import model.Department; import model.Employee; import model.Image; import model.Position; import model.TypeOfSearch; public class EmployeeDAO { Connection con = null; private final String DB_URI = "jdbc:mysql://localhost/employee_information?useUnicode=true&characterEncoding=utf8"; ImageDAO imageDao = new ImageDAO(); public List<Employee> searchEmployee(TypeOfSearch type) { List<Employee> mutterList = new ArrayList<Employee>(); try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(DB_URI, "root", "i-standard"); String department = type.getDepartment(); String empID = type.getEmpID(); String searchString = "%" + type.getSearchString() + "%"; PreparedStatement pstmt = null; String sql = null; if (!empID.equals("")) { sql = "SELECT ID,NAME FROM EMPINF WHERE ID = ?"; pstmt = con.prepareStatement(sql); pstmt.setString(1, empID); } else if (searchString.equals("")) { if (department.equals("all")) { return searchEmployee(); } sql = "SELECT ID,NAME FROM EMPINF WHERE DEPARTMENT_ID = ?"; pstmt = con.prepareStatement(sql); pstmt.setString(1, department); } else { if (department.equals("all")) { sql = "SELECT ID,NAME FROM EMPINF WHERE NAME LIKE ?"; pstmt = con.prepareStatement(sql); pstmt.setString(1, searchString); } else { sql = "SELECT ID,NAME FROM EMPINF WHERE NAME LIKE ? AND DEPARTMENT_ID = ?"; pstmt = con.prepareStatement(sql); pstmt.setString(1, searchString); pstmt.setString(2, department); } } ResultSet rs = pstmt.executeQuery(); while (rs.next()) { empID = rs.getString("ID"); String name = rs.getString("NAME"); Employee employee = new Employee(empID, name); mutterList.add(employee); } return mutterList; } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); return null; } finally { conClose(con); } } public List<Employee> searchEmployee() { List<Employee> mutterList = new ArrayList<Employee>(); try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(DB_URI, "root", "i-standard"); String sql = "SELECT ID,NAME FROM EMPINF"; PreparedStatement pstmt = con.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { String empID = rs.getString("ID"); String name = rs.getString("NAME"); Employee employee = new Employee(empID, name); mutterList.add(employee); } return mutterList; } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); return null; } finally { conClose(con); } } public Employee getEmployee(String empID) { DepartmentDAO departDao = new DepartmentDAO(); PositionDAO positionDao = new PositionDAO(); try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(DB_URI, "root", "i-standard"); String sql = "SELECT * FROM EMPINF WHERE ID = ?"; PreparedStatement pstmt = con.prepareStatement(sql); pstmt.setString(1, empID); ResultSet rs = pstmt.executeQuery(); rs.next(); String ID = rs.getString("ID"); String name = rs.getString("NAME"); String age = rs.getString("AGE"); int sex = rs.getInt("SEX"); String imageID = rs.getString("IMAGE_ID"); String addressNum = rs.getString("ADDRESS_NUM"); String city = rs.getString("CITY"); String address = rs.getString("ADDRESS"); String departID = rs.getString("DEPARTMENT_ID"); Department department = departDao.searchDepartment(departID); String posID = rs.getString("POSITION_ID"); Position position = positionDao.searchPosition(posID); String enterDate = rs.getString("ENTER_DATE"); String retireDate = rs.getString("RETIRE_DATE"); Image image = new Image(); image.setData(imageDao.getImage(imageID)); image.setImageID(imageID); Employee employee = new Employee(ID, name, age, sex, image, addressNum, city, address, department, position, enterDate, retireDate); return employee; } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); return null; } finally { conClose(con); } } public boolean addEmployee(Employee employee) { try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(DB_URI, "root", "i-standard"); String sql = "INSERT INTO EMPINF(ID, NAME, AGE, SEX, IMAGE_ID, ADDRESS_NUM, CITY, ADDRESS, DEPARTMENT_ID, POSITION_ID, ENTER_DATE, RETIRE_DATE) VALUES(?,?,?,?,?,?,?,?,?,?,?)"; PreparedStatement pstmt = con.prepareStatement(sql); int count = 1; pstmt.setString(count++, employee.getEmpID()); pstmt.setString(count++, employee.getName()); pstmt.setString(count++, employee.getAge()); pstmt.setInt(count++, employee.getSex()); pstmt.setString(count++, employee.getImage().getImageID()); pstmt.setString(count++, employee.getAddressNum()); pstmt.setString(count++, employee.getCity()); pstmt.setString(count++, employee.getAddress()); pstmt.setObject(count++, employee.getDepartment().getId()); pstmt.setObject(count++, employee.getPosition().getId()); pstmt.setString(count++, employee.getEnterDate()); pstmt.setString(count++, employee.getRetireDate()); imageDao.addImage(employee.getImage()); pstmt.executeUpdate(); return true; } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); return false; } finally { conClose(con); } } public boolean updateEmployee(Employee employee) { try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(DB_URI, "root", "i-standard"); String sql = "UPDATE EMPINF SET ID=?, NAME=?, AGE=?, SEX=?, IMAGE_ID=?, ADDRESS_NUM=?, CITY=?, ADDRESS=?, DEPARTMENT_ID=?, ENTER_DATE=?, RETIRE_DATE=? WHERE ID = ?"; PreparedStatement pstmt = con.prepareStatement(sql); int count = 1; pstmt.setString(count++, employee.getEmpID()); pstmt.setString(count++, employee.getName()); pstmt.setString(count++, employee.getAge()); pstmt.setInt(count++, employee.getSex()); pstmt.setString(count++, employee.getImage().getImageID()); pstmt.setString(count++, employee.getAddressNum()); pstmt.setString(count++, employee.getCity()); pstmt.setString(count++, employee.getAddress()); pstmt.setObject(count++, employee.getDepartment().getId()); pstmt.setString(count++, employee.getEnterDate()); pstmt.setString(count++, employee.getRetireDate()); pstmt.setString(count++, employee.getEmpID()); imageDao.updateImage(employee.getImage()); pstmt.executeUpdate(); return true; } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); return false; } finally { conClose(con); } } public boolean deleteEmployee(String empID) { try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(DB_URI, "root", "i-standard"); String sql = "SELECT IMAGE_ID FROM EMPINF WHERE ID =?"; PreparedStatement pstmt = con.prepareStatement(sql); pstmt.setString(1, empID); ResultSet rs = pstmt.executeQuery(); rs.next(); imageDao.deleteImage(rs.getString("IMAGE_ID")); sql = "DELETE FROM EMPINF WHERE ID = ?"; pstmt = con.prepareStatement(sql); pstmt.setString(1, empID); int result = pstmt.executeUpdate(); if (result != 1) { return false; } return true; } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); return false; } finally { conClose(con); } } public String getLastIDNum() { try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(DB_URI, "root", "i-standard"); String sql = "SELECT ID FROM EMPINF ORDER BY ID DESC LIMIT 1"; PreparedStatement pstmt = con.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); rs.next(); String[] idStr = rs.getString("ID").split("EMP"); int idNum = Integer.parseInt(idStr[1]) + 1; String id = "EMP" + String.format("%03d", idNum); return id; } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); return null; } finally { conClose(con); } } public void conClose(Connection con) { if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
package com.tencent.mm.plugin.wallet.balance.ui; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.os.Bundle; import android.text.SpannableString; import android.text.TextUtils; import android.text.style.ForegroundColorSpan; import android.view.LayoutInflater; import android.view.MenuItem.OnMenuItemClickListener; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.tencent.mm.ab.l; import com.tencent.mm.g.a.sy; import com.tencent.mm.plugin.wallet.a.p; import com.tencent.mm.plugin.wallet.balance.a; import com.tencent.mm.plugin.wallet_core.c.y; import com.tencent.mm.plugin.wallet_core.model.Bankcard; import com.tencent.mm.plugin.wallet_core.model.ECardInfo; import com.tencent.mm.plugin.wallet_core.model.aa; import com.tencent.mm.plugin.wallet_core.model.ae; import com.tencent.mm.plugin.wallet_core.model.ag; import com.tencent.mm.plugin.wallet_core.model.j; import com.tencent.mm.plugin.wallet_core.model.o; import com.tencent.mm.plugin.wallet_core.ui.k.10; import com.tencent.mm.plugin.wallet_core.ui.k.7; import com.tencent.mm.plugin.wallet_core.ui.k.8; import com.tencent.mm.plugin.wallet_core.ui.k.9; import com.tencent.mm.plugin.walletlock.a.b; import com.tencent.mm.plugin.wxpay.a.c; import com.tencent.mm.plugin.wxpay.a.f; import com.tencent.mm.plugin.wxpay.a.g; import com.tencent.mm.plugin.wxpay.a.h; import com.tencent.mm.plugin.wxpay.a.i; import com.tencent.mm.pluginsdk.ui.applet.CdnImageView; import com.tencent.mm.pluginsdk.wallet.PayInfo; import com.tencent.mm.sdk.platformtools.BackwardSupportUtil; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.w; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.s; import com.tencent.mm.wallet_core.c.q; import com.tencent.mm.wallet_core.c.v; import com.tencent.mm.wallet_core.ui.WalletBaseUI; import com.tencent.mm.wallet_core.ui.e; import java.util.ArrayList; import java.util.Iterator; import org.json.JSONException; import org.json.JSONObject; public class WalletBalanceManagerUI extends WalletBaseUI implements j { protected int fdx; protected TextView oZM; protected TextView pan; protected Button pao; protected View pap; protected View paq; protected TextView par; protected ViewGroup pas; protected CdnImageView pat; protected TextView pau; protected TextView pav; protected Bankcard paw; static /* synthetic */ void c(WalletBalanceManagerUI walletBalanceManagerUI) { Bundle bundle = new Bundle(); walletBalanceManagerUI.sy.get("key_pay_info"); PayInfo payInfo = new PayInfo(); payInfo.bVY = 21; bundle.putParcelable("key_pay_info", payInfo); bundle.putInt("key_scene", 21); bundle.putInt("key_bind_scene", 0); bundle.putBoolean("key_need_bind_response", true); bundle.putInt("key_bind_scene", 0); bundle.putBoolean("key_is_bind_bankcard", true); bundle.putInt("from_bind_ui", a.oYw); com.tencent.mm.wallet_core.a.a((Activity) walletBalanceManagerUI, a.class, bundle, null); } protected final int getLayoutId() { return g.wallet_balance_manager_ui; } public void onCreate(Bundle bundle) { super.onCreate(bundle); lF(getResources().getColor(c.normal_actionbar_color)); cqh(); ((b) com.tencent.mm.kernel.g.l(b.class)).a(this, null); setBackBtn(new 1(this), h.actionbar_icon_dark_back); this.fdx = getIntent().getIntExtra("key_scene_balance_manager", 0); Intent intent = getIntent(); String stringExtra = intent.getStringExtra("key_inc_bal_amt_flag"); ECardInfo eCardInfo = (ECardInfo) intent.getParcelableExtra("key_ecard_info"); if ("3".equals(stringExtra)) { if (eCardInfo != null) { View inflate = LayoutInflater.from(this).inflate(g.wallet_inc_balance_amt_dialog, null); ImageView imageView = (ImageView) inflate.findViewById(f.close_icon); int b = BackwardSupportUtil.b.b(this, 15.0f); bi.j(imageView, b, b, b, b); LinearLayout linearLayout = (LinearLayout) inflate.findViewById(f.main_tip_wording); Button button = (Button) inflate.findViewById(f.upload_btn); TextView textView = (TextView) inflate.findViewById(f.main_protocol_wording); CheckBox checkBox = (CheckBox) inflate.findViewById(f.checkbox); TextView textView2 = (TextView) inflate.findViewById(f.checkbox_protocal_tv); ((TextView) inflate.findViewById(f.main_title)).setText(eCardInfo.title); linearLayout.removeAllViews(); Iterator it = eCardInfo.pnf.iterator(); while (it.hasNext()) { String str = (String) it.next(); View inflate2 = LayoutInflater.from(this).inflate(g.wallet_id_card_wordingtip, null); ((TextView) inflate2.findViewById(f.wording_tip)).setText(str); linearLayout.addView(inflate2); } b = eCardInfo.pni.length(); int length = (eCardInfo.pni + eCardInfo.pnj).length(); CharSequence spannableString = new SpannableString(eCardInfo.pni + eCardInfo.pnj); spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(c.wallet_offline_link_color)), b, length, 33); textView.setText(spannableString); textView.setOnClickListener(new k$6(eCardInfo, this)); Dialog dialog = new Dialog(this, com.tencent.mm.plugin.wxpay.a.j.mmalertdialog); dialog.setContentView(inflate); dialog.setTitle(null); dialog.setOnCancelListener(new 7(dialog)); imageView.setOnClickListener(new 8(dialog)); button.setOnClickListener(new 9(eCardInfo, this, dialog)); if (eCardInfo.pmZ == 1) { checkBox.setOnCheckedChangeListener(new 10(button)); if (eCardInfo.pna == 1) { checkBox.setChecked(true); } else { checkBox.setChecked(false); button.setEnabled(false); button.setClickable(false); } } else { checkBox.setVisibility(8); } int length2 = eCardInfo.pnb.length(); length = (eCardInfo.pnb + eCardInfo.pnc).length(); CharSequence spannableString2 = new SpannableString(eCardInfo.pnb + eCardInfo.pnc); spannableString2.setSpan(new ForegroundColorSpan(getResources().getColor(c.wallet_offline_link_color)), length2, length, 33); textView2.setText(spannableString2); textView2.setOnClickListener(new k$2(eCardInfo, this)); dialog.show(); } else { x.w("MicroMsg.WalletBalanceManagerUI", "ecard info is null"); } } jr(621); o.bPd(); aa.a(this); initView(); q.fu(2, 0); com.tencent.mm.plugin.report.service.h.mEJ.h(11850, new Object[]{Integer.valueOf(6), Integer.valueOf(0)}); e.He(10); } public void bMV() { boolean z; p.bNp(); if (p.bNq().paw == null) { z = true; } else { z = false; } a(new y(null, 10), z, false); } public void onDestroy() { js(621); o.bPd(); aa.b(this); super.onDestroy(); } public void bMW() { L(WalletBalanceSaveUI.class); } protected final void initView() { boolean fU; setMMTitle(i.wallet_balance_manager_title); this.pan = (TextView) findViewById(f.wallet_balance_total); this.oZM = (TextView) findViewById(f.wallet_balance_manager_banner); ((Button) findViewById(f.next_btn)).setOnClickListener(new 7(this)); this.pao = (Button) findViewById(f.wallet_balance_manager_fetch_btn); this.pao.setOnClickListener(new 8(this)); TextView textView = (TextView) findViewById(f.wallet_balance_manager_qanda); if (w.chP().equals("zh_CN")) { fU = bi.fU(ad.getContext()); } else { fU = true; } if (fU) { textView.setVisibility(8); } else { textView.setOnClickListener(new 9(this)); textView.setVisibility(0); } ((TextView) findViewById(f.wallet_support_info)).setText(v.cDl()); this.pap = findViewById(f.licaitong_layout); this.par = (TextView) findViewById(f.licaitong_tips); this.paq = findViewById(f.licaitong_icon); this.pas = (ViewGroup) findViewById(f.lqt_cell_entry); this.pat = (CdnImageView) findViewById(f.lqt_cell_icon); this.pat.setUseSdcardCache(true); this.pav = (TextView) findViewById(f.lqt_cell_wording); this.pau = (TextView) findViewById(f.lqt_cell_title); final sy syVar = new sy(); syVar.cdO.buF = "2"; syVar.bJX = new Runnable() { public final void run() { if (!bi.oW(syVar.cdP.cdQ)) { e.a(WalletBalanceManagerUI.this.oZM, syVar.cdP.cdQ, syVar.cdP.content, syVar.cdP.url); } } }; com.tencent.mm.sdk.b.a.sFg.m(syVar); } public void onResume() { aL(); bMV(); super.onResume(); b bVar = (b) com.tencent.mm.kernel.g.l(b.class); bVar.a(this, bVar.bRo(), null); } public final void aL() { boolean z; int i; String str = null; p.bNp(); this.paw = p.bNq().paw; if (this.paw != null) { if (this.paw.plV >= 0.0d) { this.pan.setText(e.B(this.paw.plV)); } else { this.pan.setText(getString(i.wallet_index_ui_default_balance)); } p.bNp(); if ((p.bNq().bPw().prx & 4) > 0) { z = true; } else { z = false; } x.i("MicroMsg.WalletSwitchConfig", "isBalanceFetchOn, ret = %s switchBit %s", new Object[]{Boolean.valueOf(z), Integer.valueOf(p.bNq().bPw().prx)}); i = (!z || this.paw.plV <= 0.0d) ? 0 : 1; if (i != 0) { this.pao.setVisibility(0); } else { this.pao.setVisibility(8); } bMX(); } View findViewById = findViewById(f.lqt_red_dot); com.tencent.mm.kernel.g.Ek(); if (((Integer) com.tencent.mm.kernel.g.Ei().DT().get(com.tencent.mm.storage.aa.a.sXO, Integer.valueOf(-1))).intValue() == 1) { findViewById.setVisibility(0); } else { findViewById.setVisibility(8); } if ((new ae().prx & 32768) > 0) { z = true; } else { z = false; } x.i("MicroMsg.WalletSwitchConfig", "isShowRealnameGuide, ret = %s switchBit %s", new Object[]{Boolean.valueOf(z), Integer.valueOf(new ae().prx)}); if (z) { com.tencent.mm.kernel.g.Ek(); String str2 = (String) com.tencent.mm.kernel.g.Ei().DT().get(com.tencent.mm.storage.aa.a.sTk, getString(i.realname_mgr_title)); this.pap.setVisibility(0); this.par.setTextColor(getResources().getColor(c.wallet_balance_manager_realname_tip)); this.par.setText(str2); this.paq.setVisibility(8); this.pap.setOnClickListener(new 11(this)); return; } CharSequence charSequence; CharSequence charSequence2; p.bNp(); ag bNq = p.bNq(); z = (bNq.prA != null ? bNq.prA.field_lqt_cell_is_show : 0) == 1; p.bNp(); ag bNq2 = p.bNq(); if (bNq2.prA != null) { charSequence = bNq2.prA.field_lqt_cell_lqt_title; } else { charSequence = null; } p.bNp(); ag bNq3 = p.bNq(); if (bNq3.prA != null) { charSequence2 = bNq3.prA.field_lqt_cell_lqt_wording; } else { charSequence2 = null; } x.i("MicroMsg.WalletBalanceManagerUI", "isShowLqtCell:%s lqtCellTitle:%s lqtCellWording:%s", new Object[]{Boolean.valueOf(z), charSequence, charSequence2}); if (!z || (bi.oW(charSequence) && bi.oW(charSequence2))) { this.pas.setVisibility(8); p.bNp(); if (p.bNq().bPC()) { this.pap.setVisibility(0); this.pap.setOnClickListener(new 14(this)); TextView textView = this.par; p.bNp(); textView.setText(p.bNq().bPz()); this.paq.setVisibility(0); return; } p.bNp(); bNq2 = p.bNq(); if (bNq2 != null) { if ((bNq2.bPw().prx & 1024) > 0) { z = true; } else { z = false; } x.i("MicroMsg.WalletSwitchConfig", "isSupportLCT, ret = %s switchBit %s", new Object[]{Boolean.valueOf(z), Integer.valueOf(bNq2.bPw().prx)}); if (!(!z || TextUtils.isEmpty(bNq2.bPz()) || TextUtils.isEmpty(bNq2.bPA()))) { this.pap.setVisibility(0); this.par.setText(bNq2.bPz()); this.paq.setVisibility(0); this.pap.setOnClickListener(new 2(this, bNq2)); return; } } this.pap.setVisibility(8); return; } this.pap.setVisibility(8); p.bNp(); bNq = p.bNq(); if (bNq.prA != null) { str = bNq.prA.field_lqt_cell_icon; } if (bi.oW(str)) { this.pat.setVisibility(8); } else { this.pat.setUrl(str); this.pat.setVisibility(0); } this.pau.setText(charSequence); this.pav.setText(charSequence2); p.bNp(); bNq = p.bNq(); if (bNq.prA != null) { i = bNq.prA.field_lqt_cell_is_open_lqt; } else { i = 0; } if (i == 1) { this.pav.setTextColor(getResources().getColor(c.black)); this.pas.setOnClickListener(new 12(this)); } else { this.pav.setTextColor(getResources().getColor(c.grey_text_color)); this.pas.setOnClickListener(new 13(this)); } this.pas.setVisibility(0); } private void bMX() { String str; JSONObject jSONObject; Throwable e; this.mController.removeAllOptionMenu(); JSONObject jSONObject2 = null; boolean z; try { str = (String) com.tencent.mm.kernel.g.Ei().DT().get(com.tencent.mm.storage.aa.a.sZr, ""); if (bi.oW(str)) { z = false; jSONObject = null; } else { jSONObject = new JSONObject(str); try { z = jSONObject.optBoolean("is_show_menu", false); } catch (JSONException e2) { e = e2; jSONObject2 = jSONObject; } } } catch (JSONException e3) { e = e3; x.printErrStackTrace("MicroMsg.WalletBalanceManagerUI", e, "", new Object[0]); z = false; jSONObject = jSONObject2; if (jSONObject == null) { } x.i("MicroMsg.WalletBalanceManagerUI", "go old menu logic"); p.bNp(); p.bNq(); str = this.paw.field_bindSerial; if (!bi.oW(this.paw.plY)) { a(getString(i.wallet_balance_manager_option_detail), (OnMenuItemClickListener) new 4(this), s.b.tng); } } if (jSONObject == null && z) { x.i("MicroMsg.WalletBalanceManagerUI", "go new menu logic"); addIconOptionMenu(0, h.actionbar_icon_dark_more, new 3(this, jSONObject, new ArrayList())); return; } x.i("MicroMsg.WalletBalanceManagerUI", "go old menu logic"); p.bNp(); p.bNq(); str = this.paw.field_bindSerial; if (!bi.oW(this.paw.plY)) { a(getString(i.wallet_balance_manager_option_detail), (OnMenuItemClickListener) new 4(this), s.b.tng); } } public boolean d(int i, int i2, String str, l lVar) { if (i == 0 && i2 == 0 && !(lVar instanceof com.tencent.mm.plugin.wallet.bind.a.b) && (lVar instanceof y)) { aL(); } return false; } public final void ss(int i) { p.bNp(); this.paw = p.bNq().paw; if (this.paw != null) { if (this.paw.plV >= 0.0d) { this.pan.setText(e.B(this.paw.plV)); } else { this.pan.setText(getString(i.wallet_index_ui_default_balance)); } bMX(); } } protected void onNewIntent(Intent intent) { x.i("MicroMsg.WalletBalanceManagerUI", "jumpFethProcess from bind ui flag:" + intent.getIntExtra("from_bind_ui", 0)); if (intent.getIntExtra("from_bind_ui", 0) == a.oYw) { com.tencent.mm.wallet_core.a.a((Activity) this, com.tencent.mm.plugin.wallet.balance.b.class, null, null); e.He(15); } } }
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.builder; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ArbeitsvorgangTypType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.LSCHNEIDSolldatenType; import java.io.StringWriter; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.namespace.QName; public class LSCHNEIDSolldatenTypeBuilder { public static String marshal(LSCHNEIDSolldatenType lSCHNEIDSolldatenType) throws JAXBException { JAXBElement<LSCHNEIDSolldatenType> jaxbElement = new JAXBElement<>(new QName("TESTING"), LSCHNEIDSolldatenType.class , lSCHNEIDSolldatenType); StringWriter stringWriter = new StringWriter(); return stringWriter.toString(); } private Boolean geaendertKz; private ArbeitsvorgangTypType arbeitsvorgang; public LSCHNEIDSolldatenTypeBuilder setGeaendertKz(Boolean value) { this.geaendertKz = value; return this; } public LSCHNEIDSolldatenTypeBuilder setArbeitsvorgang(ArbeitsvorgangTypType value) { this.arbeitsvorgang = value; return this; } public LSCHNEIDSolldatenType build() { LSCHNEIDSolldatenType result = new LSCHNEIDSolldatenType(); result.setGeaendertKz(geaendertKz); result.setArbeitsvorgang(arbeitsvorgang); return result; } }
package com.pel.mathias.merob; import android.content.Context; import android.content.IntentFilter; import android.net.wifi.p2p.WifiP2pDevice; import android.net.wifi.p2p.WifiP2pDeviceList; import android.net.wifi.p2p.WifiP2pGroup; import android.net.wifi.p2p.WifiP2pInfo; import android.net.wifi.p2p.WifiP2pManager; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import com.pel.mathias.merob.MainActivity; import com.pel.mathias.merob.WiFiDirectBroadcastReceiver; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.Collection; /** * Created by Mathias on 18/12/2015. */ public class CreateAP extends Thread{ private String SSID; private String passphrase; private InetAddress IP_adress; private WifiP2pManager mManager; private WifiP2pManager.Channel mChannel; private WiFiDirectBroadcastReceiver mReceiver; private IntentFilter mIntentFilter; private Collection<WifiP2pDevice> deviceList; private MainActivity main; private TextView textssid,textpass,textip; CreateAP(MainActivity main, TextView textssid, TextView textpass,TextView textip){ this.main=main; this.textssid=textssid; this.textpass=textpass; this.textip=textip; } @Override public void run() { super.run(); mManager = (WifiP2pManager) main.getSystemService(Context.WIFI_P2P_SERVICE); mChannel = mManager.initialize(main, main.getMainLooper(), null); mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, main); mIntentFilter = new IntentFilter(); mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION); mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION); mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION); mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION); mManager.createGroup(mChannel, null); mManager.requestGroupInfo(mChannel, new WifiP2pManager.GroupInfoListener() { @Override public void onGroupInfoAvailable(WifiP2pGroup group) { SSID = group.getNetworkName(); passphrase = group.getPassphrase(); Log.d("test group", "ssid:" + SSID + " passphrase:" + passphrase); main.runOnUiThread(new Runnable() { @Override public void run() { textssid.setText("SSID: " + SSID); textpass.setText("Passphrase: " + passphrase); } }); } }); mManager.requestConnectionInfo(mChannel, new WifiP2pManager.ConnectionInfoListener() { @Override public void onConnectionInfoAvailable(WifiP2pInfo info) { IP_adress = info.groupOwnerAddress; main.runOnUiThread(new Runnable() { @Override public void run() { textip.setText("IP: " + IP_adress.toString()); } }); } }); mManager.discoverPeers(mChannel, null); try { sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } deviceList=mReceiver.getDeviceList(); } public Collection<WifiP2pDevice> getDeviceList() { return deviceList; } public void resume_connect() { main.registerReceiver(mReceiver, mIntentFilter); } public void pause_connect(){ main.unregisterReceiver(mReceiver); } }
// Sun Certified Java Programmer // Chapter 2, P143 // Object Orientation public class Tester143 { public static void main(String[] args) { //A a = new A(); //a.go(); } }
/* 문제 설명 n개의 음이 아닌 정수가 있습니다. 이 수를 적절히 더하거나 빼서 타겟 넘버를 만들려고 합니다. 예를 들어 [1, 1, 1, 1, 1]로 숫자 3을 만들려면 다음 다섯 방법을 쓸 수 있습니다. -1+1+1+1+1 = 3 +1-1+1+1+1 = 3 +1+1-1+1+1 = 3 +1+1+1-1+1 = 3 +1+1+1+1-1 = 3 사용할 수 있는 숫자가 담긴 배열 numbers, 타겟 넘버 target이 매개변수로 주어질 때 숫자를 적절히 더하고 빼서 타겟 넘버를 만드는 방법의 수를 return 하도록 solution 함수를 작성해주세요. 제한사항 주어지는 숫자의 개수는 2개 이상 20개 이하입니다. 각 숫자는 1 이상 50 이하인 자연수입니다. 타겟 넘버는 1 이상 1000 이하인 자연수입니다. 입출력 예 numbers target return [1, 1, 1, 1, 1] 3 5 입출력 예 설명 문제에 나온 예와 같습니다. */ package programmers; public class Lessons43165 { public int solution(int[] numbers, int target) { int answer = 0; answer += combination(numbers[0], 1, numbers, target); answer += combination(numbers[0] * -1, 1, numbers, target); return answer; } public int combination(int sum, int index, int[] numbers, int target){ if(index == numbers.length){ if(sum == target) return 1; return 0; } return combination(sum + numbers[index], index + 1, numbers, target) + combination(sum - numbers[index], index + 1, numbers, target); } }
package com.lingnet.vocs.action.leaguer; import javax.annotation.Resource; import com.lingnet.common.action.BaseAction; import com.lingnet.qxgl.entity.QxUsers; import com.lingnet.util.JsonUtil; import com.lingnet.vocs.service.leaguer.LeaguerService; /** * 会员信息管理 * * @ClassName: LeaguerAction * @Description: TODO * @author wanl * @date 2017年7月8日 下午5:44:21 * */ @SuppressWarnings("all") public class LeaguerAction extends BaseAction { private static final long serialVersionUID = -7368057178862917623L; @Resource(name = "leaguerService") private LeaguerService leaguerService; // @Resource(name = "leaguerDao") // private LeaguerDao leaguerDao; private String formdata; private QxUsers qxUsers; public String list() { return LIST; } public String getListData() { if (id == null || "-1".equals(id)) { id = this.getSession("partnerId").toString(); } return ajax(Status.success, leaguerService.getListData(pager, id)); } public String edit() { qxUsers = this.getBeanById(QxUsers.class, id); return ADD; } public String look() { qxUsers = this.getBeanById(QxUsers.class, id); return "look"; } public String saveOrUpdate() { qxUsers = JsonUtil.toObject(formdata, QxUsers.class); operate("会员信息管理", "会员信息编辑", qxUsers.getCode()); try { return ajax(Status.success, leaguerService.saveOrUpdate(qxUsers)); } catch (Exception e) { return ajax(Status.error, e.getMessage()); } } /********************************************************* get Set ***************************************************/ public QxUsers getQxUsers() { return qxUsers; } public void setQxUsers(QxUsers qxUsers) { this.qxUsers = qxUsers; } public String getFormdata() { return formdata; } public void setFormdata(String formdata) { this.formdata = formdata; } }
package net.iz44kpvp.kitpvp.Kits; import java.util.HashMap; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.plugin.Plugin; import net.iz44kpvp.kitpvp.Main; import net.iz44kpvp.kitpvp.Sistemas.API; import net.iz44kpvp.kitpvp.Sistemas.Habilidade; public class Trader extends TraderUtil implements Listener { public static HashMap<String, Integer> coin; static { Trader.coin = new HashMap<String, Integer>(); } public static void setCoinTrader(final Player p, final int quantidade) { if (!Trader.coin.containsKey(p.getName())) { Trader.coin.put(p.getName(), 0); } else { Trader.coin.put(p.getName(), Trader.coin.get(p.getName()) + quantidade); } } public static void removeCoinTrader(final Player p, final int quantidade) { Trader.coin.put(p.getName(), Trader.coin.get(p.getName()) - quantidade); } public static int getCoinsTrader(final Player p) { if (!Trader.coin.containsKey(p.getName())) { Trader.coin.put(p.getName(), 0); } return Trader.coin.get(p.getName()); } public static boolean getTrader(final Player p, final int quantidade) { return getCoinsTrader(p) >= quantidade; } public static void InvTrader(final Player p) { final Inventory inv = Bukkit.createInventory((InventoryHolder) null, 9, "§aLoja§7(§eTrader§7)"); API.darItemInv(inv, Material.IRON_SWORD, 1, 0, "§7Pre\u00e7o: §66 Coins", 0); API.darItemInv(inv, Material.LEATHER_HELMET, 1, 0, "§7Pre\u00e7o: §64 Coins", 1); API.darItemInv(inv, Material.IRON_CHESTPLATE, 1, 0, "§7Pre\u00e7o: §67 Coins", 2); API.darItemInv(inv, Material.LEATHER_LEGGINGS, 1, 0, "§7Pre\u00e7o: §64 Coins", 3); API.darItemInv(inv, Material.IRON_BOOTS, 1, 0, "§7Pre\u00e7o: §65 Coins", 4); API.darItemInv(inv, Material.POTION, 1, 16428, "§7Pre\u00e7o: §62 Coins", 5); API.darItemInv(inv, Material.POTION, 1, 8265, "§7Pre\u00e7o: §63 Coins", 6); API.darItemInv(inv, Material.STAINED_GLASS_PANE, 1, 5, " ", 7); Bukkit.getScheduler().scheduleSyncRepeatingTask((Plugin) Main.instance, (Runnable) new Runnable() { @Override public void run() { API.darItemInv(inv, Material.EMERALD, 1, 0, "§7Coins: §6" + Trader.getCoinsTrader(p), 8); } }, 0L, 20L); p.openInventory(inv); } @EventHandler public void aotrader(final PlayerInteractEvent e) { final Player p = e.getPlayer(); if (Habilidade.getAbility(p).equalsIgnoreCase("Trader") && (e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.RIGHT_CLICK_BLOCK) && p.getItemInHand().getType() == Material.ENDER_CHEST) { InvTrader(p); } } @EventHandler public void aocomprar(final InventoryClickEvent e) { final Player p = (Player) e.getWhoClicked(); if (e.getInventory().getTitle().equalsIgnoreCase("§aLoja§7(§eTrader§7)") && e.getCurrentItem() != null && e.getCurrentItem().getTypeId() != 0) { if (e.getCurrentItem().getType() == Material.EMERALD) { e.setCancelled(true); return; } if (e.getCurrentItem().getType() == Material.STAINED_GLASS_PANE) { e.setCancelled(true); return; } if (e.getCurrentItem().getType() == Material.IRON_SWORD) { e.setCancelled(true); if (getTrader(p, 6)) { removeCoinTrader(p, 6); TraderUtil.darItemTroca(p, Material.IRON_SWORD, 0); } else { TraderUtil.MsgSemTrader(p); } return; } if (e.getCurrentItem().getType() == Material.LEATHER_HELMET) { e.setCancelled(true); if (getTrader(p, 4)) { removeCoinTrader(p, 4); TraderUtil.darItemTroca(p, Material.LEATHER_HELMET, 0); } else { TraderUtil.MsgSemTrader(p); } return; } if (e.getCurrentItem().getType() == Material.IRON_CHESTPLATE) { e.setCancelled(true); if (getTrader(p, 7)) { removeCoinTrader(p, 7); TraderUtil.darItemTroca(p, Material.IRON_CHESTPLATE, 0); } else { TraderUtil.MsgSemTrader(p); } return; } if (e.getCurrentItem().getType() == Material.LEATHER_LEGGINGS) { e.setCancelled(true); if (getTrader(p, 4)) { removeCoinTrader(p, 4); TraderUtil.darItemTroca(p, Material.LEATHER_LEGGINGS, 0); } else { TraderUtil.MsgSemTrader(p); } return; } if (e.getCurrentItem().getType() == Material.IRON_BOOTS) { e.setCancelled(true); if (getTrader(p, 5)) { removeCoinTrader(p, 5); TraderUtil.darItemTroca(p, Material.LEATHER_HELMET, 0); } else { TraderUtil.MsgSemTrader(p); } return; } if (e.getCurrentItem().getItemMeta().getDisplayName().equalsIgnoreCase("§7Pre\u00e7o: §62 Coins")) { e.setCancelled(true); if (getTrader(p, 2)) { removeCoinTrader(p, 2); TraderUtil.darItemTroca(p, Material.POTION, 16428); } else { TraderUtil.MsgSemTrader(p); } return; } if (e.getCurrentItem().getItemMeta().getDisplayName().equalsIgnoreCase("§7Pre\u00e7o: §63 Coins")) { e.setCancelled(true); if (getTrader(p, 3)) { removeCoinTrader(p, 3); TraderUtil.darItemTroca(p, Material.POTION, 8265); } else { TraderUtil.MsgSemTrader(p); } } } } @EventHandler public void aomatar(final PlayerDeathEvent e) { if (e.getEntity().getKiller() instanceof Player) { final Player matou = e.getEntity().getKiller(); final Player morreu = e.getEntity(); if (Habilidade.getAbility(morreu).equalsIgnoreCase("Trader")) { Trader.coin.remove(morreu.getName()); } if (Habilidade.getAbility(matou).equalsIgnoreCase("Trader")) { setCoinTrader(matou, 1); } } } }
package at.xirado.bean.misc.objects; import com.fasterxml.jackson.annotation.JsonProperty; import net.dv8tion.jda.api.utils.data.DataObject; import java.io.Serializable; public class RoleReward implements Serializable { @JsonProperty("level") private int level; @JsonProperty("role_id") private long roleId; @JsonProperty("persists") private boolean persist; @JsonProperty("remove_on_next_reward") private boolean removeOnNextReward; public RoleReward(int level, long roleId, boolean persist, boolean removeOnNextReward) { this.level = level; this.roleId = roleId; this.persist = persist; this.removeOnNextReward = removeOnNextReward; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public long getRoleId() { return roleId; } public void setRoleId(long roleId) { this.roleId = roleId; } public boolean isPersistant() { return persist; } public void setPersist(boolean persist) { this.persist = persist; } public boolean doesRemoveOnNextReward() { return removeOnNextReward; } public void setRemoveOnNextReward(boolean removeOnNextReward) { this.removeOnNextReward = removeOnNextReward; } public static RoleReward fromData(DataObject object) { return new RoleReward(object.getInt("level"), object.getLong("role_id"), object.isNull("persistant") ? object.getBoolean("persists") : object.getBoolean("persistant"), object.getBoolean("remove_on_next_reward")); } }
package com.tencent.mm.modelrecovery; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import com.tencent.mm.g.a.my; import com.tencent.mm.kernel.api.bucket.c; import com.tencent.mm.kernel.b.f; import com.tencent.mm.kernel.b.g; import com.tencent.mm.kernel.e; import com.tencent.mm.modelsfs.FileOp; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.d; import com.tencent.mm.sdk.platformtools.x; import com.tencent.recovery.RecoveryContext; import com.tencent.recovery.RecoveryLogic; import com.tencent.recovery.log.RecoveryLog; import com.tencent.recovery.log.RecoveryLog.RecoveryLogImpl; import com.tencent.recovery.option.CommonOptions.Builder; import com.tencent.recovery.wx.WXConstantsRecovery; import com.tencent.recovery.wx.service.WXRecoveryHandleService; import com.tencent.recovery.wx.service.WXRecoveryUploadService; import com.tencent.recovery.wx.util.WXUtil; import java.io.File; public class PluginRecovery extends f implements c { private com.tencent.mm.sdk.b.c<my> edh = new com.tencent.mm.sdk.b.c<my>() { { this.sFo = my.class.getName().hashCode(); } private static boolean a(my myVar) { Context context; Builder builder; switch (myVar.bYa.action) { case 1: context = ad.getContext(); builder = new Builder(); builder.vhz = WXRecoveryHandleService.class.getName(); builder.vhA = WXRecoveryUploadService.class.getName(); builder.clientVersion = d.CLIENT_VERSION; builder.vhv = String.format("file:///sdcard/test-recovery.conf", new Object[0]); builder.fMk = WXUtil.hp(context); RecoveryLogic.a(context, builder.cEZ(), new RecoveryContext()); break; case 2: a.Qr(); break; case 3: context = ad.getContext(); builder = new Builder(); builder.vhz = WXRecoveryHandleService.class.getName(); builder.vhA = WXRecoveryUploadService.class.getName(); builder.clientVersion = d.CLIENT_VERSION; builder.vhv = "http://dldir1.qq.com/weixin/android/recovery-0x26032011.conf"; builder.fMk = WXUtil.hp(context); RecoveryLogic.a(context, builder.cEZ(), new RecoveryContext()); break; } return false; } }; private RecoveryLogImpl edi = new 5(this); private BroadcastReceiver rj = new BroadcastReceiver() { public final void onReceive(Context context, Intent intent) { if (intent == null) { return; } if ("com.tecent.recovery.intent.action.LOG".equals(intent.getAction())) { PluginRecovery.this.postLog(); } else if ("com.tecent.mm.intent.action.RECOVERY_STATUS_UPLOAD".equals(intent.getAction())) { PluginRecovery.this.postReport(); } } }; public void configure(g gVar) { RecoveryLog.a(this.edi); if (gVar.gn(":sandbox")) { long currentTimeMillis = System.currentTimeMillis(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("com.tecent.recovery.intent.action.LOG"); intentFilter.addAction("com.tecent.mm.intent.action.RECOVERY_STATUS_UPLOAD"); ad.getContext().registerReceiver(this.rj, intentFilter); File file = new File(WXConstantsRecovery.vhL); if (!file.exists()) { file.mkdir(); } File file2 = new File(file, "version.info"); if (file2.exists()) { file2.delete(); } try { FileOp.l(file2.getAbsolutePath(), Integer.toHexString(com.tencent.mm.protocal.d.qVN).getBytes()); } catch (Exception e) { } x.i("MicroMsg.Recovery.PluginRecovery", "add recovery intent filter and save client verison file %d", new Object[]{Long.valueOf(System.currentTimeMillis() - currentTimeMillis)}); } } public void execute(g gVar) { } public void onAccountInitialized(e.c cVar) { this.edh.cht(); } public void onAccountRelease() { this.edh.dead(); } private void postLog() { com.tencent.mm.sdk.f.e.post(new Runnable() { public final void run() { x.i("MicroMsg.Recovery.PluginRecovery", "postLog"); a.Qr(); } }, "RecoveryWriteLogThread"); } private void postReport() { com.tencent.mm.sdk.f.e.post(new Runnable() { public final void run() { x.i("MicroMsg.Recovery.PluginRecovery", "postReport"); b.Qs(); } }, "RecoveryReportStatusThread"); } }
package controllers; import play.mvc.Controller; import java.util.List; public class Article extends Controller { public static void view(long id) { models.Article article = models.Article.findById(id); render(article); } public static void list() { List<models.Article> articles = models.Article.findAll(); render(articles); } public static void articlePhoto(long id) { models.Article article = models.Article.findById(id); notFoundIfNull(article); response.setContentTypeIfNotSet(article.image.type()); renderBinary(article.image.get()); } }
package com.ingenico.pay.test; import com.ingenico.pay.dto.AccountDto; import com.ingenico.pay.service.AccountService; import com.ingenico.pay.service.TransferService; import org.junit.Assert; 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.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import java.util.logging.Logger; /** * Created by mohamedtantawy on 10/18/17. */ @RunWith(SpringRunner.class) @SpringBootTest public class ConcurrentTransferRestServiceTest { private static final Logger logger = Logger.getLogger(ConcurrentTransferRestServiceTest.class.getSimpleName()); @Autowired WebApplicationContext webApplicationContext; @Autowired AccountService accountService; @Autowired TransferService transferService; MockMvc mockMvc; private static AccountDto accountDto1; private static AccountDto accountDto2; String accountName1 = "account 1"; String accountName2 = "account 2"; double balance = 1000d; double amount = 10d; /** * setup the env and create two vitrual accounts with initial balance @balance */ @Before public void setup() { mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); accountDto1 = accountService.create(accountName1, balance); accountDto2 = accountService.create(accountName2, balance); } /* * trying to make multiple transfer from @accountDto1 to @accountDto2 by @amount */ @Test public void makeTransfer() throws Exception { for (int i = 0; i < 100; i++) { new Thread("thread 1->2 [" + i+"]") { @Override public void run() { transferService.validateAccountAndDoTransfer(accountDto1.getId(), accountDto2.getId(), amount); } }.start(); } Thread.sleep(5000); AccountDto account2 = accountService.find(accountDto2.getId()); Assert.assertEquals( accountDto1.getBalance()+accountDto2.getBalance(),account2.getBalance(),0.0); } }
package com.tencent.mm.plugin.fav.ui.detail; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import com.tencent.mm.plugin.fav.a.m; import com.tencent.mm.plugin.fav.a.m.a; class FavoriteFileDetailUI$8 implements OnMenuItemClickListener { final /* synthetic */ FavoriteFileDetailUI jcx; FavoriteFileDetailUI$8(FavoriteFileDetailUI favoriteFileDetailUI) { this.jcx = favoriteFileDetailUI; } public final boolean onMenuItemClick(MenuItem menuItem) { m.a(a.iWn, FavoriteFileDetailUI.b(this.jcx)); this.jcx.finish(); return true; } }
package it.htm; import it.htm.dao.UserDao; import it.htm.dao.UserDaoImpl; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication public class HackathonApplication { public static void main(String[] args) { SpringApplication.run(HackathonApplication.class, args); UserDaoImpl userDao = new UserDaoImpl(); userDao.insertUser(); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.pinchofintelligence.duolingoemersion.duolingo; import java.util.ArrayList; /** * * @author Roland */ public class UserRepresentation { private String username; public ArrayList<LanguageWithWords> knownLanguagesWithWords ; private String languageLearning; public UserRepresentation() { knownLanguagesWithWords = new ArrayList<LanguageWithWords>(); } public UserRepresentation(String username) { this.username = username; } public String getUsername() { return username; } public String getLanguageLearning() { return languageLearning; } void setLanguageLearning(String nameLanguage) { this.languageLearning = nameLanguage; } }
public class Monster { private String name; public Monster(String name) { this.name = name; } public String attack() { return "RAWR KAIJU CAT 5"; } }
package com.hesoyam.pharmacy.user.model; public enum RoleEnum { NONE, PATIENT, PHARMACIST, DERMATOLOGIST, ADMINISTRATOR, SYS_ADMIN, SUPPLIER; }
package br.com.scd.demo.session; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.springframework.test.util.ReflectionTestUtils; import br.com.scd.demo.session.Session; import br.com.scd.demo.session.SessionEntity; import br.com.scd.demo.session.SessionFactory; import br.com.scd.demo.topic.TopicEntity; public class SessionFactoryTest { @Test public void shouldCreateInstance() { TopicEntity topicEntity = new TopicEntity(); ReflectionTestUtils.setField(topicEntity, "id", 45l); SessionEntity sessionEntity = new SessionEntity(); ReflectionTestUtils.setField(sessionEntity, "id", 20l); sessionEntity.setDurationInMinutes(10); sessionEntity.setTopic(topicEntity); Session session = SessionFactory.getInstance(sessionEntity); assertEquals("10", session.getDurationInMinutes().toString()); assertEquals("45", session.getTopicId().toString()); assertEquals("20", session.getId().toString()); } }
package BD; import java.sql.*; import UML.Perfil; import BD.BaseDatos; import java.util.ArrayList; import javax.swing.JOptionPane; public class tablaPerfiles { private static Connection con; public static void crearPerfil (Perfil perfil) throws Exception{ BaseDatos.conectar(); con = BaseDatos.getCon(); String plantilla = "INSERT INTO PERFILES VALUES (?,?,?,?)"; PreparedStatement ps = con.prepareStatement(plantilla); ps.setInt(1, perfil.getIdPerfil()); ps.setString(2, perfil.getUsuario()); ps.setString(3, perfil.getPasswd()); ps.setString(4, perfil.getPrivilegios()); int n = ps.executeUpdate(); ps.close(); if (n!=1) throw new Exception ("Error. Se ha creado más de un perifl"); System.out.println("Perfil creado con éxito"); BaseDatos.desconectar(); } public static void eliminarPerfil (String id) throws Exception{ BaseDatos.conectar(); con = BaseDatos.getCon(); String plantilla = "DELETE FROM EQUIPOS WHERE IDEQUIPO=?"; PreparedStatement ps = con.prepareStatement(plantilla); ps.setString(1, id); int n = ps.executeUpdate(); ps.close(); System.out.println("Perfil eliminado correctamente"); BaseDatos.desconectar(); } public static void eliminarPerfil (Perfil perfil) throws Exception{ BaseDatos.conectar(); con = BaseDatos.getCon(); String plantilla = "DELETE FROM EQUIPOS WHERE IDEQUIPO=?"; PreparedStatement ps = con.prepareStatement(plantilla); ps.setInt(1, perfil.getIdPerfil()); int n = ps.executeUpdate(); ps.close(); System.out.println("Perfil eliminado correctamente"); BaseDatos.desconectar(); } public static Perfil validarLogin (Perfil perfil) throws Exception{ BaseDatos.conectar(); con = BaseDatos.getCon(); String plantilla = "SELECT * FROM PERFILES WHERE USER=? AND PASSWD=?"; PreparedStatement ps = con.prepareStatement(plantilla); ps.setString(1, perfil.getUsuario()); ps.setString(2, perfil.getPasswd()); ResultSet resultado = ps.executeQuery(); Perfil perfilActual = new Perfil(); if(resultado.next()){ perfilActual.setIdPerfil(resultado.getInt("IDPERFIL")); perfilActual.setUsuario(resultado.getString("USUARIO")); perfilActual.setPasswd(resultado.getString("PASSWD")); if(resultado.getString("PRIVILEGIO").equalsIgnoreCase("ADMIN")){ perfilActual.setPrivilegiosAdmin(); } else{ perfilActual.setPrivilegiosUser(); } BaseDatos.desconectar(); return perfilActual; }else{ BaseDatos.desconectar(); return null; } } public static Perfil PerfilByIdPerfil (String id) throws Exception{ BaseDatos.conectar(); con = BaseDatos.getCon(); String plantilla = "SELECT * FROM PERFILES WHERE IDPERFIL=?"; PreparedStatement ps = con.prepareStatement(plantilla); ps.setString(1, id); ResultSet resultado = ps.executeQuery(); if(resultado.next()){ Perfil perfilActual = new Perfil(); perfilActual.setIdPerfil(resultado.getInt("IDPERFIL")); perfilActual.setUsuario(resultado.getString("USUARIO")); perfilActual.setPasswd(resultado.getString("PASSWD")); if(resultado.getString("PRIVILEGIO").equalsIgnoreCase("ADMIN")){ perfilActual.setPrivilegiosAdmin(); } else{ perfilActual.setPrivilegiosUser(); } BaseDatos.desconectar(); return perfilActual; } else{ return null; } } public static Perfil PerfilByIdPerfil (Perfil perfil) throws Exception{ BaseDatos.conectar(); con = BaseDatos.getCon(); String plantilla = "SELECT * FROM PERFILES WHERE IDPERFIL=?"; PreparedStatement ps = con.prepareStatement(plantilla); ps.setInt(1, perfil.getIdPerfil()); ResultSet resultado = ps.executeQuery(); if(resultado.next()){ Perfil perfilActual = new Perfil(); perfilActual.setIdPerfil(resultado.getInt("IDPERFIL")); perfilActual.setUsuario(resultado.getString("USUARIO")); perfilActual.setPasswd(resultado.getString("PASSWD")); if(resultado.getString("PRIVILEGIO").equalsIgnoreCase("ADMIN")){ perfilActual.setPrivilegiosAdmin(); } else{ perfilActual.setPrivilegiosUser(); } BaseDatos.desconectar(); return perfilActual; } else{ BaseDatos.desconectar(); return null; } } public static ArrayList<Perfil> allPerfil() throws Exception{ BaseDatos.conectar(); con = BaseDatos.getCon(); String plantilla = "SELECT * FROM PERFILES"; PreparedStatement ps = con.prepareStatement(plantilla); ResultSet resultado = ps.executeQuery(); ArrayList<Perfil> listaPerfiles = new ArrayList(); while(resultado.next()){ Perfil perfilActual = new Perfil(); perfilActual.setIdPerfil(resultado.getInt("IDPERFIL")); perfilActual.setUsuario(resultado.getString("USUARIO")); perfilActual.setPasswd(resultado.getString("PASSWD")); if(resultado.getString("PRIVILEGIO").equalsIgnoreCase("ADMIN")){ perfilActual.setPrivilegiosAdmin(); } else{ perfilActual.setPrivilegiosUser(); } listaPerfiles.add(perfilActual); } if(!listaPerfiles.isEmpty()){ BaseDatos.desconectar(); return listaPerfiles; } else{ BaseDatos.desconectar(); JOptionPane.showMessageDialog(null, "No hay perfiles creados en la BD"); return null; } } public static void modUsuarioPerfil (Perfil perfil) throws Exception{ BaseDatos.conectar(); con = BaseDatos.getCon(); String plantilla = "UPDATE PERFILES SET USUARIO=? WHERE IDPERFIL=?"; PreparedStatement ps = con.prepareStatement(plantilla); ps.setString(1, perfil.getUsuario()); ps.setInt(2, perfil.getIdPerfil()); int n = ps.executeUpdate(); if (n!=1) throw new Exception ("Se ha modificado más de un perfil"); System.out.println("Perfil modificado con éxito"); BaseDatos.desconectar(); } public static void modPassPerfil (Perfil perfil) throws Exception{ BaseDatos.conectar(); con = BaseDatos.getCon(); String plantilla = "UPDATE PERFILES SET PASSWD=? WHERE IDPERFIL=?"; PreparedStatement ps = con.prepareStatement(plantilla); ps.setString(1, perfil.getPasswd()); ps.setInt(2, perfil.getIdPerfil()); int n = ps.executeUpdate(); if (n!=1) throw new Exception ("Se ha modificado más de un perfil"); System.out.println("Perfil modificado con éxito"); BaseDatos.desconectar(); } }
package combination; import java.util.HashMap; /** * Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. * <p> * For example, given s = "leetcode", dict = ["leet", "code"]. * <p> * Return true because "leetcode" can be segmented as "leet code". */ public class WordBreak { public boolean wordBreak(String s) { boolean[] f = new boolean[s.length() + 1]; f[0] = true; /* First DP for(int i = 1; i <= s.length(); i++){ for(String str: dict){ if(str.length() <= i){ if(f[i - str.length()]){ if(s.substring(i-str.length(), i).equals(str)){ f[i] = true; break; } } } } }*/ //Second DP for (int i = 1; i <= s.length(); i++) { for (int j = 0; j < i; j++) { if (f[j] && dict.containsKey(s.substring(j, i))) { f[i] = true; break; } } } for (int i = 1; i < f.length; i++) { System.out.println("s.charAt(i) = " + s.charAt(i-1)); System.out.println("f[i] = " + f[i]); } return f[s.length()]; } HashMap<String, Boolean> dict = new HashMap<>(); { dict.put("leet", true); dict.put("code", true); dict.put("he", true); dict.put("hell", true); dict.put("hello", true); dict.put("h", true); dict.put("world", true); } void toWords(StringBuilder result, String temp, String input, int index) { if (dict.containsKey(temp)) { result.append(" "); result.append(temp); System.out.println("temp = " + temp); if (index == input.length()) { System.out.println("result = " + result.toString()); } temp = ""; } if (index == input.length()) { return; } for (int i = index; i < input.length(); i++) { String s = temp + input.charAt(i); toWords(result, s, input, index + 1); } } public static void main(String[] args) { String input = "helloworld"; boolean wordBreak = new WordBreak().wordBreak(input); System.out.println("wordBreak = " + wordBreak); } }
public class CustomCheckedException extends Exception { public CustomCheckedException() { System.out.println("CustomCheckedException"); } public CustomCheckedException(String ex) { System.out.println(ex); } public CustomCheckedException(Exception ex) { } }
package Kursach.Comparators; /** * Created by skyll on 23.05.2016. */ public enum Order { ASC, DESC; }
package com.example.proiectdam_serbansorinaalexandra.Data; import android.os.Parcel; import android.os.Parcelable; import androidx.annotation.NonNull; import androidx.room.Entity; import androidx.room.PrimaryKey; @Entity(tableName = "users") public class User implements Parcelable { @PrimaryKey(autoGenerate = true) public int id; public String username; public String password; public String firstName; public String lastName; public String email; public User() { } public User(String username, String password, String firstName, String lastName, String email) { this.username = username; this.password = password; this.firstName = firstName; this.lastName = lastName; this.email = email; } protected User(Parcel in) { id = in.readInt(); password = in.readString(); email = in.readString(); firstName = in.readString(); lastName = in.readString(); username = in.readString(); } public static final Creator<User> CREATOR = new Creator<User>() { @Override public User createFromParcel(Parcel in) { return new User(in); } @Override public User[] newArray(int size) { return new User[size]; } }; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public int describeContents() {return 0;} @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeInt(id); parcel.writeString(username); parcel.writeString(password); parcel.writeString(email); parcel.writeString(firstName); parcel.writeString(lastName); } @NonNull @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + '}'; } }
package Utils; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Date; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class SpiderUtil { public static String getHtml() throws IOException { HttpURLConnection connection = null; URL url = new URL("http://www.mzitu.com/86712"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(8000); connection.setReadTimeout(8000); InputStream in = connection.getInputStream(); /* 下面对获取到的输入流进行读取 */ BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } System.out.println(response.toString()); return response.toString(); } public static void getHtmlByJsoup() throws IOException { int i =1; String url = "http://www.mzitu.com/86712"; Document doc = Jsoup.connect(url+"/"+i).get(); Elements imageDiv = doc.getElementsByClass("meta-images"); // System.out.println(doc); Elements allsrc = doc.getElementsByTag("img"); String src = allsrc.attr("src"); if(!src.isEmpty()){ i++; } } public static String getSrc(String url) throws IOException{ Document doc = Jsoup.connect(url).get(); Elements imageDiv = doc.getElementsByClass("meta-images"); Elements allsrc = doc.getElementsByTag("img"); String src = allsrc.attr("src"); System.out.println(src); return src; } public static void getAllSrc() throws IOException{ int i = 1; String url = "http://www.mzitu.com/86712/1"; int lastnumber = url.indexOf("m")+16; int beginnumber = url.indexOf("h"); System.out.println(beginnumber); System.out.println(lastnumber); System.out.println(url.substring(beginnumber, lastnumber)+i); String realurl = url.substring(beginnumber, lastnumber)+i; while(!getSrc(realurl).isEmpty()){ i++; System.out.println(url); System.out.println(getSrc(url)); } } public static void saveImage(ArrayList<String> urls) throws Exception{ System.out.println("开始下载!"); File file = new File("D:\\pic"); URLConnection imageconnection = null ; InputStream imageInputStream=null; for(String url:urls){ URL oneurl = new URL(url); try{ imageconnection = oneurl.openConnection(); imageInputStream = imageconnection.getInputStream(); }catch(Exception e){ System.out.println("下载失败"); continue; } if (!file.exists()) { file.mkdir(); } OutputStream imageoutputStream = new FileOutputStream(new File("D:\\pic\\" + new Date().getTime() + ".jpg")); byte[] b = new byte[2048]; int len = 0; while ((len = imageInputStream.read(b)) != -1) { imageoutputStream.write(b, 0, len); } } System.out.println("下载完成"); } } //int lastnumber = src.indexOf("m")+16; //int beginnumber = src.indexOf("h"); //String realurl = src.substring(beginIndex)
package com.steinshuh.tut; // https://wiki.mcjty.eu/modding/index.php?title=Basic_Mod-1.12 import java.util.HashSet; import org.apache.logging.log4j.Logger; import com.steinshuh.tut.blocks.ModBlocks; import com.steinshuh.tut.items.ModItems; import com.steinshuh.tut.proxy.CommonProxy; import net.minecraft.block.Block; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.item.Item; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.registries.IForgeRegistry; @Mod(modid=Ref.MODID, name=Ref.NAME, version=Ref.VERSION) @Mod.EventBusSubscriber public class TutorialMod { public static Logger logger; @Mod.Instance public static TutorialMod instance; @SidedProxy(clientSide=Ref.CLIENT_PROXY, serverSide=Ref.SERVER_PROXY) public static CommonProxy proxy; @Mod.EventHandler public void preInit(FMLPreInitializationEvent event){ System.out.println("TutorialMod.preInit"); logger=event.getModLog(); proxy.preInit(event); } @Mod.EventHandler public void init(FMLInitializationEvent event){ System.out.println("TutorialMod.init"); proxy.init(event); } @Mod.EventHandler public void postInit(FMLPostInitializationEvent event){ System.out.println("TutorialMod.postInit"); proxy.postInit(event); } @SubscribeEvent public static void registerBlocks(RegistryEvent.Register<Block> event) { System.out.println("TutorialMod.registerBlocks"); ModBlocks.registerBlocks(event); } @SubscribeEvent public static void registerItems(RegistryEvent.Register<Item> event) { System.out.println("TutorialMod.registerItems"); ModBlocks.registerItems(event); ModItems.registerItems(event); } @SideOnly(Side.CLIENT) @SubscribeEvent public static void onRegisterModels(ModelRegistryEvent event) { System.out.println("TutorialMod.onRegisterModels"); ModBlocks.onRegisterModels(event); ModItems.onRegisterModels(event); } }
/* * 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 controller; import com.google.gson.Gson; import connection.DBConnection; import dto.LoanDTO; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import service.LoanService; /** * * @author sashika */ public class LoanController extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException,ClassNotFoundException,SQLException,Exception { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { String type = request.getParameter("type"); DBConnection dBConnection = new DBConnection(); Connection connection = dBConnection.getConnection(); LoanService loanService = new LoanService(); //Class.forName("com.mysql.jdbc.Driver"); //Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/sri_lanka_cricket","root",""); if ("empid".equals(type)) { String name = request.getParameter("name"); boolean empIdExcist = loanService.isEmpIdExcist(name, connection); response.setContentType("text/plain"); response.getWriter().write("" + empIdExcist); } /*if ("view".equals(type)) { String loanId = request.getParameter("loanId"); LoanService loanService = new LoanService(); LoanDTO result = loanService.getLoanByLoanId(loanId, connection); Gson gson = new Gson(); String lon = gson.toJson(result); response.setContentType("text/plain"); response.getWriter().write(lon); }*/ if("search1".equals(type)){ LoanService lonService = new LoanService(); ArrayList<LoanDTO> allLoan = lonService.getAllLoan(connection); Gson gson = new Gson(); String lon = gson.toJson(allLoan); response.setContentType("text/plain"); response.getWriter().write(lon); } if ("delete1".equals(type)) { String lonid = request.getParameter("loanid"); LoanService lonService = new LoanService(); boolean result = lonService.deleteLoan(lonid, connection); response.setContentType("text/plain"); response.getWriter().write("" + result); } if ("add1".equals(type)) { String Loan_Id = request.getParameter("lno"); String Loan_Date = request.getParameter("ldate"); String Amount = request.getParameter("amount"); String Period = request.getParameter("time"); String Status = request.getParameter("status"); String Emp_Id = request.getParameter("eno"); //LoanService loanService = new LoanService(); /*CadreDTO cadreDTO = cadreService.getCadreByName(cardreName, connection); String cadreId = cadreDTO.getCadre_Id(); DepartmentService departmentService = new DepartmentService(); DepartmentDTO departmentDTO = departmentService.getDepartmentByName(deptName, connection); String departmentId = departmentDTO.getDpt_id(); String[] split = photo.split("\\\\"); */ //File source = new File("C:\\Users\\Chamath\\Desktop/"+split[2]+""); //File dest = new File("web\\image\\photo"); //File dest = new File("D:\\cs\\cs\\uni\\2nd year\\Synergy\\project\\11 7\\new\\SLCHRMS\\web\\image\\photo"); // try { // //FileUtils.copyDirectory(source, dest); // FileUtils.copyFileToDirectory(source, dest); // } catch (IOException e) { // e.printStackTrace(); // } LoanDTO loanDTO = new LoanDTO(Loan_Id, Loan_Date, Amount, Period, Status, Emp_Id); boolean result = loanService.addLoan(loanDTO, connection); response.setContentType("text/plain"); response.getWriter().write("" + result); } /* if ("add".equals(type)) { String loanId = request.getParameter("lno"); String loandate = request.getParameter("date"); String amount = request.getParameter("amount"); String period = request.getParameter("time"); String status = request.getParameter("status"); String empId = request.getParameter("eno"); boolean idExcist = loanService.isIdExist(loanId, connection); LoanDTO loanDTO = new LoanDTO(loanId,loandate,amount,period,status,empId); String curForm = "Loan.jsp"; HttpSession session = null; HttpSession session2 = request.getSession(); UserDTO user = (UserDTO) session2.getAttribute("user"); if (idExcist) { session = request.getSession(); session.setAttribute("msg", loanId + "already exists"); session.setAttribute("loanDTO", loanDTO); session.setAttribute("curForm", curForm); response.sendRedirect("views/Work_Area_" + user.getUser_Level() + ".jsp"); } else { boolean addloan = loanService.addLoan(loanDTO, connection); if (addloan) { session = request.getSession(); String[] s = user.getUser_Level().split(" "); if (s.length == 2) { session2.setAttribute("curForm", "Dashboard_" + s[0] + "_" + s[1] + ".jsp"); } else { session2.setAttribute("curForm", "Dashboard_" + s[0] + ".jsp"); } session.setAttribute("msg", loanId + " Loan added"); response.sendRedirect("views/Work_Area_" + user.getUser_Level() + ".jsp"); } else { session2.setAttribute("msg", "Loan added failed."); session2.setAttribute("curForm", curForm); response.sendRedirect("views/Work_Area_" + user.getUser_Level() + ".jsp"); } } }*/ /* if("search1".equals(type)){ LoanService loanService = new LoanService(); ArrayList<LoanDTO> allLoan = loanService.getAllLoan(connection); Gson gson = new Gson(); String lon = gson.toJson(allLoan); response.setContentType("text/plain"); response.getWriter().write(lon); } if ("delete1".equals(type)) { String lonid = request.getParameter("loanId"); LoanService loanService = new LoanService(); boolean result = loanService.deleteLoan(lonid, connection); response.setContentType("text/plain"); response.getWriter().write("" + result); } */ /*if ("search".equals(type)) { String cno = request.getParameter("cnom"); String cname = request.getParameter("cname2"); CadreService cadreService = new CadreService(); CadreDTO cadreDTO = new CadreDTO(); HttpSession session = request.getSession(); UserDTO user = (UserDTO) session.getAttribute("user"); session.setAttribute("cid", cno); if (!cno.equals("") && cname.equals("")) { cadreDTO = cadreService.getCadreByID(cno, connection); if (cadreDTO.getCadre_Id() == null) { session.setAttribute("msg", cno + " is not available"); } else { //session.setAttribute("sType", "ENo"); session.setAttribute("cadre", cadreDTO); } session.setAttribute("curForm", "SearchCadre.jsp"); } else if (!cname.equals("") && cno.equals("")) { cadreDTO = cadreService.getCadreByName(cname, connection); if (cadreDTO.getCadre_Id() == null) { session.setAttribute("msg", cname + " is not available"); } else { //session.setAttribute("sType", "ENo"); session.setAttribute("cadre", cadreDTO); } session.setAttribute("curForm", "SearchCadre.jsp"); } response.sendRedirect("views/Work_Area_" + user.getUser_Level() + ".jsp"); }*/ /* if ("delete".equals(type)) { HttpSession session = request.getSession(); String loanid = request.getParameter("loanId"); LoanService loanService = new LoanService(); boolean result = loanService.deleteLoan(loanid, connection); UserDTO user = (UserDTO)session.getAttribute("user"); if (result) { session.setAttribute("msg", loanid+" Loan details deleted."); } else { session.setAttribute("msg", loanid+" Loan details deleted failed."); } session.setAttribute("curForm", "Loan.jsp"); response.sendRedirect("views/Work_Area_"+user.getUser_Level()+".jsp"); }*/ } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { processRequest(request, response); } catch (SQLException ex) { Logger.getLogger(LoanController.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(LoanController.class.getName()).log(Level.SEVERE, null, ex); } } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { processRequest(request, response); } catch (SQLException ex) { Logger.getLogger(LoanController.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(LoanController.class.getName()).log(Level.SEVERE, null, ex); } } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
package com.mo.mohttp.response; import com.mo.mohttp.Request; import com.mo.mohttp.misc.IOUtils; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpResponse; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class HttpClientResponse extends AbstractResponse { private HttpResponse httpResponse; private InputStream inputStream; public HttpClientResponse(HttpResponse httpResponse, Request request) throws IOException { super(request); this.httpResponse = httpResponse; inputStream = IOUtils.buffer(httpResponse.getEntity().getContent()); } public int statusCode() { return httpResponse.getStatusLine().getStatusCode(); } public String contentType() { return httpResponse.getEntity().getContentType().getValue(); } public InputStream stream() throws IOException { return inputStream; } public String encoding() { return httpResponse.getEntity().getContentEncoding().getValue(); } public Map<String,List<String>> getHeaders(){ Map<String,List<String>> map = new HashMap<String, List<String>>(); Header[] headers = httpResponse.getAllHeaders(); for(Header header:headers){ String key = header.getName(); List<String> list = new ArrayList<String>(); for(HeaderElement headerElement:header.getElements()){ list.add(headerElement.toString()); } map.put(key,list); } return map; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; HttpClientResponse that = (HttpClientResponse) o; return httpResponse != null ? httpResponse.equals(that.httpResponse) : that.httpResponse == null; } @Override public int hashCode() { return httpResponse != null ? httpResponse.hashCode() : 0; } }
package de.tu_clausthal.in.informatikwerkstatt.sensors.informatikwerkstatt_philssensors.sensor; /** * Interface für einen GPS-Positions Listener */ public interface ILocationListener extends ISensorListener { /** * liefert die aktuelle Position mit weiteren Meta-Daten * * @param p_latitude Breitengrad im Gradmaß * @param p_longitude Längengrad im Gradmaß * @param p_altitude Höhe in Meter, sofern es im Gerät gemessen wird, ansonsten 0 * @param p_speed Geschwindigkeit in m/s, sofern es im Gerät gemessen wird, ansonsten 0 * @param p_distance Distanz zur vergangenen Position */ void location(final Number p_latitude, final Number p_longitude, final Number p_altitude, final Number p_speed, final Number p_distance); }
package org.murinrad.android.musicmultiply.time; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import net.murinrad.android.timekeeper.ITimeKeeperServer; import org.murinrad.android.musicmultiply.LibTags; import java.io.IOException; public class TimeKeeperServerService extends Service { NtpServer ntpServer = null; ITimeKeeperServer binder = new ITimeKeeperServer.Stub() { @Override public void stop() throws RemoteException { stopServer(); // TODO Auto-generated method stub } @Override public void setPort(int portNumber) throws RemoteException { } @Override public void start() throws RemoteException { if (ntpServer == null || !ntpServer.isStarted()) { activateServer(); } } }; @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return (IBinder) binder; } @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); if (noServicePresentOnLAN()) { activateServer(); } } private void activateServer() { stopServer(); ntpServer = new NtpServer(NTPSettings.NTP_PORT); try { ntpServer.start(); } catch (IOException e) { Log.w(LibTags.APPTAG, "Error in time server startup"); e.printStackTrace(); } } @Override public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; } private boolean noServicePresentOnLAN() { // TODO Auto-generated method stub return true; } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); stopServer(); } private void stopServer() { if (ntpServer != null) { ntpServer.stop(); } } }
package com.tencent.mm.plugin.game.gamewebview.jsapi.biz; import com.tencent.mm.ab.b; import com.tencent.mm.ab.l; import com.tencent.mm.ab.v.a; import com.tencent.mm.modelsns.d; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.sdk.platformtools.x; class ah$1 implements a { final /* synthetic */ d jHm; final /* synthetic */ ah jHn; ah$1(ah ahVar, d dVar) { this.jHn = ahVar; this.jHm = dVar; } public final int a(int i, int i2, String str, b bVar, l lVar) { x.d("MicroMsg.GameJsApiOpenWeAppPage", "onGYNetEnd oreh errType:%d errCode:%d msg:%s", Integer.valueOf(i), Integer.valueOf(i2), str); if (!(i == 0 && i2 == 0)) { x.i("MicroMsg.GameJsApiOpenWeAppPage", "report oreh logbuffer(13927)"); h.mEJ.h(13927, this.jHm); h.mEJ.a(457, 0, 1, false); } return 0; } }
package com.wllfengshu.mysql.model.dto; import lombok.Data; import java.util.List; /** * 分析器处理后的sql对象 */ @Data public class AnalyseSqlDTO extends PendingSqlDTO { /** * 字段的集合 */ private List<String> fields; }
/******************************************************************************* * =============LICENSE_START========================================================= * * ================================================================================= * Copyright (c) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END========================================================= * *******************************************************************************/ package org.onap.ccsdk.dashboard.model.deploymenthandler; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; /** * Response body for a PUT or DELETE to /dcae-deployments/{deploymentId} * */ public class DeploymentResponse { /** Unique Identifier for the request */ private String requestId; /** Links that the API client can access */ private DeploymentResponseLinks links; @JsonCreator public DeploymentResponse(@JsonProperty("requestId") String requestId, @JsonProperty("links") DeploymentResponseLinks links) { this.requestId = requestId; this.links = links; } public String getRequestId() { return this.requestId; } public DeploymentResponseLinks getLinks() { return this.links; } }
package com.madoka.navigationdemo; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentStatePagerAdapter; import androidx.fragment.app.Fragment; public class PageAdapter extends FragmentStatePagerAdapter { int num; public PageAdapter(FragmentManager fn,int numoftab) { super(fn); this.num=numoftab; } @Override public Fragment getItem(int i){ switch (1) { case 0: return new Fragment1(); case 1: return new Fragment2(); case 2: return new Fragment3(); default: return null; } } @Override public int getCount() { return num; } }
import javax.swing.*; public class FormView { private final JFrame frame; private final FormThreeFields formThreeFields; private final FormOneFields formOneFields; public FormView() { this.frame = MainFrame.getInstance(); this.formThreeFields = new FormThreeFields(); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setVisible(true); this.formThreeFields.getCollapseButton().addActionListener(e -> btnPressedThreeFields()); this.formOneFields = new FormOneFields(); this.formOneFields.getExpandButton().addActionListener(e -> btnPressedOneFields()); frame.setContentPane(formThreeFields.getPanelThreeFields()); frame.setSize(formThreeFields.getPanelThreeFields().getMinimumSize()); } private void viewFormOneFields() { frame.setContentPane(formOneFields.getPanelFormFiled()); frame.setSize(formOneFields.getPanelFormFiled().getMinimumSize()); frame.repaint(); } private void viewFormThreeFields() { frame.setContentPane(formThreeFields.getPanelThreeFields()); frame.setSize(formThreeFields.getPanelThreeFields().getMinimumSize()); frame.repaint(); } private void btnPressedThreeFields() { if (!formThreeFields.getFirstNameField().getText().isEmpty() && !formThreeFields.getSurNameField().getText().isEmpty() && (formThreeFields.getFirstNameField().getText() + formThreeFields.getSurNameField().getText() + formThreeFields.getMidNameField().getText()).matches("^[\\p{L}\\p{Blank}.’\\-]+")) { formOneFields.getFullNameField().setText(joinText()); viewFormOneFields(); } else { JOptionPane.showMessageDialog( formThreeFields.getPanelThreeFields(), "Заполните поля", "Некорректный ввод, только буквы и - ", JOptionPane.WARNING_MESSAGE ); } } private String joinText() { String first = formThreeFields.getFirstNameField().getText(); String sur = formThreeFields.getSurNameField().getText(); String mid = formThreeFields.getMidNameField().getText(); return sur + " " + first + (mid.isEmpty() ? "" : (" " + mid)); } private void btnPressedOneFields() { String name = formOneFields.getFullNameField().getText(); String[] splitName = name.split(" "); if (splitName.length >= 2 && splitName.length <= 3 && name.matches("^[\\p{L}\\s.’\\-]+$")) { splitText(); viewFormThreeFields(); } else { JOptionPane.showMessageDialog( formOneFields.getPanelFormFiled(), "Введите ФИО через пробел, только буквы и - ", "Некорректный ввод", JOptionPane.WARNING_MESSAGE ); } } private void splitText() { String[] name = formOneFields.getFullNameField().getText().split(" "); formThreeFields.getFirstNameField().setText(name[0]); formThreeFields.getSurNameField().setText(name[1]); formThreeFields.getMidNameField().setText(name.length == 3 ? name[2] : ""); } }
package com.cmj.demo; import com.cmj.consumer.Consumer; import com.cmj.rpc.handler.RpcEntity; import java.util.UUID; /** * Created by chenminjian on 2018/4/18. */ public class ConsumerDemo { public static void main(String[] args) { Consumer consumer = new Consumer("127.0.0.1", 8999); RpcEntity entity = new RpcEntity(); entity.setId(UUID.randomUUID().toString()); entity.setServiceName("com.cmj.demo.DemoService"); entity.setMethodName("str"); Object o = consumer.send(entity); System.out.println("receive:" + o); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } consumer.close(); } }
package com.paisheng.instagme.base; import android.view.View; import com.paisheng.instagme.network.bean.ServerDownInfoBean; import com.paisheng.lib.mvp.extend.AbstractLazyFragment; import com.paisheng.lib.mvp.network.NetworkPresenter; import com.paisheng.lib.widget.dialog.ProgressHUD; import butterknife.ButterKnife; import butterknife.Unbinder; /** * @author: yuanbaining * @Filename: AbstractIMFragment * @Description: Fragment中间层,预留 * @Copyright: Copyright (c) 2017 Tuandai Inc. All rights reserved. * @date: 2018/1/30 13:59 */ public abstract class AbstractIMFragment<T extends NetworkPresenter> extends AbstractLazyFragment<T> implements IBaseView { protected ProgressHUD mProgressHUD; private Unbinder mUnbinder; /** *<br> Description: 延时后先加载布局 *<br> Author: yuanbaining *<br> Date: 2018/2/1 18:25 */ protected abstract int getLayoutRes(); /** *<br> Description: 延时后再加载执行 *<br> Author: yuanbaining *<br> Date: 2018/2/1 18:24 */ protected abstract void lazyLoad(); protected View getMainLayout() { return mRootView; } @Override protected View onLoadUI() { mVsContent.setLayoutResource(getLayoutRes()); View contentView = mVsContent.inflate(); bindView(true, contentView); lazyLoad(); return contentView; } @Override protected void setPageId() { } /** *<br> Description: Fragment销毁时解绑binder *<br> Author: yuanbaining *<br> Date: 2018/2/1 18:26 */ @Override public void onDestroy() { super.onDestroy(); // 解绑 bindView(false, null); } /** * <br> Description: 绑定/解绑定 ButterKnife * <br> Author: yuanbaining * <br> Date: 2018/1/30 15:16 */ protected void bindView(boolean bind, View view) { if (!bind && mUnbinder != null) { mUnbinder.unbind(); mUnbinder = null; return; } if (bind && view != null) { mUnbinder = ButterKnife.bind(this, view); } } @Override public void displayRquestServerDown(String taskId, ServerDownInfoBean serverDownInfo) { } }