text
stringlengths
10
2.72M
package vue; import controler.controlerLocal.ChessGameControler; import model.Coord; import model.PieceIHM; import model.observable.ChessGame; import tools.ChessImageProvider; import javax.swing.*; import java.awt.*; import java.util.List; public class ChessGameGUI extends javax.swing.JFrame implements java.awt.event.MouseListener, java.awt.event.MouseMotionListener, java.util.Observer { JLayeredPane layeredPane; JPanel chessBoard; JLabel chessPiece; int xAdjustment; int yAdjustment; ChessGameControler chessGameControler; public ChessGameGUI( java.lang.String name, controler.controlerLocal.ChessGameControler chessGameControler, java.awt.Dimension boardSize){ this.chessGameControler = chessGameControler; // Use a Layered Pane for this this application layeredPane = new JLayeredPane(); getContentPane().add(layeredPane); layeredPane.setPreferredSize(boardSize); layeredPane.addMouseListener(this); layeredPane.addMouseMotionListener(this); //Add a chess board to the Layered Pane chessBoard = new JPanel(); layeredPane.add(chessBoard, JLayeredPane.DEFAULT_LAYER); chessBoard.setLayout( new GridLayout(8, 8) ); chessBoard.setPreferredSize( boardSize ); chessBoard.setBounds(0, 0, boardSize.width, boardSize.height); for (int i = 0; i < 64; i++) { JPanel square = new JPanel( new BorderLayout() ); chessBoard.add( square ); int row = (i / 8) % 2; if (row == 0) square.setBackground( i % 2 == 0 ? Color.black : Color.white ); else square.setBackground( i % 2 == 0 ? Color.white : Color.black ); } } public void mouseClicked(java.awt.event.MouseEvent e){ /* TODO */ } public void mouseDragged(java.awt.event.MouseEvent e){ /* TODO */ /* Code found here: https://www.roseindia.net/java/example/java/swing/chess-application-swing.shtml */ if (chessPiece == null) return; chessPiece.setLocation(e.getX() + xAdjustment, e.getY() + yAdjustment); } public void mouseEntered(java.awt.event.MouseEvent e){ /* TODO */ } public void mouseExited(java.awt.event.MouseEvent e){ /* TODO */ } public void mouseMoved(java.awt.event.MouseEvent e){ /* TODO */ } public void mousePressed(java.awt.event.MouseEvent e){ /* Code found here: https://www.roseindia.net/java/example/java/swing/chess-application-swing.shtml */ if(chessGameControler.isPlayerOK(getPieceCoord(e.getX(),e.getY()))) { chessPiece = null; Component c = chessBoard.findComponentAt(e.getX(), e.getY()); if (c instanceof JPanel) return; Point parentLocation = c.getParent().getLocation(); xAdjustment = parentLocation.x - e.getX(); yAdjustment = parentLocation.y - e.getY(); chessPiece = (JLabel) c; chessPiece.setLocation(e.getX() + xAdjustment, e.getY() + yAdjustment); chessPiece.setSize(chessPiece.getWidth(), chessPiece.getHeight()); layeredPane.add(chessPiece, JLayeredPane.DRAG_LAYER); } } public void mouseReleased(java.awt.event.MouseEvent e){ /* TODO */ /* Code found here: https://www.roseindia.net/java/example/java/swing/chess-application-swing.shtml */ if(chessPiece == null) return; chessPiece.setVisible(false); Component c = chessBoard.findComponentAt(e.getX(), e.getY()); if (c instanceof JLabel){ Container parent = c.getParent(); parent.remove(0); parent.add( chessPiece ); } else { Container parent = (Container)c; parent.add( chessPiece ); } chessPiece.setVisible(true); } public void update(java.util.Observable arg0, java.lang.Object o){ List<PieceIHM> piecesIHM = (List<PieceIHM>) o; for (PieceIHM piece : piecesIHM) { for (Coord coord : piece.getList()) { JLabel current = new JLabel( new ImageIcon(ChessImageProvider.getImageFile(piece.getTypePiece(), piece.getCouleur()))); JPanel panel = (JPanel) chessBoard.getComponent(coord.x + coord.y * 8); panel.add(current); } } } private Coord getPieceCoord(int x, int y) { return new Coord(x/(700/8), y/(700/8)); } public static void main(String[] args) { ChessGame chessGame = new ChessGame(); ChessGameControler chessGameControler = new ChessGameControler(chessGame); Dimension dimension = new Dimension(900,900); JFrame frame = new ChessGameGUI("ChessGame",chessGameControler, dimension); frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE ); frame.pack(); frame.setResizable(true); frame.setLocationRelativeTo( null ); frame.setVisible(true); } }
package com.lj.app.bsweb.upm.user.service; import com.lj.app.core.common.base.service.BaseService; import com.lj.app.bsweb.upm.user.entity.UpmUserAndUserGroupRel; import java.util.List; import java.util.Map; public interface UpmUserAndUserGroupRelService<UpmUserAndUserGroupRel> extends BaseService { }
package com.server; import com.messages.Message; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.util.HashSet; public class Server { private static final int PORT = 9001; private static final HashSet<String> names = new HashSet<String>(); private static HashSet<ObjectOutputStream> writers = new HashSet<ObjectOutputStream>(); public static void main(String[] args) throws Exception { System.out.println("The chat server is running."); ServerSocket listener = new ServerSocket(PORT); try { while (true) { new Handler(listener.accept()).start(); } } catch (Exception e) { e.printStackTrace(); } finally { listener.close(); } } private static class Handler extends Thread { private String name; private Socket socket; private InputStream is; private ObjectInputStream input; private OutputStream os; private ObjectOutputStream output; public Handler(Socket socket) { this.socket = socket; } public void run() { try { is = socket.getInputStream(); input = new ObjectInputStream(is); os = socket.getOutputStream(); output = new ObjectOutputStream(os); Message nameCheck = (Message) input.readObject(); synchronized (names) { if (!names.contains(nameCheck.getName())) { writers.add(output); this.name = nameCheck.getName(); names.add(name); addToList(nameCheck); System.out.println(name + " added"); } else { System.out.println("duplicate name"); } } while (true) { Message inputmsg = (Message) input.readObject(); if (inputmsg != null) { System.out.println(currentThread().getName() + " name size : " + names.size()); switch (inputmsg.getType()) { case "USER": write(inputmsg); break; case "CONNECTED": addToList(inputmsg); break; } } } } catch (IOException e) { System.out.println(e); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if (name != null) { names.remove(name); System.out.println("User: " + name + " has been removed!"); try { removeFromList(name); } catch (Exception e) { e.printStackTrace(); } } if (output != null) { writers.remove(output); } } try { output.close(); } catch (IOException e) { } } private synchronized void removeFromList(String name) throws IOException { names.remove(name); Message msg = new Message(); msg.setMsg("Welcome, You have now joined the server! Enjoy chatting!"); msg.setType("DISCONNECTED"); msg.setName("SERVER"); msg.setUserlist(names); write(msg); } private void addToList(Message msg) throws IOException { msg = new Message(); msg.setMsg("Welcome, You have now joined the server! Enjoy chatting!"); msg.setType("CONNECTED"); msg.setName("SERVER"); write(msg); } private void write(Message msg) throws IOException { for (ObjectOutputStream writer : writers) { msg.setUserlist(names); System.out.println(msg.getUserlist().size()); writer.writeObject(msg); } } } }
import java.util.Scanner; public class Prog7{ public static void main(String args[]){ int x,y,z; Scanner scn = new Scanner(System.in); System.out.println("Enter X:"); x = scn.nextInt(); System.out.println("Enter Y:"); y = scn.nextInt(); System.out.println("Enter Z"); z = scn.nextInt(); if(x>y&&x>z) System.out.println("x is the biggest out of the three"); else if(y>x&&y>z) System.out.println("Y is the biggest out of the three"); else System.out.println(" Z is the biggest out of the three"); System.out.println("Made By\nPrubhtej Singh\n07113203118\nIT2"); } }
package org.ah.minecraft.tweaks; import org.bukkit.Material; import org.bukkit.entity.LivingEntity; import org.bukkit.event.EventHandler; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.inventory.ItemStack; public class PrimitiveTools extends Tweak { @EventHandler public void onHit (EntityDamageByEntityEvent event) { if (event.getDamager() instanceof LivingEntity) { LivingEntity e = (LivingEntity)event.getDamager(); if (e.getEquipment() != null) { ItemStack hand = e.getEquipment().getItemInMainHand(); if (hand.getType() == Material.FLINT) { event.setDamage(event.getDamage() + 1); return; } if (hand.getType() == Material.STICK) { event.setDamage(event.getDamage() + 1); return; } if (hand.getType() == Material.BLAZE_ROD) { event.setDamage(event.getDamage() + 1); event.getEntity().setFireTicks(5); return; } if (hand.getType() == Material.BONE) { event.setDamage(event.getDamage() + 1); return; } } } } }
package fr.lteconsulting.outil; import javax.servlet.http.HttpServletRequest; import fr.lteconsulting.User; public class DonneesScopes { public static void resetSession( HttpServletRequest request ) { request.getSession().invalidate(); } /** * Returns the user registered in the session */ public static User getConnectedUser( HttpServletRequest request ) { return (User) request.getSession().getAttribute( "user" ); } /** * Registers the user in the session */ public static void setConnectedUser( User user, HttpServletRequest request ) { request.getSession().setAttribute( "user", user ); } }
package com.tencent.mm.ui.base; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.GridView; import com.tencent.mm.sdk.platformtools.x; public final class MMGridPaperGridView extends GridView { private int mCount; private int mIndex; private OnItemClickListener osG = new OnItemClickListener() { public final void onItemClick(AdapterView<?> adapterView, View view, int i, long j) { if (MMGridPaperGridView.this.tvq == null) { x.w("MicroMsg.MMGridPaperGridView", "on item click, but main adapter is null"); } } }; private int tvk; private int tvl; private int tvm; private int tvn = -1; private boolean tvo = false; a tvp; private j tvq; private OnItemLongClickListener tvr = new 2(this); public MMGridPaperGridView(Context context, AttributeSet attributeSet, int i) { super(context, attributeSet, i); } public MMGridPaperGridView(Context context, AttributeSet attributeSet) { super(context, attributeSet); } public final int getIndex() { return this.mIndex; } public final void a(int i, int i2, int i3, j jVar) { boolean z = true; String str = "MicroMsg.MMGridPaperGridView"; String str2 = "index[%d], rows[%d], columns[%d], adapter is null[%B]"; Object[] objArr = new Object[4]; objArr[0] = Integer.valueOf(i); objArr[1] = Integer.valueOf(i2); objArr[2] = Integer.valueOf(i3); if (jVar != null) { z = false; } objArr[3] = Boolean.valueOf(z); x.i(str, str2, objArr); this.mIndex = i; this.tvk = i2; this.tvl = i3; this.tvq = jVar; this.mCount = this.tvk * this.tvl; this.tvm = this.mIndex * this.mCount; if (this.tvq != null && this.tvq.getCount() - this.tvm < this.mCount) { this.mCount = this.tvq.getCount() - this.tvm; } if (getAdapter() == null) { x.w("MicroMsg.MMGridPaperGridView", "get adapter null, new one"); this.tvp = new a(this, (byte) 0); setAdapter(this.tvp); } setNumColumns(this.tvl); setColumnWidth(3); setOnItemClickListener(this.osG); setOnItemLongClickListener(this.tvr); } public final void setHiddenIndex(int i) { this.tvn = i; } public final void setClearMode(boolean z) { this.tvo = z; } }
/* * This demo started life as part of Sun's Java Tutorial for Drag and Drop/Cut and Paste. * The tutorial had already been updated to Java 6 (which includes changes to * TransferHandler that I didn't want to use yet), so a cached version was found * at http://mockus.us/optimum/JavaTutorial/mustang/uiswing/dnd/examples/index.html#DragPictureDemo * (retrieved June 17, 2009). * * It was modified by Byron Weber Becker as follows: * -- code to initialize the pictures was simplified with an array and loop * -- removed unused imports * -- used inner classes for listeners rather than exposing the * methods in a class's public interface * -- there were funny inheritance interactions between DTPicture and Picture * in the mouse and mousemotion listeners, so combined the two classes * -- added support for the javaFileList data flavor, enabling drag 'n drop * from the desktop and to other applications such as image editors * -- removed the copy/cut/paste magic using action maps and the automatic * stuff in TransferHandler and replaced it with direct and easier to * understand implementations. */ import java.awt.*; import javax.swing.*; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.FocusListener; import java.awt.event.FocusEvent; import java.awt.event.KeyEvent; import java.io.IOException; public class TransferDemo { /** * Create the GUI and show it. For thread safety, * this method should be invoked from the * event-dispatching thread. */ private static void createAndShowGUI() { //Create and set up the window. JFrame frame = new JFrame("TransferDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create and set up the menu bar and content pane. PicturePanel demo = new PicturePanel(); //demo.setOpaque(true); //content panes must be opaque frame.setContentPane(demo); frame.setJMenuBar(demo.createMenuBar()); //Display the window. frame.pack(); frame.setVisible(true); } public static void main(String[] args) { System.out.println("You may need to copy the images directory from the"); System.out.println("source code directory to the same directory as TransferDemo.class."); //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }
package s260452449.MyTools.Tree; import boardgame.Board; import halma.CCMove; /** * Created by jeffrey on 3/28/2014. */ public class Leaf extends Node{ private Board board; public Leaf (CCMove move, Board theBoard, Integer depth) { super(move, depth); this.board = theBoard; } public Board getBoard() { return this.board; } public void setBoard(Board theBoard) { this.board = theBoard; } }
import java.io.Serializable; public class MyBean implements Serializable { private static final long serialVersionUID = 1L; private String one; private String two; public MyBean() { } public MyBean(String one, String two) { this.one = one; this.two = two; } public String getOne() { return one; } public void setOne(String one) { this.one = one; } public String getTwo() { return two; } public void setTwo(String two) { this.two = two; } }
package com.melonBean.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import com.melonBean.entities.Employee; public interface EmployeeMapperSql { public List<Employee> getEmpByCondition(Employee emp); public Integer updateEmpById(Employee emp); public Integer addEmps(@Param("emps")List<Employee> emps); }
package com.gym.appointments.ServiceImp; import com.gym.appointments.Input.AlphabetSoupInput; import com.gym.appointments.Input.DatosInput; import com.gym.appointments.Input.JsonInput; import com.gym.appointments.Input.MensajeInput; import com.gym.appointments.Model.*; import com.gym.appointments.Service.SopaDePalabrasService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.ResponseStatus; import sun.security.provider.certpath.OCSPResponse; import java.lang.Error; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; @Service public class SopaDePalabrasServiceImpl implements SopaDePalabrasService { AlphabetSoup alphabetSoup; @Override public ResponseEntity<JsonInput> crearSopaDePalabras(AlphabetSoup alphabetSoupNew) { //Por defecto valor = 15 int altura = alphabetSoupNew.getW(); int ancho = alphabetSoupNew.getH(); if(altura < 15 || altura > 80){ altura = 15; } if(ancho < 15 || ancho > 80){ ancho = 15; } List<String> ubicaciones = new ArrayList<>(); List<Ubicacion> ubicacionList = new ArrayList<>(); ubicaciones.add("Si"); //HORIZONTAL_IZQUIERDA_DERECHA /0 ubicacionList.add(Ubicacion.HORIZONTAL_IZQUIERDA_DERECHA); ubicaciones.add("No"); //HORIZONTAL_DERECHA_IZQUIERDA /1 ubicacionList.add(Ubicacion.HORIZONTAL_DERECHA_IZQUIERDA); ubicaciones.add("Si"); //VERTICAL_ARRIBA_ABAJO /2 ubicacionList.add(Ubicacion.VERTICAL_ARRIBA_ABAJO); ubicaciones.add("No"); //VERTICAL_ABAJO_ARRIBA /3 ubicacionList.add(Ubicacion.VERTICAL_ABAJO_ARRIBA); ubicaciones.add("No"); //DIAGONAL_IZQUIERDA_DERECHA_ARRIBA_ABAJO /4 ubicacionList.add(Ubicacion.DIAGONAL_IZQUIERDA_DERECHA_ARRIBA_ABAJO); ubicaciones.add("No"); //DIAGONAL_DERECHA_IZQUIERDA_ABAJO_ARRIBA; 5 ubicacionList.add(Ubicacion.DIAGONAL_DERECHA_IZQUIERDA_ABAJO_ARRIBA); ubicaciones.add("No"); //DIAGONAL_IZQUIERDA_DERECHA_ABAJO_ARRIBA /6 ubicacionList.add(Ubicacion.DIAGONAL_IZQUIERDA_DERECHA_ABAJO_ARRIBA); ubicaciones.add("No"); //DIAGONAL_DERECHA_IZQUIERDA_ARRIBA_ABAJO; 7 ubicacionList.add(Ubicacion.DIAGONAL_DERECHA_IZQUIERDA_ARRIBA_ABAJO); //Izquierda Derecha (ltr) if(!alphabetSoupNew.isLtr()){ ubicaciones.set(0, "No"); ubicacionList.remove(Ubicacion.HORIZONTAL_IZQUIERDA_DERECHA); } //Derecha Izquierda (rtl) if(alphabetSoupNew.isRtl()){ ubicaciones.set(1, "Si"); }else{ ubicacionList.remove(Ubicacion.HORIZONTAL_DERECHA_IZQUIERDA); } //Arriba hacia Abajo (ttb) if(!alphabetSoupNew.isTtb()){ ubicaciones.set(2, "No"); ubicacionList.remove(Ubicacion.VERTICAL_ARRIBA_ABAJO); } //Abajo hacia Arriba (btt) if(alphabetSoupNew.isBtt()){ ubicaciones.set(3, "Si"); }else{ ubicacionList.remove(Ubicacion.VERTICAL_ABAJO_ARRIBA); } //Diagonales (d) if(alphabetSoupNew.isD()){ ubicaciones.set(4, "Si"); ubicaciones.set(5, "Si"); ubicaciones.set(6, "Si"); ubicaciones.set(7, "Si"); }else{ ubicacionList.remove(Ubicacion.DIAGONAL_IZQUIERDA_DERECHA_ARRIBA_ABAJO); ubicacionList.remove(Ubicacion.DIAGONAL_DERECHA_IZQUIERDA_ABAJO_ARRIBA); ubicacionList.remove(Ubicacion.DIAGONAL_IZQUIERDA_DERECHA_ABAJO_ARRIBA); ubicacionList.remove(Ubicacion.DIAGONAL_DERECHA_IZQUIERDA_ARRIBA_ABAJO); } int categoria = alphabetSoupNew.getC(); if(categoria < 1 || categoria > 11){ categoria = 1; } SopaDePalabras sp = new SopaDePalabras(); boolean sopaDePalabrasGenerada = false; sopaDePalabrasGenerada = sp.generarSopaDepalabras(altura, ancho, ubicaciones, categoria); if(sopaDePalabrasGenerada){ this.alphabetSoup = new AlphabetSoup(); this.alphabetSoup.setW(altura); this.alphabetSoup.setH(ancho); this.alphabetSoup.setLtr(alphabetSoupNew.isLtr()); this.alphabetSoup.setRtl(alphabetSoupNew.isRtl()); this.alphabetSoup.setTtb(alphabetSoupNew.isTtb()); this.alphabetSoup.setBtt(alphabetSoupNew.isBtt()); this.alphabetSoup.setD(alphabetSoupNew.isD()); this.alphabetSoup.setC(categoria); this.alphabetSoup.setSopaDePalabras(sp); this.alphabetSoup.setUbicaciones(ubicacionList); AlphabetSoupInput alphabetSoupInput = new AlphabetSoupInput(sp.getId()); return ResponseEntity.status(HttpStatus.CREATED).body(alphabetSoupInput); }else{ String mensaje = ""; mensaje = "No se pudo crear la Sopa de Palabras"; MensajeInput mensajeInput = new MensajeInput(mensaje); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(mensajeInput); } } @Override public ResponseEntity<List<String>> getListaDePalabras(UUID alphabetSoupId) { List<String> listMensaje = new ArrayList<>(); if(this.alphabetSoup != null){ if(alphabetSoupId.equals(this.alphabetSoup.getSopaDePalabras().getId())){ return ResponseEntity.status(HttpStatus.OK).body(this.alphabetSoup.getSopaDePalabras().getPalabras()); }else{ String mensaje = "El Id es incorrecto "; listMensaje.add(mensaje); return ResponseEntity.status(HttpStatus.NOT_FOUND).body(listMensaje); } }else{ String mensaje = "No existe una Sopa de Palabras creada"; listMensaje.add(mensaje); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(listMensaje); } } @Override public ResponseEntity<String> getSopaDePalabras(UUID alphabetSoupId) { if(this.alphabetSoup != null){ if(alphabetSoupId.equals(this.alphabetSoup.getSopaDePalabras().getId())){ Character[][] sopa = this.alphabetSoup.getSopaDePalabras().getSopaPalabras(); String sopaComoString = ""; String filasSopa = ""; for ( int i=0; i<sopa.length; i++ ){ for ( int j=0; j<sopa[0].length; j++ ){ filasSopa = filasSopa + sopa[i][j] + "|"; } filasSopa = filasSopa + "\n"; sopaComoString = sopaComoString + filasSopa; filasSopa = ""; } return ResponseEntity.status(HttpStatus.OK).body(sopaComoString); }else{ String mensaje = " El Id es incorrecto "; return ResponseEntity.status(HttpStatus.NOT_FOUND).body(mensaje); } }else{ String mensaje = "No existe una Sopa de Palabras creada"; return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(mensaje); } } @Override public ResponseEntity<List<String>> validarCoordenadasDePalabras(UUID alphabetSoupId, CoordenadasInput coordenadasInput) { List<String> listMensaje = new ArrayList<>(); if(this.alphabetSoup != null){ final boolean[] coordenadasValidas = {false}; if(alphabetSoupId.equals(this.alphabetSoup.getSopaDePalabras().getId())){ SopaDePalabras sp = this.alphabetSoup.getSopaDePalabras(); coordenadasValidas[0] = sp.encontrarPalabraEnSopa(coordenadasInput.getSr() - 1, coordenadasInput.getSc() -1, coordenadasInput.getEr() -1, coordenadasInput.getEc() -1); if(coordenadasValidas[0]){ if(sp.getPalabras().size() == sp.getPalabrasEncontradas().size()){ System.out.println(""); System.out.println(" !!!FELICIDADES!!! "); System.out.println("----Usted ha ganado el Juego, ya no quedan palabras por descubrir----"); String mensaje = "!!!FELICIDADES!!! ----Ha ganado el Juego, ya no quedan palabras por descubrir----"; listMensaje.add(mensaje); return ResponseEntity.status(HttpStatus.OK).body(listMensaje); }else{ String mensaje = "Las coordenadas insertadas son válidas, se ha modificado correctamente la Sopa de Palabras "; listMensaje.add(mensaje); return ResponseEntity.status(HttpStatus.OK).body(listMensaje); } }else{ String mensaje = "Las coordenadas insertadas son inválidas o ya han sido encontradas anteriormente, la Sopa de Palabras no ha sido modificada "; listMensaje.add(mensaje); return ResponseEntity.status(HttpStatus.NOT_FOUND).body(listMensaje); } }else{ String mensaje = " El Id es incorrecto "; listMensaje.add(mensaje); return ResponseEntity.status(HttpStatus.NOT_FOUND).body(listMensaje); } }else{ String mensaje = "No existe una Sopa de Palabras creada"; listMensaje.add(mensaje); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(listMensaje); } } @Override public ResponseEntity<List<String>> getListaDePalabrasEncontradas(UUID alphabetSoupId) { List<String> listMensaje = new ArrayList<>(); if(this.alphabetSoup != null){ if(alphabetSoupId.equals(this.alphabetSoup.getSopaDePalabras().getId())){ return ResponseEntity.status(HttpStatus.OK).body(this.alphabetSoup.getSopaDePalabras().getPalabrasEncontradas()); }else{ String mensaje = " El Id es incorrecto "; listMensaje.add(mensaje); return ResponseEntity.status(HttpStatus.NOT_FOUND).body(listMensaje); } }else{ String mensaje = "No existe una Sopa de Palabras creada"; listMensaje.add(mensaje); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(listMensaje); } } @Override public ResponseEntity<List<String>> getListaDeCoordenasDePalabrasEnSopa(UUID alphabetSoupId) { List<String> listMensaje = new ArrayList<>(); if(this.alphabetSoup != null){ if(alphabetSoupId.equals(this.alphabetSoup.getSopaDePalabras().getId())){ List<Coordenada> coordDePalabras = this.alphabetSoup.getSopaDePalabras().getCoordenasDePalabras(); List<Coordenada> coordDePalabrasEncontradas = this.alphabetSoup.getSopaDePalabras().getCoordenasDePalabrasEncontradas(); List<String> coordenadasDePalabrasString = new ArrayList<>(); final int[] contCoordenadas = {0}; final boolean[] coordEncontradas = {false}; coordenadasDePalabrasString = coordDePalabras.stream().map(it -> { String coordenadas = ""; coordDePalabrasEncontradas.stream().forEach(it1 -> { if (it.getCoordenadaAlturaInicial() == it1.getCoordenadaAlturaInicial() && it.getCoordenadaAnchoInicial() == it1.getCoordenadaAnchoInicial() && it.getCoordenadaAlturaFinal() == it1.getCoordenadaAlturaFinal() && it.getCoordenadaAnchoFinal() == it1.getCoordenadaAnchoFinal()) { coordEncontradas[0] = true; } }); if(!coordEncontradas[0]){ int coordAlturaInicial = it.getCoordenadaAlturaInicial() +1; int coordAnchoInicial = it.getCoordenadaAnchoInicial() +1; int coordAlturaFinal = it.getCoordenadaAlturaFinal() +1; int coordAnchoFinal = it.getCoordenadaAnchoFinal() +1; contCoordenadas[0]++; coordenadas = contCoordenadas[0] + "-" + "(" + coordAlturaInicial+ "," + coordAnchoInicial + ")" + " " + "(" + coordAlturaFinal + "," + coordAnchoFinal + ")"; }else{ int coordAlturaInicial = it.getCoordenadaAlturaInicial() +1; int coordAnchoInicial = it.getCoordenadaAnchoInicial() +1; int coordAlturaFinal = it.getCoordenadaAlturaFinal() +1; int coordAnchoFinal = it.getCoordenadaAnchoFinal() +1; contCoordenadas[0]++; coordenadas = contCoordenadas[0] + "-" + "(" + coordAlturaInicial+ "," + coordAnchoInicial + ")" + " " + "(" + coordAlturaFinal + "," + coordAnchoFinal + ")" + " !!!Coordenada encontrada!!! "; coordEncontradas[0] = false; } return coordenadas; }).collect(Collectors.toList()); return ResponseEntity.status(HttpStatus.OK).body(coordenadasDePalabrasString); }else{ String mensaje = " El Id es incorrecto "; listMensaje.add(mensaje); return ResponseEntity.status(HttpStatus.NOT_FOUND).body(listMensaje); } }else{ String mensaje = "No existe una Sopa de Palabras creada"; listMensaje.add(mensaje); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(listMensaje); } } @Override public ResponseEntity<JsonInput> getDatosDeLaSopaDepalabras(UUID alphabetSoupId) { if(this.alphabetSoup != null){ if(alphabetSoupId.equals(this.alphabetSoup.getSopaDePalabras().getId())){ List<Ubicacion> ubicaciones = new ArrayList<>(); DatosInput datosInput = new DatosInput(); datosInput.setAlto(this.alphabetSoup.getW()); datosInput.setAncho(this.alphabetSoup.getH()); datosInput.setCategoriasPalabras(this.alphabetSoup.getCategoriasPalabrasByOrdinal()); datosInput.setUbicaciones(this.alphabetSoup.getUbicaciones()); datosInput.setTotalDePalabras( "(" + this.alphabetSoup.getSopaDePalabras().getPalabras().size() + ")"); datosInput.setPalabras(this.alphabetSoup.getSopaDePalabras().getPalabras()); datosInput.setTotalDePalabrasEncontradas("(" + this.alphabetSoup.getSopaDePalabras().getPalabrasEncontradas().size() + "/" + this.alphabetSoup.getSopaDePalabras().getPalabras().size() + ")"); datosInput.setPalabrasEncontradas(this.alphabetSoup.getSopaDePalabras().getPalabrasEncontradas()); return ResponseEntity.status(HttpStatus.OK).body(datosInput); }else{ String mensaje = " El Id es incorrecto "; MensajeInput mensajeInput = new MensajeInput(mensaje); return ResponseEntity.status(HttpStatus.NOT_FOUND).body(mensajeInput); } }else{ String mensaje = "No existe una Sopa de Palabras creada"; MensajeInput mensajeInput = new MensajeInput(mensaje); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(mensajeInput); } } @Override public ResponseEntity<JsonInput> deleteSopaDePalabra(UUID alphabetSoupId) { if(this.alphabetSoup != null){ if(alphabetSoupId.equals(this.alphabetSoup.getSopaDePalabras().getId())){ this.alphabetSoup = null; String mensaje = "La Sopa de Palabras ha sido eliminada correctamente"; MensajeInput mensajeInput = new MensajeInput(mensaje); return ResponseEntity.status(HttpStatus.OK).body(mensajeInput); }else{ String mensaje = " El Id es incorrecto "; MensajeInput mensajeInput = new MensajeInput(mensaje); return ResponseEntity.status(HttpStatus.NOT_FOUND).body(mensajeInput); } }else{ String mensaje = "No existe una Sopa de Palabras creada"; MensajeInput mensajeInput = new MensajeInput(mensaje); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(mensajeInput); } } }
package com.ant.liao.chuxin; public interface GifAction { /** * gif解码观察�? * @hide * @param parseStatus 解码是否成功,成功会为true * @param frameIndex 当前解码的第几帧,当全部解码成功后,这里�?1 */ public void parseOk(boolean parseStatus,int frameIndex); }
package com.packers.movers.commons.contracts; import com.packers.movers.commons.utils.JsonUtils; import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl; import java.lang.reflect.Type; public class DataContract<Contract> extends ContractBase { private final Contract data; public DataContract(Contract data) { this.data = data; } public static <Contract> DataContract<Contract> fromJson(String json, Class<Contract> targetClass) { Type type = ParameterizedTypeImpl.make(DataContract.class, new Type[] { targetClass }, null); return JsonUtils.deserialize(json, type); } public Contract getData() { return data; } }
package com.javaconceptprograms; import java.util.Arrays; import java.util.*; public class ArrayConcept { public static void main(String[] args) { String s = "Syed Qhubaib Ahmed Roshan Sadaddin Hasnaino"; String t[] = s.split(" "); String a[] = {"Syed", "Qhubaib", "Ahmed", "Roshan", "Sadaddin", "Hasnain"}; String b[] = new String[5]; b[0] = "Syed"; b[1] = "Roshan"; b[2] = "Sadaddin"; b[3] = "Qhubaib"; b[4] = "Hasnain"; System.out.println(t); System.out.println(a.toString()); System.out.println(b); System.out.println("***** Fetch the values through for each method********"); for(String name:a) { System.out.print(name+" "); } System.out.println(); System.out.println("********* Arrays Comparision By using Predefined Arrays Class **************"); //Arrays Comparision System.out.println(Arrays.equals(t, a)); System.out.println("*********** Arrays Comparision by using Logic ************"); int tlen = t.length; int alen = a.length; int count = 0; if(tlen == alen) { for(int i=0;i<tlen;i++) { if(t[i].equals(a[i])) { count++; } } System.out.println(count); } if(count == alen) { System.out.println("Both the Arrays are equal"); } else { System.out.println("Both the Arrays are not equal"); } System.out.println("************* Convert Arrays as ArrayList ************"); List<String> list = Arrays.asList(a); System.out.println("Converted Array 'a' to the List is: "+ list); System.out.println("************** Some More Methods in Array **************"); System.out.println(a.equals(t)); } }
package com.tao.logger.printer; import android.util.Log; import com.tao.logger.utils.Utils; /** * @project android_lib_logger * @class * @describe * @anthor * @time 2019/4/29 5:31 PM * @change * @time * @describe */ class LogcatPrinter implements IPrinter { public static final int MAX_LOG_LENGTH = 1900; @Override public void print(int priority, String tag, String msg) { if (Utils.checkNotNull(msg) ==null ) msg ="message is null"; if (tag == null) { tag = DEFAULT_TAG; } int lastLength = msg.length(); int originLength = msg.length(); int start = 0; int separatorOffset = System.lineSeparator().length() - 1; if (originLength < MAX_LOG_LENGTH + 90) { printActual(priority, tag, msg.substring(start)); return; } while (lastLength > MAX_LOG_LENGTH) { int index = msg.substring(start, start + MAX_LOG_LENGTH). lastIndexOf(System.lineSeparator(), start + MAX_LOG_LENGTH - 100); int nextStart; if (index <= 0) { nextStart = start + MAX_LOG_LENGTH - separatorOffset; } else { nextStart = start + index - separatorOffset; } String logString = msg.substring(start, nextStart); if (start != 0) { logString = "|" + logString; } printActual(priority, tag, logString); start = nextStart; lastLength = originLength - start; } printActual(priority, tag, "|" + msg.substring(start)); } private int printActual(int priority, String tag, String msg) { return Log.println(priority, tag, msg); } }
package ru.sg_studio.escapegame.bindings.libgdx.primitives; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Batch; import net.raydeejay.escapegame.Reactor; import ru.sg_studio.escapegame.IProxiedObject; import ru.sg_studio.escapegame.bindings.libgdx.LibGDXTextureUtilities; import ru.sg_studio.escapegame.bindings.libgdx.LibGDXTextureWrapper; import ru.sg_studio.escapegame.primitives.GraphicalEntity; public class LibGDXReactor extends LibGDXProto implements IProxiedObject { protected Reactor coreObject; @Override public GraphicalEntity getBinded() { return coreObject; } public LibGDXReactor(String name){ super();//DO NOT REMOVE! THIS IS IMPORTANT! coreObject = new Reactor(name, this); } @Override public void draw(Batch batch, float parentAlpha) { LibGDXTextureUtilities.checkLibGDXTexture((Reactor)getBinded()); if(((Reactor)getBinded()).getImage() != null) { batch.setColor(Color.WHITE); //batch.draw(coreObject.getImage(), coreObject.getX(), coreObject.getY()); //TODO: Ugly large... batch.draw(((LibGDXTextureWrapper)((Reactor)getBinded()).getImage()).getGdxTexture(), getX(),getY()); } } @Override public void trySyncGraphicalObject() { //TODO: Should be moved to LibGDXProto if(getBinded()==null){return;}//Bad syncable this.setX(getBinded().getX()); this.setY(getBinded().getY()); this.setWidth(getBinded().getWidth()); this.setHeight(getBinded().getHeight()); this.setVisible(getBinded().isVisible()); } }
package ac.iie.nnts.pgserver; import io.hops.exception.StorageException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class CountHelper { public static final String COUNT_QUERY = "select count(*) from %s"; public static final String COUNT_QUERY_UNIQUE = "select count(distinct %s) from %s"; public static final String COUNT_WHERE = "select count(*) from %s where %s"; private static PGServerConnector connector = PGServerConnector.getInstance(); public static int countWhere(String tableName, String condition) throws StorageException { String query = String.format(COUNT_WHERE, tableName, condition); return count(query); } /** * Counts the number of rows in a given table. * <p/> * This creates and closes connection in every request. * * @param tableName * @return Total number of rows a given table. * @throws StorageException */ public static int countAll(String tableName) throws StorageException { // TODO[H]: Is it good to create and close connections in every call? String query = String.format(COUNT_QUERY, tableName); return count(query); } public static int countAllUnique(String tableName, String columnName) throws StorageException { String query = String.format(COUNT_QUERY_UNIQUE, columnName, tableName); return count(query); } private static int count(String query) throws StorageException { Connection conn = null; PreparedStatement s = null; ResultSet result = null; try { conn = connector.obtainSession(); s = conn.prepareStatement(query); result = s.executeQuery(); if (result.next()) { return result.getInt(1); } else { throw new StorageException( String.format("Count result set is empty. Query: %s", query)); } } catch (SQLException ex) { throw new StorageException(ex); } finally { connector.closeSession(conn,s,result); } } /** * Counts the number of rows in a table specified by the table name where * satisfies the given criterion. The criterion should be a valid SLQ * statement. * * @param tableName * @param criterion * E.g. criterion="id > 100". * @return */ public static int countWithCriterion(String tableName, String criterion) throws StorageException { StringBuilder queryBuilder = new StringBuilder(String.format(COUNT_QUERY, tableName)). append(" where "). append(criterion); return count(queryBuilder.toString()); } }
package Tests.Produit; import marche.traitement.Produit.Miel; import marche.traitement.Produit.Produit; import java.time.LocalDate; public class TestProduit { @org.junit.jupiter.api.Test public void test() { Miel miel = new Miel(5, LocalDate.MAX,""); Produit mazer = miel.clone(); mazer.setQuantite(4); System.out.println(mazer.getQuantite() +" "+ miel.getQuantite()); } }
package com.wsg.protocl_7001; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class HashUtil { public static byte[] md5(byte[] src) { return hash(src, "MD5"); } private static byte[] hash(byte[] src, String algorithm) { MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance(algorithm); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("No such algorithm [" + algorithm + "]"); } return messageDigest.digest(src); } }
package com.rex.demo.study.demo.sink; import com.rex.demo.study.demo.constants.KafkaConstants; import com.rex.demo.study.demo.entity.FlinkInitInfo; import com.rex.demo.study.demo.enums.KafkaConfigEnum; import com.rex.demo.study.demo.util.FlinkUtils; import lombok.extern.slf4j.Slf4j; import org.apache.flink.api.common.serialization.SimpleStringSchema; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer; import org.apache.flink.streaming.connectors.kafka.internals.KafkaSerializationSchemaWrapper; import org.apache.flink.streaming.connectors.kafka.partitioner.FlinkKafkaPartitioner; import java.util.Properties; /** * kafka sink 示例 * 使用官方提供的kafka sink * * @Author li zhiqang * @create 2020/12/1 */ @Slf4j public class MyKafkaSink { public static void main(String[] args) throws Exception { // 设置将来访问 hdfs 的使用的用户名, 否则会出现权限不够 System.setProperty("HADOOP_USER_NAME", "hadoop"); FlinkInitInfo flinkKafkaInitInfo = FlinkUtils.getFlinkKafkaInitInfo(FlinkUtils.FlinkStartConfig.builder() .kafKaConfig(KafkaConfigEnum.TEST) .messageTopic(KafkaConstants.LOCATIONS_TOPIC) .messageGroup(KafkaConstants.TEST_CONSUMER_GROUP) .flinkCheckpointConfig(FlinkUtils.FlinkCheckpointConfig.builder().build()) .build()); StreamExecutionEnvironment env = flinkKafkaInitInfo.getEnv(); DataStream<String> messageStream = flinkKafkaInitInfo.getMessageStream(); Properties properties = new Properties(); properties.setProperty("bootstrap.servers", "172.26.55.116:9092"); //增加配置属性操作如下: properties.setProperty("transaction.timeout.ms", String.valueOf(1000*60*5)); FlinkKafkaProducer<String> myProducer = new FlinkKafkaProducer( "testTopic", // target topic new KafkaSerializationSchemaWrapper<String>("testTopic", new FlinkKafkaPartitioner<String>() { @Override public int partition(String record, byte[] key, byte[] value, String targetTopic, int[] partitions) { return 0; } }, true, new SimpleStringSchema()), // serialization schema properties, // producer config FlinkKafkaProducer.Semantic.EXACTLY_ONCE); // fault-tolerance // messageStream.print(); messageStream.addSink(myProducer); env.execute("kafka-flink-Xsink"); } }
package com.timmy.highUI.coordinatorLayout.behavior.zhihuHome; import android.content.Context; import android.support.design.widget.AppBarLayout; import android.support.design.widget.CoordinatorLayout; import android.util.AttributeSet; import android.view.View; import com.timmy.library.util.Logger; /** * Created by admin on 2017/2/8. */ public class ZhihuBottomBehavior extends CoordinatorLayout.Behavior<View> { public ZhihuBottomBehavior(Context context, AttributeSet attrs) { super(context, attrs); } //确定所提供的子视图是否有一个特定的同级视图作为布局从属--我们使用AppBarlayout @Override public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) { return dependency instanceof AppBarLayout; } //响应从属布局的变化 @Override public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) { float translationY = Math.abs(dependency.getTop()); child.setTranslationY(translationY); Logger.d("Zhihu", "translationY:" + translationY); return true; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package talaash.Indexer; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import talaash.ExtraGui.histgui; import talaash.Tasveer_Talaash; /** * * @author asheesh */ public class HistogramIndexer extends Thread{ public String queryimagepath; public HistogramIndexer(String path) { queryimagepath=path; } public int [][] []rgb; public int [][] []rgbvalues; public int size; public int [] counter; public int [][] diffvalue; public int [][] rgbdiffvalue; public int min=99999; int p=0; // bring histogram of all db images public int[] indexer(int arg) throws ClassNotFoundException { try { FileInputStream fis=new FileInputStream(new File("C:/Users/asheesh/Documents/NetBeansProjects/Talaash/abcd.txt")); ObjectInputStream ois=new ObjectInputStream(fis); rgb=(int [][][])ois.readObject(); fis.close(); ois.close(); histgui queryobj=new histgui(); rgbvalues=queryobj.comphist(queryimagepath); size=rgb[0].length; counter=new int[size]; diffvalue=new int[size][2]; rgbdiffvalue=new int[size][2]; for(int i=0;i<size;i++) { diffvalue[i][0]=0; diffvalue[i][1]=0; rgbdiffvalue[i][0]=0; rgbdiffvalue[i][1]=0; for(int j=0;j<255;j++) { diffvalue[i][0]+=Math.abs(rgbvalues[0][0][j]-rgb[0][i][j]); rgbdiffvalue[i][0]+=Math.abs((rgbvalues[1][0][j]-rgb[1][i][j])+((rgbvalues[2][0][j]-rgb[2][i][j]))+(rgbvalues[3][0][j]-rgb[3][i][j])); } } if(arg==1) { counter=getmin(diffvalue); } else if( arg==2) { counter=getmin(rgbdiffvalue); } // System.out.println("counter= "); // for(int i=0;i<20;i++) // System.out.println(counter[i]); } catch(IOException ioe) { System.out.println(ioe); } catch(ClassNotFoundException cnf) { System.out.println(cnf); } return counter; } int [] getmin(int [][]diffvalue) { for(int i=0;i<size;i++) { for(int j=0;j<size;j++) { if((diffvalue[j][0]<=min)&&(diffvalue[j][1]==0)) { min=diffvalue[j][0]; counter[p]=j; } } diffvalue[counter[p]][1]=1; min=99999; p++; } p=0; return counter; } public void setsize () throws ClassNotFoundException { try { FileInputStream fis=new FileInputStream(new File("C:/Users/asheesh/Documents/NetBeansProjects/Talaash/abcd.txt")); ObjectInputStream ois=new ObjectInputStream(fis); rgb=(int [][][])ois.readObject(); fis.close(); ois.close(); this.size=rgb[0].length; System.out.println("size = "+size); } catch(IOException ioe) { System.out.println(ioe); } catch(ClassNotFoundException cnf) { System.out.println(cnf); } } }
package pageobjects; import static org.junit.Assert.assertTrue; import static org.testng.Assert.assertEquals; import java.util.List; import java.util.Map; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import base.TestBase; import cucumber.api.DataTable; public class AdminProfilePage extends TestBase { // setupElements @FindBy(xpath = "//h1[text()='Your Profile']") private WebElement labelYourProfile; @FindBy(xpath = "//h1[text()='Your Profile']/../p[2]") private WebElement labelAdminSuperPower; @FindBy(xpath = "//h1[text()='Your Profile']/../p[1]") private WebElement labelAdminWelcomeText; @FindBy(xpath = "//a[@id='details_link']") private WebElement linkDetails; @FindBy(xpath = "//div[@id='status']/p") private WebElement labelLoginStatus; /* * The By type element is used in the method that verifies if the login page has * loaded, so we can use ExpectedConsitions */ By usersTable = By.xpath("//table[@id='users_list_table']"); public AdminProfilePage() { PageFactory.initElements(driver, this); } public void accessHome(String url) { driver.get(url); } public void validateUsernameAndEmailinTable(String userName, String userEmail) throws InterruptedException { /* * This xpath is not together with the other elements above, because the xpath * must be a constant expression, and in this case we are using two variables to * make it flexible to validate any line of the table. This xpath validates if * we have the correct combination of Username and e-mail in the same line of * the table located in admin Profile Page. */ WebElement userNameAndEmail = driver.findElement(By.xpath("//th[text()='Name']/../..//tr//td[text()='" + userName + "']/following::td[text()='" + userEmail + "']")); assertTrue(userNameAndEmail.isDisplayed()); } public void doClickDetails() { linkDetails.click(); } public void validateLoggedUserInfo(String expectedLoggedUserInfo) throws InterruptedException { String actualUserInfo = labelLoginStatus.getText(); /* * Here we remove the text related to log out link which is a child element from * labelLoginStatus */ actualUserInfo = actualUserInfo.replaceAll("log out", "").trim(); assertEquals(actualUserInfo, expectedLoggedUserInfo); } public void validateAdminSuperPower(String expectedAdminSuperPower) throws InterruptedException { String actualSuperPower = labelAdminSuperPower.getText(); assertEquals(actualSuperPower, expectedAdminSuperPower); } public void validateAdminWelcomeText(String expectedAdminWelcomeText) throws InterruptedException { String actualAdminWelcomeText = labelAdminWelcomeText.getText(); assertEquals(actualAdminWelcomeText, expectedAdminWelcomeText); } public void validateUsernameAndEmailInTable(DataTable table) throws InterruptedException { String name, email; List<Map<String, String>> maps = table.asMaps(String.class, String.class); /* * Go the table and gets the name and email, then uses the values to create the * xpath which is going to validate if we have the correct Name and Email in the * same line. */ for (Map<String, String> map : maps) { name = map.get("Name"); email = map.get("Email"); /* * This xpath is not together with the other mapped elements above, because the * xpath must be a constant expression, and in this case we are using two * variables to make it flexible to validate any line of the table. This xpath * validates if we have the correct combination of Username and e-mail in the * same line of the table located in admin Profile Page. */ WebElement userNameAndEmail = driver.findElement(By.xpath( "//th[text()='Name']/../..//tr//td[text()='" + name + "']/following::td[text()='" + email + "']")); assertTrue(userNameAndEmail.isDisplayed()); } } /* * This method wait for the list of users table to be displayed, so we will know when * the Admin Profile page has loaded. This is necessary because sometimes the automation * runs so fast that it tries to click on elements before they are displayed displayed. */ public void verifyAdminProfilePageHasLoaded() { new WebDriverWait(driver, 5).until(ExpectedConditions.presenceOfElementLocated(usersTable)); } }
package com.tencent.mm.plugin.downloader.model; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.support.v4.app.z.d; import com.tencent.mm.kernel.g; import com.tencent.mm.loader.stub.b; import com.tencent.mm.plugin.appbrand.s$l; import com.tencent.mm.plugin.cdndownloader.ipc.CDNTaskInfo; import com.tencent.mm.plugin.cdndownloader.ipc.CDNTaskState; import com.tencent.mm.plugin.downloader.b.c; import com.tencent.mm.plugin.downloader.ui.FileDownloadConfirmUI; import com.tencent.mm.sdk.platformtools.ac; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.ao; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import java.io.File; import java.util.HashMap; import java.util.concurrent.ConcurrentHashMap; import org.json.JSONException; import org.json.JSONObject; public final class a extends h { private static final String ibz = (b.bnE + "BigFile"); private byte[] dsN; private com.tencent.mm.plugin.cdndownloader.c.b hKd; private HashMap<String, Long> ibA; private HashMap<String, Long> ibB; private ConcurrentHashMap<String, Integer> ibC; private HashMap<String, Long> ibD; private HashMap<String, Long> ibE; private Context mContext; static /* synthetic */ void a(a aVar, String str, int i, int i2, boolean z) { x.d("MicroMsg.FileCDNDownloader", "state = %d, progress = %d, firstShown = %b", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), Boolean.valueOf(z)}); com.tencent.mm.plugin.downloader.c.a yN = c.yN(str); if (yN == null) { x.e("MicroMsg.FileCDNDownloader", "updateNotification failed: null task info"); } else if (yN.field_showNotification) { d dVar = new d(aVar.mContext); if (z) { long currentTimeMillis = System.currentTimeMillis(); aVar.ibA.put(str, Long.valueOf(currentTimeMillis)); dVar.g(currentTimeMillis); } else { Long l = (Long) aVar.ibA.get(str); if (l != null) { dVar.g(l.longValue()); } } dVar.b(yN.field_fileName); switch (i) { case 1: dVar.Y(17301633); dVar.b(100, i2, i2 == 0); dVar.c(aVar.mContext.getString(c.file_downloader_download_running)); dVar.j(2, true); long j = yN.field_downloadId; Intent intent = new Intent(aVar.mContext, FileDownloadConfirmUI.class); intent.putExtra("extra_download_id", j); dVar.pu = PendingIntent.getActivity(aVar.mContext, (int) System.currentTimeMillis(), intent, 268435456); break; case 4: dVar.Y(17301634); dVar.u(true); dVar.pu = PendingIntent.getActivity(ad.getContext(), 0, new Intent(), 0); dVar.c(aVar.mContext.getString(c.file_downloader_download_failed)); break; default: aVar.cancelNotification(str); return; } synchronized (aVar.dsN) { Integer num = (Integer) aVar.ibC.get(str); if (num == null) { aVar.ibC.put(str, Integer.valueOf(((com.tencent.mm.plugin.notification.b.a) g.n(com.tencent.mm.plugin.notification.b.a.class)).getNotification().b(dVar.build()))); } else { ((com.tencent.mm.plugin.notification.b.a) g.n(com.tencent.mm.plugin.notification.b.a.class)).getNotification().notify(num.intValue(), dVar.build()); } if (i == 4) { aVar.ibC.remove(str); } } } } public a(b bVar) { super(bVar); this.dsN = new byte[0]; this.ibD = new HashMap(); this.ibE = new HashMap(); this.hKd = new 1(this); this.mContext = ad.getContext(); this.ibA = new HashMap(); this.ibB = new HashMap(); this.ibC = new ConcurrentHashMap(); com.tencent.mm.plugin.cdndownloader.c.a.aAk().hKd = this.hKd; } public final long a(com.tencent.mm.plugin.downloader.c.a aVar) { new Thread(new 2(this, aVar)).start(); return aVar.field_downloadId; } public final long a(e eVar) { if (eVar == null || bi.oW(eVar.fhq)) { x.e("MicroMsg.FileCDNDownloader", "Invalid Request"); return -1; } String str = eVar.fhq; com.tencent.mm.plugin.downloader.c.a yN = c.yN(str); FileDownloadTaskInfo fileDownloadTaskInfo = null; if (yN != null) { fileDownloadTaskInfo = cm(yN.field_downloadId); x.i("MicroMsg.FileCDNDownloader", "addDownloadTask, status = " + fileDownloadTaskInfo.status); if (fileDownloadTaskInfo.status == 1) { return fileDownloadTaskInfo.id; } } if (yN == null) { yN = c.yK(eVar.mAppId); } File file = new File(ibz); if (!file.exists()) { if (!file.getParentFile().exists()) { File parentFile = file.getParentFile(); File file2 = new File(parentFile.getAbsolutePath() + System.currentTimeMillis()); if (file2.mkdirs()) { file2.renameTo(parentFile); } else { x.e("MicroMsg.FileCDNDownloader", "mkdir parent error, %s", new Object[]{parentFile.getAbsolutePath()}); } } x.i("MicroMsg.FileCDNDownloader", "Make download dir result: %b", new Object[]{Boolean.valueOf(file.mkdirs())}); } c.yL(str); c.yM(eVar.mAppId); com.tencent.mm.plugin.downloader.c.a c = f.c(eVar); if (!eVar.ici || yN == null) { c.field_downloadId = System.currentTimeMillis(); } else { c.field_downloadId = yN.field_downloadId; } c.field_downloaderType = 3; c.field_filePath = ibz + "/" + ac.ce(str); if (fileDownloadTaskInfo == null || !c.field_filePath.equals(fileDownloadTaskInfo.path)) { c.field_startState = 0; } else { String str2 = c.field_filePath; str = fileDownloadTaskInfo.path; if (!(str2 == null || str == null || str2.equals(str))) { if (new File(str).exists()) { x.i("MicroMsg.FileCDNDownloader", "Delete previous file result: %b", new Object[]{Boolean.valueOf(new File(str).delete())}); } } if (fileDownloadTaskInfo.status == 2) { c.field_startState = com.tencent.mm.plugin.downloader.a.b.ibt; } else if (fileDownloadTaskInfo.status == 4) { c.field_startState = com.tencent.mm.plugin.downloader.a.b.ibu; } else { c.field_startState = com.tencent.mm.plugin.downloader.a.b.ibs; } c.field_startSize = fileDownloadTaskInfo.icq; x.d("MicroMsg.FileCDNDownloader", "addDownloadTask, startSize = " + fileDownloadTaskInfo.icq); } c.field_startTime = System.currentTimeMillis(); if (!eVar.fGM || ao.isWifi(ad.getContext())) { return a(c); } x.i("MicroMsg.FileCDNDownloader", "downloadInWifi, not in wifi"); c.field_status = 0; c.d(c); return c.field_downloadId; } private static CDNTaskInfo b(com.tencent.mm.plugin.downloader.c.a aVar) { CDNTaskInfo cDNTaskInfo = new CDNTaskInfo(); cDNTaskInfo.dQc = true; cDNTaskInfo.mediaId = aVar.field_downloadUrl; cDNTaskInfo.downloadUrl = aVar.field_downloadUrl; cDNTaskInfo.filePath = aVar.field_filePath; cDNTaskInfo.hKj = aVar.field_secondaryUrl; cDNTaskInfo.hKl = 15; cDNTaskInfo.hKm = 3600; cDNTaskInfo.hKn = true; cDNTaskInfo.hKo = aVar.field_downloadInWifi; JSONObject jSONObject = new JSONObject(); try { if (aVar.field_fileSize > 0) { jSONObject.put("Content-Length", aVar.field_fileSize); } cDNTaskInfo.hKk = jSONObject.toString(); } catch (JSONException e) { x.e("MicroMsg.FileCDNDownloader", "addVerifyHeaders: " + e.getMessage()); } return cDNTaskInfo; } public final int cl(long j) { new Thread(new 3(this, j)).start(); return 1; } public final FileDownloadTaskInfo cm(long j) { FileDownloadTaskInfo fileDownloadTaskInfo = null; com.tencent.mm.plugin.downloader.c.a cs = c.cs(j); if (cs != null) { fileDownloadTaskInfo = new FileDownloadTaskInfo(); CDNTaskState yl = com.tencent.mm.plugin.cdndownloader.c.a.aAk().yl(cs.field_downloadUrl); if (yl != null) { switch (yl.taskState) { case s$l.AppCompatTheme_buttonStyle /*100*/: case s$l.AppCompatTheme_buttonStyleSmall /*101*/: fileDownloadTaskInfo.status = 1; break; case s$l.AppCompatTheme_checkboxStyle /*102*/: fileDownloadTaskInfo.status = 2; break; default: if (cs.field_status != 1) { fileDownloadTaskInfo.status = cs.field_status; break; } fileDownloadTaskInfo.status = 0; break; } fileDownloadTaskInfo.icq = (long) yl.completeSize; fileDownloadTaskInfo.gTK = (long) yl.fileTotalSize; if (!(fileDownloadTaskInfo.status == 0 || fileDownloadTaskInfo.status == 5)) { cs.field_downloadedSize = fileDownloadTaskInfo.icq; cs.field_totalSize = fileDownloadTaskInfo.gTK; c.e(cs); } } else { if (cs.field_status == 1) { fileDownloadTaskInfo.status = 0; } else { fileDownloadTaskInfo.status = cs.field_status; } fileDownloadTaskInfo.icq = cs.field_downloadedSize; fileDownloadTaskInfo.gTK = cs.field_totalSize; } fileDownloadTaskInfo.id = j; fileDownloadTaskInfo.bPG = cs.field_downloaderType; fileDownloadTaskInfo.icr = cs.field_autoDownload; fileDownloadTaskInfo.path = cs.field_filePath; fileDownloadTaskInfo.url = cs.field_downloadUrl; fileDownloadTaskInfo.bKg = cs.field_md5; } return fileDownloadTaskInfo; } public final boolean cn(long j) { new Thread(new 4(this, j)).start(); return true; } public final boolean co(long j) { com.tencent.mm.plugin.downloader.c.a cs = c.cs(j); if (cs == null) { return false; } if (!cs.field_downloadInWifi || ao.isWifi(ad.getContext())) { new Thread(new 5(this, cs, j)).start(); return true; } x.i("MicroMsg.FileCDNDownloader", "resumeDownloadTask, downloadInWifi, not wifi"); return true; } private void cancelNotification(String str) { synchronized (this.dsN) { Integer num = (Integer) this.ibC.get(str); if (num == null) { x.i("MicroMsg.FileCDNDownloader", "No notification id found"); return; } ((com.tencent.mm.plugin.notification.b.a) g.n(com.tencent.mm.plugin.notification.b.a.class)).getNotification().cancel(num.intValue()); x.i("MicroMsg.FileCDNDownloader", "cancelNotification, id = " + num); this.ibC.remove(str); } } }
package com.ojas.rpo.security.dao.location; import java.util.List; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import org.springframework.transaction.annotation.Transactional; import com.ojas.rpo.security.dao.JpaDao; import com.ojas.rpo.security.entity.Location; /** * * @author Jyothi.Gurijala * */ public class JpaLocationDao extends JpaDao<Location, Long>implements LocationDao { public JpaLocationDao() { super(Location.class); } /* * (non-Javadoc) * * @see com.ojas.rpo.security.dao.JpaDao#findAll() */ @Override @Transactional(readOnly = true) public List<Location> findAll() { final CriteriaBuilder builder = this.getEntityManager().getCriteriaBuilder(); final CriteriaQuery<Location> criteriaQuery = builder.createQuery(Location.class); Root<Location> root = criteriaQuery.from(Location.class); criteriaQuery.orderBy(builder.desc(root.get("date"))); TypedQuery<Location> typedQuery = this.getEntityManager().createQuery(criteriaQuery); return typedQuery.getResultList(); } }
package jp.smartcompany.job.modules.quartz.pojo.dto; import jp.smartcompany.job.group.UpdateGroup; import jp.smartcompany.job.modules.quartz.JobValidateMessage; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.Range; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; /** * @author Xiao Wenpeng */ @Getter @Setter @ToString public class ScheduleJobDTO { /** * 任务ID */ @NotNull(message= JobValidateMessage.JOB_ID_EMPTY,groups = UpdateGroup.class) private Integer jobId; /** * spring bean名称 */ @NotBlank(message= JobValidateMessage.BEAN_NAME_EMPTY) @Length(min=1,max=100,message = JobValidateMessage.BEAN_NAME_LENGTH_1_100) private String beanName; /** * 参数 */ @Length(min=1,max=100,message = JobValidateMessage.PARAM_LENGTH_1_100) private String params; /** * cron表达式 */ @NotBlank(message=JobValidateMessage.JOB_EXPRESS_EMPTY) @Length(min=1,max=100,message = JobValidateMessage.EXPRESS_LENGTH_1_100) private String cronExpression; /** * 任务状态 */ @NotNull(message=JobValidateMessage.TASK_STATUS_EMPTY) @Range(min=0,max = 1,message=JobValidateMessage.TASK_STATUS_INVALID) private Integer status; /** * 备注 */ private String remark; }
package com.tencent.mm.ipcinvoker.wx_extension; import com.tencent.mm.ab.b; import com.tencent.mm.ab.l; import com.tencent.mm.ab.v; import com.tencent.mm.ipcinvoker.a; import com.tencent.mm.ipcinvoker.c; import com.tencent.mm.ipcinvoker.wx_extension.service.IPCRunCgiRespWrapper; import com.tencent.mm.sdk.platformtools.x; final class b$b implements a<b, IPCRunCgiRespWrapper> { private b$b() { } public final /* synthetic */ void a(Object obj, final c cVar) { b bVar = (b) obj; if (bVar == null || bVar.dIE.dIL.getClass() == com.tencent.mm.bk.a.class) { x.e("MicroMsg.IPCRunCgi", "InvokeTask, mm received invalid rr %s", new Object[]{bVar}); if (cVar != null) { cVar.at(IPCRunCgiRespWrapper.CF()); return; } return; } v.a(bVar, new v.a() { public final int a(int i, int i2, String str, b bVar, l lVar) { if (cVar != null) { IPCRunCgiRespWrapper iPCRunCgiRespWrapper = new IPCRunCgiRespWrapper(); iPCRunCgiRespWrapper.errType = i; iPCRunCgiRespWrapper.errCode = i2; iPCRunCgiRespWrapper.Yy = str; iPCRunCgiRespWrapper.diG = bVar; cVar.at(iPCRunCgiRespWrapper); } return 0; } }, true); } }
package org.sang.controller; import org.sang.bean.*; import org.sang.service.LikesService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * Created by albert on 2019/12/19. */ @RestController @RequestMapping("/likes") public class LikesController { @Autowired LikesService likesService; @RequestMapping(value = "/getlikes", method = RequestMethod.POST) public Likes getLikes(Likes likes) { return likesService.getLikes(likes); } @RequestMapping(value = "/delete", method = RequestMethod.POST) public RespBean deletelike(Likes likes) { int result = likesService.deletelike(likes); if (result == 1) { return new RespBean("success", "删除成功!"); } return new RespBean("error", "删除失败!"); } @RequestMapping(value = "/add", method = RequestMethod.POST) public RespBean add(Likes likes, Long aid) { int result = likesService.add(likes); if (result == 1) { return new RespBean("success", "点赞成功!"); } return new RespBean("error", "点赞失败!"); } @RequestMapping(value = "/adddislike", method = RequestMethod.POST) public RespBean adddislike(Long aid) { int result = likesService.adddislike(aid); if (result == 1) { return new RespBean("success", "差评成功!"); } return new RespBean("error", "差评失败!"); } }
package m; import android.os.Handler; import org.json.JSONObject; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import bean.Duanzibean; import bean.Guanggao; import bean.TuijianBean; import bean.UserBean; import fragment.Tuijian; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; import io.reactivex.subscribers.DisposableSubscriber; import mybase.Basebean; import okhttp3.ResponseBody; import utils.MyQusetUtils; /** * Created by 地地 on 2017/11/28. * 邮箱:461211527@qq.com. */ public class Getdatamodle { @Inject public Getdatamodle() { } private CompositeDisposable compositeDisposable=new CompositeDisposable(); public void getduanzidata(int page ,final requestBack requestBack){ new MyQusetUtils.Builder().addConverterFactory() .addCallAdapterFactory().build().getQuestInterface().getdata(page) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<Basebean<List<Duanzibean>>>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(Basebean<List<Duanzibean>> value) { requestBack.success(value.data); } @Override public void onError(Throwable e) { requestBack.fail(e); } @Override public void onComplete() { } }); } public void getad(final AdBack adBack){ new MyQusetUtils.Builder().addConverterFactory() .addCallAdapterFactory().build().getQuestInterface().getad() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<Basebean<List<Guanggao>>>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(Basebean<List<Guanggao>> value) { adBack.success(value.data,value.msg,value.code); } @Override public void onError(Throwable e) { } @Override public void onComplete() { } }); } public void changenicheng(int uid ,String nickname,final XiuniBack requestBack){ new MyQusetUtils.Builder().addConverterFactory() .addCallAdapterFactory().build().getQuestInterface().xiunicheng(uid,nickname) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<Basebean>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(Basebean value) { requestBack.success(value.code,value.msg); } @Override public void onError(Throwable e) { requestBack.fail(e); } @Override public void onComplete() { } }); } public void getuserdata(int uid ,int page,final GetuserdataBack requestBack){ DisposableSubscriber<Basebean<List<TuijianBean>>> disposableSubscriber = new MyQusetUtils.Builder().addConverterFactory() .addCallAdapterFactory().build().getQuestInterface().getuserdata(uid, page) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeWith(new DisposableSubscriber<Basebean<List<TuijianBean>>>() { @Override public void onNext(Basebean<List<TuijianBean>> listBasebean) { requestBack.success(listBasebean.data); } @Override public void onError(Throwable t) { requestBack.fail(t); } @Override public void onComplete() { } }); compositeDisposable.add(disposableSubscriber); } public void ondestory(){ if(!compositeDisposable.isDisposed()){ compositeDisposable.dispose(); } } public void gettuijian(String uid, int type, int page, final requesttuijianBack requesttuijianBack){ new MyQusetUtils.Builder().addConverterFactory() .addCallAdapterFactory().build().getQuestInterface().gettuijian(uid,type,page) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<Basebean<List<TuijianBean>>>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(Basebean<List<TuijianBean>> value) { requesttuijianBack.success(value.data); } @Override public void onError(Throwable e) { requesttuijianBack.fail(e); } @Override public void onComplete() { } }); } public void getspremen(int page, final requesttuijianBack requesttuijianBack){ new MyQusetUtils.Builder().addConverterFactory() .addCallAdapterFactory().build().getQuestInterface().spremen(page) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<Basebean<List<TuijianBean>>>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(Basebean<List<TuijianBean>> value) { requesttuijianBack.success(value.data); } @Override public void onError(Throwable e) { requesttuijianBack.fail(e); } @Override public void onComplete() { } }); } public interface requestBack{ void success(List<Duanzibean> list); void fail(Throwable e); } public interface XiuniBack{ void success(String code,String msg); void fail(Throwable e); } public interface AdBack{ void success(List<Guanggao> list,String msg ,String code); void fail(Throwable e); } public interface requesttuijianBack{ void success(List<TuijianBean> list); void fail(Throwable e); } public interface GetuserdataBack{ void success(List<TuijianBean> list); void fail(Throwable e); } }
package MiddleClass; /** * @author renyujie518 * @version 1.0.0 * @ClassName nearMultiple4Times.java * @Description * 给定一个数组arr, 如果通过调整可以做到arr中任意两个相邻的数字相乘是4的倍数, 返回true; 如果不能返回false * * 思路: * 遍历数组 找到四种数:奇数 a个 偶数只有一个2因子 b个 偶数包含4因子 c 个 * 思路: * 当b = 0的时候 什么情况下用到c的个数最少: 奇4奇4... 观察发现 a>=1 c就要>=a-1 * 当b!=0 22...4奇4奇.... 在2都放在前面的情况下 a = 0 c>=0;a>=1 c>=a * * * @createTime 2021年07月30日 16:49:00 */ public class nearMultiple4Times { public static boolean nearMultiple4Times(int[] arr) { //奇数 a个 int a = 0; //偶数只有一个2因子(是偶数但不是4的倍数的数) b个 int b = 0; //是4的倍数的数 c个 int c = 0; for (int i = 0; i < arr.length; i++) { if ((arr[i] & 1) != 0) { //&按位与 (两个为真才为真 一个数 & 1的结果就是取二进制的最末位。 // 这可以用来判断一个整数的奇偶,二进制的最末位为0表示该数为偶数,最末位为1表示该数为奇数 a++; } else { //一定是偶数 if (arr[i] % 4 == 0) { c++; } else { b++; } } } return b == 0 ? (c >= a - 1) : (c >= a); } }
package com.smxknife.servlet.async.servlet; import javax.servlet.*; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.concurrent.TimeUnit; /** * @author smxknife * 2020/7/9 */ @WebServlet(name = "indexServlet", urlPatterns = "/*", asyncSupported = true) public class IndexServlet extends HttpServlet { @Override public void init(ServletConfig config) throws ServletException { System.out.println(config.getServletName() + " init..."); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); try { PrintWriter writer = resp.getWriter(); writer.println("servlet started.<br/>"); writer.flush(); AsyncContext asyncContext = req.startAsync(); asyncContext.addListener(getListener()); asyncContext.start(new IndexAsyncThread(asyncContext)); writer.println("servlet end.<br/>"); writer.flush(); } catch (Exception e) { } } private AsyncListener getListener() { return new AsyncListener() { @Override public void onComplete(AsyncEvent asyncEvent) throws IOException { asyncEvent.getSuppliedResponse().getWriter().close(); System.out.println("listen thread completed."); } @Override public void onTimeout(AsyncEvent asyncEvent) throws IOException { System.out.println("listen thread timeout"); } @Override public void onError(AsyncEvent asyncEvent) throws IOException { System.out.println("listen thread error"); } @Override public void onStartAsync(AsyncEvent asyncEvent) throws IOException { System.out.println("listen thread start"); } }; } static class IndexAsyncThread extends Thread { private AsyncContext asyncContext; public IndexAsyncThread(AsyncContext asyncContext) { this.asyncContext = asyncContext; } @Override public void run() { try { TimeUnit.SECONDS.sleep(3); PrintWriter writer = asyncContext.getResponse().getWriter(); writer.println("async handler..."); writer.flush(); asyncContext.complete(); } catch (Exception e) { e.printStackTrace(); } } } }
package com.fancy.ownparking.ui.activate; import android.text.TextUtils; import com.fancy.ownparking.data.local.LocalDatabase; import com.fancy.ownparking.ui.base.mvp.BasePresenter; import io.reactivex.Flowable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; public class ActivationPresenter extends BasePresenter<ActivationContract.View> implements ActivationContract.Presenter { public ActivationPresenter(ActivationContract.View view, LocalDatabase database) { super(view, database); } @Override public void changePassword(int id, String email, String newPassword) { if (TextUtils.isEmpty(email) || TextUtils.isEmpty(newPassword)) { getMvpView().onDataEmpty(); return; } // TODO: 12.05.2018 email matcher mCompositeDisposable.add( mLocalDataManager.isUserExists(email) .subscribeOn(Schedulers.io()) .flatMap(count -> { if (count == 0) { mLocalDataManager.changePassword(id, email, newPassword); } return Flowable.just(count); }) .observeOn(AndroidSchedulers.mainThread()) .subscribe(count -> { if (count > 0) { getMvpView().wrongEmail(); return; } getMvpView().changePasswordSuccess(); }, throwable -> { getMvpView().changePasswordFail(); getMvpView().onError(throwable); }) ); } @Override public void addUserInfo(int id, String firstName, String lastName) { if (TextUtils.isEmpty(firstName) || TextUtils.isEmpty(lastName)) { getMvpView().onDataEmpty(); return; } mCompositeDisposable.add( mLocalDataManager.updateUserInfo(id, firstName, lastName) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(res -> getMvpView().updateSuccess(), throwable -> { getMvpView().updateFail(); getMvpView().onError(throwable); }) ); getMvpView().updateSuccess(); } }
package com.ericlam.mc.minigames.core.event.player; import com.ericlam.mc.minigames.core.game.GameState; import com.ericlam.mc.minigames.core.game.InGameState; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerEvent; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * 遊戲玩家準備加入時觸發的事件。 * <p> * 此事件可以被取消。當取消事件後,小遊戲系統將不會把該玩家加入為遊戲玩家。 */ public final class GamePlayerPreJoinEvent extends PlayerEvent implements Cancellable { private static final HandlerList handerlist = new HandlerList(); private boolean cancelled; private GameState state; private InGameState inGameState; public GamePlayerPreJoinEvent(Player who, GameState state, @Nullable InGameState inGameState) { super(who); this.cancelled = false; this.state = state; this.inGameState = inGameState; } @Nonnull @Override public HandlerList getHandlers() { return handerlist; } @Override public boolean isCancelled() { return cancelled; } @Override public void setCancelled(boolean b) { this.cancelled = b; } /** * 獲取遊戲狀態 * * @return 遊戲狀態 */ public GameState getState() { return state; } /** * 獲取場地狀態 * @return 場地狀態 */ @Nullable public InGameState getInGameState() { return inGameState; } }
package com.tencent.mm.plugin.sns.ui; import android.app.Activity; import android.content.Intent; import android.view.MenuItem; import com.tencent.mm.g.a.cb; import com.tencent.mm.g.a.ch; import com.tencent.mm.g.a.pt; import com.tencent.mm.plugin.sns.c.a; import com.tencent.mm.plugin.sns.data.i; import com.tencent.mm.plugin.sns.i.j; import com.tencent.mm.plugin.sns.model.af; import com.tencent.mm.plugin.sns.model.aj; import com.tencent.mm.plugin.sns.model.an; import com.tencent.mm.plugin.sns.storage.n; import com.tencent.mm.pluginsdk.ui.tools.l; import com.tencent.mm.protocal.c.ate; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.av; import com.tencent.mm.ui.base.n.d; class FlipView$4 implements d { final /* synthetic */ String fQh; final /* synthetic */ String fYI; final /* synthetic */ FlipView nNe; final /* synthetic */ String sl; FlipView$4(FlipView flipView, String str, String str2, String str3) { this.nNe = flipView; this.fQh = str; this.fYI = str2; this.sl = str3; } public final void onMMMenuItemSelected(MenuItem menuItem, int i) { n Nl = af.byo().Nl(this.fQh); if (Nl == null) { x.i("MicroMsg.FlipView", "error beacause info null"); return; } n Nl2; switch (menuItem.getItemId()) { case 0: if (Nl.field_type != 15) { l.i(this.fYI, FlipView.e(this.nNe)); return; } else { FlipView.NL(this.fQh); return; } case 1: if (Nl.field_type != 15) { Intent intent = new Intent(); intent.putExtra("Retr_File_Name", this.fYI); intent.putExtra("Retr_Compress_Type", 0); intent.putExtra("Retr_Msg_Type", 0); if (Nl != null) { intent.putExtra("Retr_FromMainTimeline", this.nNe.bBX()); intent.putExtra("Retr_KSnsId", i.g(Nl)); } a.ezn.l(intent, FlipView.e(this.nNe)); return; } new StringBuilder().append(an.s(af.getAccSnsPath(), this.sl)).append(i.e((ate) Nl.bAJ().sqc.ruA.get(0))); FlipView.NM(this.fQh); return; case 2: ch chVar; pt ptVar; if (Nl.field_type != 15) { chVar = new ch(); String str = this.fQh; String str2 = this.sl; if (str2 == null || bi.oW(str)) { x.w("MicroMsg.Sns.GetFavDataSource", "fill favorite event fail, event is null or snsId error or position errro"); chVar.bJF.bJL = j.favorite_fail_argument_error; } else if (af.bxX()) { x.w("MicroMsg.Sns.GetFavDataSource", "fill favorite event fail, sns core is invalid"); chVar.bJF.bJL = j.favorite_fail_system_error; } else { Nl2 = af.byo().Nl(str); if (Nl2 == null) { x.w("MicroMsg.Sns.GetFavDataSource", "fill favorite event fail, snsInfo is null"); chVar.bJF.bJL = j.favorite_fail_attachment_not_exists; } else { com.tencent.mm.plugin.sns.i.a.a(chVar, Nl2, str2); } } chVar.bJF.bJM = 13; chVar.bJF.activity = (Activity) FlipView.e(this.nNe); com.tencent.mm.sdk.b.a.sFg.m(chVar); if (this.nNe.bBX()) { ptVar = new pt(); ptVar.caz.bSZ = i.g(Nl); ptVar.caz.bKW = Nl.bBe(); com.tencent.mm.sdk.b.a.sFg.m(ptVar); return; } return; } else if (Nl != null) { if (Nl.xb(32)) { chVar = new ch(); com.tencent.mm.plugin.sns.i.a.a(chVar, Nl); chVar.bJF.bJM = 14; chVar.bJF.activity = (Activity) FlipView.e(this.nNe); com.tencent.mm.sdk.b.a.sFg.m(chVar); } else { FlipView.o(this.nNe.bBX(), Nl.bBe()); } if (this.nNe.bBX()) { ptVar = new pt(); ptVar.caz.bSZ = i.g(Nl); ptVar.caz.bKW = Nl.bBe(); com.tencent.mm.sdk.b.a.sFg.m(ptVar); return; } return; } else { return; } case 3: Intent intent2 = new Intent(); intent2.putExtra("k_expose_msg_id", this.nNe.getSnsId()); Nl2 = af.byo().fi(this.nNe.getSnsId()); intent2.putExtra("k_username", Nl2 == null ? "" : Nl2.field_userName); intent2.putExtra("showShare", false); intent2.putExtra("rawUrl", "https://weixin110.qq.com/security/readtemplate?t=weixin_report/w_type&scene=%d#wechat_redirect33"); intent2.putExtra("rawUrl", String.format("https://weixin110.qq.com/security/readtemplate?t=weixin_report/w_type&scene=%d#wechat_redirect", new Object[]{Integer.valueOf(33)})); com.tencent.mm.bg.d.b(FlipView.e(this.nNe), "webview", ".ui.tools.WebViewUI", intent2); return; case 4: x.i("MicroMsg.FlipView", "request deal QBAR string"); cb cbVar = new cb(); cbVar.bJq.activity = (Activity) FlipView.e(this.nNe); cbVar.bJq.bHL = FlipView.f(this.nNe); cbVar.bJq.bJr = FlipView.g(this.nNe); cbVar.bJq.bJs = FlipView.h(this.nNe); ate a = aj.a(Nl, this.sl); if (a != null) { cbVar.bJq.imagePath = a.jPK; cbVar.bJq.bJw = a.rVV; } cbVar.bJq.scene = 38; if (FlipView.e(this.nNe) instanceof Activity) { cbVar.bJq.bJx = ((Activity) FlipView.e(this.nNe)).getIntent().getBundleExtra("_stat_obj"); } if (this.nNe instanceof SnsInfoFlip) { SnsInfoFlip snsInfoFlip = (SnsInfoFlip) this.nNe; av fromScene = snsInfoFlip.getFromScene(); x.d("MicroMsg.FlipView", "from Scene: %s", new Object[]{fromScene.tag}); if (fromScene.tag.equals(av.tbn.tag) || fromScene.tag.equals(av.tbo.tag) || fromScene.tag.equals(av.tbp.tag)) { cbVar.bJq.bJt = 5; if (bi.oW(snsInfoFlip.username)) { x.i("MicroMsg.FlipView", "empty username"); snsInfoFlip.username = ""; } cbVar.bJq.bhd = snsInfoFlip.username; } else if (fromScene.tag.equals(av.tbm.tag)) { cbVar.bJq.bJt = 3; } else { x.i("MicroMsg.FlipView", "other scene_from: %s", new Object[]{fromScene.tag}); } } com.tencent.mm.sdk.b.a.sFg.m(cbVar); return; case 5: if (Nl.bAJ().sqc.ruA.size() != 0) { Intent intent3 = new Intent(); if (Nl.field_type == 1) { int position = this.nNe.getPosition(); int size = Nl.bAJ().sqc.ruA.size(); if (size <= 1 || position <= 1 || position > size) { position = 0; } else { position--; } String g = FlipView.g(this.fYI, FlipView.e(this.nNe)); if (g != null) { intent3.putExtra("sns_send_data_ui_image_path", g); intent3.putExtra("sns_send_data_ui_image_position", position); } else { return; } } intent3.putExtra("sns_send_data_ui_activity", true); intent3.putExtra("sns_local_id", this.fQh); com.tencent.mm.bg.d.e(FlipView.e(this.nNe), ".ui.chatting.ChattingSendDataToDeviceUI", intent3); return; } return; case 6: this.nNe.NK(this.fYI); return; default: return; } } }
package com.dao; import com.pojo.Dept; import java.sql.*; import java.util.ArrayList; import java.util.List; public class DeptDao extends BaseDao{ private Connection conn; private PreparedStatement pstm; private ResultSet rs; private Statement st; public void update(Dept dept) { conn = getConn(); try { pstm = conn.prepareStatement("update dept set dname=? where did=?"); pstm.setString(1,dept.getDname()); pstm.setInt(2,dept.getDid()); pstm.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); }finally { close(); } } public Dept getOne(int did) { Dept dept=new Dept(); conn = getConn(); try { pstm = conn.prepareStatement("select * from dept where did=?"); pstm.setInt(1,did); rs = pstm.executeQuery(); while (rs!=null && rs.next()) { String dname = rs.getString(2); dept.setDid(did); dept.setDname(dname); } } catch (SQLException e) { e.printStackTrace(); }finally { close(); } return dept; } public void delete(int did) { conn = getConn(); try { pstm = conn.prepareStatement("delete from dept where did=?"); pstm.setInt(1,did); pstm.execute(); } catch (SQLException e) { e.printStackTrace(); }finally { close(); } } //添加 public void add(Dept dept) { conn = getConn(); try { pstm = conn.prepareStatement("insert into dept values(null,?)"); pstm.setString(1,dept.getDname()); pstm.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); }finally { close(); } } //全查询 public List<Dept> list() { List<Dept> depts=new ArrayList<>(); conn = getConn(); try { pstm = conn.prepareStatement("select * from dept"); rs = pstm.executeQuery(); while (rs!=null && rs.next()) { int did = rs.getInt(1); String dname = rs.getString(2); Dept dept =new Dept(did,dname); depts.add(dept); } } catch (SQLException e) { e.printStackTrace(); }finally { close(); } return depts; } }
package com.internousdev.ecsite.action; public class ItemCreateCompleteAction extends ActionSupport implements SessionAware{ public Map<String,Object> session; public String execute()throws SQLException{ ItemCreateComp; } }
package cc.isotopestudio.Strength.data; import java.sql.Statement; public class PlayerData { public static Statement statement; }
package com.tencent.mm.plugin.account.friend.a; import android.content.ContentValues; import android.database.Cursor; import com.tencent.mm.bt.h; import com.tencent.mm.sdk.e.m; import com.tencent.mm.sdk.platformtools.bg; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import java.util.ArrayList; import java.util.List; public final class b extends m { public static final String[] diD = new String[]{"CREATE TABLE IF NOT EXISTS addr_upload2 ( id int PRIMARY KEY , md5 text , peopleid text , uploadtime long , realname text , realnamepyinitial text , realnamequanpin text , username text , nickname text , nicknamepyinitial text , nicknamequanpin text , type int , moblie text , email text , status int , reserved1 text , reserved2 text , reserved3 int , reserved4 int , lvbuf BLOG , showhead int ) ", "CREATE INDEX IF NOT EXISTS upload_time_index ON addr_upload2 ( uploadtime ) ", "CREATE INDEX IF NOT EXISTS addr_upload_user_index ON addr_upload2 ( username ) "}; public final h dCZ; public b(h hVar) { this.dCZ = hVar; String str = "addr_upload2"; Cursor b = hVar.b("PRAGMA table_info( " + str + " )", null, 2); int columnIndex = b.getColumnIndex("name"); Object obj = null; Object obj2 = null; while (b.moveToNext()) { if (columnIndex >= 0) { String string = b.getString(columnIndex); if ("lvbuf".equalsIgnoreCase(string)) { obj2 = 1; } else if ("showhead".equalsIgnoreCase(string)) { obj = 1; } } } b.close(); if (obj2 == null) { hVar.fV(str, "Alter table " + str + " add lvbuf BLOB "); } if (obj == null) { hVar.fV(str, "Alter table " + str + " add showhead int "); } } public final boolean Z(List<String> list) { if (list.size() <= 0) { return false; } boolean z; bg bgVar = new bg("MicroMsg.AddrUploadStorage", "delete transaction"); bgVar.addSplit("begin"); long dO = this.dCZ.dO(Thread.currentThread().getId()); try { for (String str : list) { if (str != null && str.length() > 0) { int delete = this.dCZ.delete("addr_upload2", "id =?", new String[]{a.pn(str)}); x.d("MicroMsg.AddrUploadStorage", "delete addr_upload2 md5 :" + str + ", res:" + delete); if (delete > 0) { b(5, this, str); } } } z = true; } catch (Throwable e) { x.printErrStackTrace("MicroMsg.AddrUploadStorage", e, "", new Object[0]); z = false; } this.dCZ.gp(dO); bgVar.addSplit("end"); bgVar.dumpToLog(); return z; } public final boolean L(List<a> list) { if (list == null || list.size() <= 0) { return false; } boolean z; bg bgVar = new bg("MicroMsg.AddrUploadStorage", "transaction"); bgVar.addSplit("transation begin"); long dO = this.dCZ.dO(Thread.currentThread().getId()); int i = 0; while (true) { try { int i2 = i; if (i2 >= list.size()) { z = true; break; } a aVar = (a) list.get(i2); if (aVar != null) { boolean z2; Cursor b = this.dCZ.b("select addr_upload2.id,addr_upload2.md5,addr_upload2.peopleid,addr_upload2.uploadtime,addr_upload2.realname,addr_upload2.realnamepyinitial,addr_upload2.realnamequanpin,addr_upload2.username,addr_upload2.nickname,addr_upload2.nicknamepyinitial,addr_upload2.nicknamequanpin,addr_upload2.type,addr_upload2.moblie,addr_upload2.email,addr_upload2.status,addr_upload2.reserved1,addr_upload2.reserved2,addr_upload2.reserved3,addr_upload2.reserved4,addr_upload2.lvbuf,addr_upload2.showhead from addr_upload2 where addr_upload2.id = \"" + a.pn(aVar.Xh()) + "\"", null, 2); if (b == null) { z2 = false; } else { z2 = b.moveToFirst(); b.close(); } if (z2) { int pn = a.pn(aVar.Xh()); ContentValues wH = aVar.wH(); int i3 = 0; if (wH.size() > 0) { i3 = this.dCZ.update("addr_upload2", wH, "id=?", new String[]{String.valueOf(pn)}); } if (i3 == 0) { x.i("MicroMsg.AddrUploadStorage", "batchSet update result=0, num:%s email:%s", new Object[]{aVar.Xp(), aVar.Xq()}); } else if (i3 < 0) { x.i("MicroMsg.AddrUploadStorage", "batchSet update failed, num:%s email:%s", new Object[]{aVar.Xp(), aVar.Xq()}); z = true; break; } else { b(3, this, aVar.Xh()); } } else { aVar.bWA = -1; if (((int) this.dCZ.insert("addr_upload2", "id", aVar.wH())) == -1) { x.i("MicroMsg.AddrUploadStorage", "batchSet insert failed, num:%s email:%s", new Object[]{aVar.Xp(), aVar.Xq()}); z = true; break; } b(2, this, aVar.Xh()); } } i = i2 + 1; } catch (Exception e) { x.e("MicroMsg.AddrUploadStorage", e.getMessage()); z = false; } } this.dCZ.gp(dO); bgVar.addSplit("transation end"); bgVar.dumpToLog(); return z; } public final boolean aa(List<String> list) { boolean z; bg bgVar = new bg("MicroMsg.AddrUploadStorage", "set uploaded transaction"); bgVar.addSplit("transation begin"); long dO = this.dCZ.dO(Thread.currentThread().getId()); try { for (String str : list) { if (str != null && str.length() > 0) { a aVar = new a(); aVar.bWA = 8; aVar.eJx = bi.VE(); ContentValues wH = aVar.wH(); int i = 0; if (wH.size() > 0) { i = this.dCZ.update("addr_upload2", wH, "id=?", new String[]{a.pn(str)}); } x.i("MicroMsg.AddrUploadStorage", "local contact uploaded : " + str + ", update result: " + i); } } z = true; } catch (Exception e) { x.e("MicroMsg.AddrUploadStorage", e.getMessage()); z = false; } this.dCZ.gp(dO); bgVar.addSplit("transation end"); bgVar.dumpToLog(); if (z) { b(3, this, null); } return z; } public final int a(String str, a aVar) { int i = 0; ContentValues wH = aVar.wH(); if (wH.size() > 0) { i = this.dCZ.update("addr_upload2", wH, "id=?", new String[]{a.pn(str)}); } if (i > 0) { if (aVar.Xh().equals(str)) { b(3, this, str); } else { b(5, this, str); b(2, this, aVar.Xh()); } } return i; } public final a pp(String str) { if (bi.oW(str)) { return null; } a aVar = new a(); Cursor b = this.dCZ.b("select addr_upload2.id,addr_upload2.md5,addr_upload2.peopleid,addr_upload2.uploadtime,addr_upload2.realname,addr_upload2.realnamepyinitial,addr_upload2.realnamequanpin,addr_upload2.username,addr_upload2.nickname,addr_upload2.nicknamepyinitial,addr_upload2.nicknamequanpin,addr_upload2.type,addr_upload2.moblie,addr_upload2.email,addr_upload2.status,addr_upload2.reserved1,addr_upload2.reserved2,addr_upload2.reserved3,addr_upload2.reserved4,addr_upload2.lvbuf,addr_upload2.showhead from addr_upload2 where addr_upload2.username=\"" + bi.oU(str) + "\"", null, 2); x.d("MicroMsg.AddrUploadStorage", "get addrUpload :" + str); if (b.moveToFirst()) { aVar.d(b); } b.close(); return aVar; } public final a pq(String str) { a aVar = null; if (str != null && str.length() > 0) { Cursor b = this.dCZ.b("select addr_upload2.id,addr_upload2.md5,addr_upload2.peopleid,addr_upload2.uploadtime,addr_upload2.realname,addr_upload2.realnamepyinitial,addr_upload2.realnamequanpin,addr_upload2.username,addr_upload2.nickname,addr_upload2.nicknamepyinitial,addr_upload2.nicknamequanpin,addr_upload2.type,addr_upload2.moblie,addr_upload2.email,addr_upload2.status,addr_upload2.reserved1,addr_upload2.reserved2,addr_upload2.reserved3,addr_upload2.reserved4,addr_upload2.lvbuf,addr_upload2.showhead from addr_upload2 where addr_upload2.id=\"" + a.pn(str) + "\"", null, 2); if (b.moveToFirst()) { aVar = new a(); aVar.d(b); } x.d("MicroMsg.AddrUploadStorage", "get addrUpload :" + str + ", resCnt:" + (aVar != null ? 1 : 0)); b.close(); } return aVar; } public final List<String[]> Xt() { Cursor b = this.dCZ.b("select addr_upload2.moblie , addr_upload2.md5 from addr_upload2 where addr_upload2.type = 0", null, 2); List<String[]> arrayList = new ArrayList(); while (b.moveToNext()) { arrayList.add(new String[]{b.getString(0), b.getString(1)}); } b.close(); return arrayList; } public final List<a> pr(String str) { x.d("MicroMsg.AddrUploadStorage", "sql : " + str); List<a> arrayList = new ArrayList(); x.d("MicroMsg.AddrUploadStorage", "sql : " + str); Cursor b = this.dCZ.b(str, null, 2); while (b.moveToNext()) { a aVar = new a(); aVar.d(b); arrayList.add(aVar); } b.close(); return arrayList; } protected final boolean Xu() { if (this.dCZ != null && !this.dCZ.cjr()) { return true; } String str = "MicroMsg.AddrUploadStorage"; String str2 = "shouldProcessEvent db is close :%s"; Object[] objArr = new Object[1]; objArr[0] = this.dCZ == null ? "null" : Boolean.valueOf(this.dCZ.cjr()); x.w(str, str2, objArr); return false; } public final String pt(String str) { Exception e; Throwable th; if (!bi.oW(str)) { Cursor a; try { a = this.dCZ.a("addr_upload2", null, "peopleid=?", new String[]{str}, null, null, null, 2); try { if (a.moveToFirst()) { a aVar = new a(); aVar.d(a); String username = aVar.getUsername(); if (a == null) { return username; } a.close(); return username; } else if (a != null) { a.close(); } } catch (Exception e2) { e = e2; try { x.e("MicroMsg.AddrUploadStorage", "getFriendUsernameBySystemAddrBookPeopleId, error:%s", new Object[]{e.getMessage()}); if (a != null) { a.close(); } return null; } catch (Throwable th2) { th = th2; if (a != null) { a.close(); } throw th; } } } catch (Exception e3) { e = e3; a = null; } catch (Throwable th3) { th = th3; a = null; if (a != null) { a.close(); } throw th; } } return null; } }
package com.jenmaarai.sidekick.locale; import java.util.Locale; import javax.swing.event.EventListenerList; /** * Delegate for the <tt>Locale</tt> class with extended capabilities. * This class is most notably able to register <tt>LocaleListener</tt>s and * call them back whenever a change of locale happens. The only drawback is * that every locale change must pass through this delegate. * * @see LocaleListener * @see Locale */ public class LocaleDelegate { private static EventListenerList listeners = new EventListenerList(); /** * Sets the default locale for this instance of the JVM. * All <tt>LocaleListener</tt>s are notified of this change, unless the * locale is already the default one. */ public static void setDefault(Locale locale) { if (locale == null) { throw new IllegalArgumentException("locale is null"); } Locale old = Locale.getDefault(); if (!old.equals(locale)) { Locale.setDefault(locale); Localizer.purgeBundleCache(); fireLocalChanged(old, locale); } } /** * Registers the specified listener with the delegate. * The listener will be informed of every locale changed, if the change was * made through <tt>LocaleDelegate.setDefault()</tt> */ public static void addLocaleListener(LocaleListener listener) { if (listener == null) { throw new IllegalArgumentException("listener is null"); } listeners.add(LocaleListener.class, listener); } /** * Unregisters the specified listener. */ public static void removeLocaleListener(LocaleListener listener) { listeners.remove(LocaleListener.class, listener); } /** * Fires off an event specifiying that the default locale has changed. */ private static void fireLocalChanged(Locale oldLocale, Locale newLocale) { for (LocaleListener l : listeners.getListeners(LocaleListener.class)) { l.localeChanged(new LocaleEvent(oldLocale, newLocale)); } } }
package com.thoughtworks.capability.gtb; import java.time.LocalDate; import java.time.Month; import java.time.Period; /** * 计算任意日期与下一个劳动节相差多少天 * * @author itutry * @create 2020-05-15_16:33 */ public class Practice1 { public static long getDaysBetweenNextLaborDay(LocalDate date) { Month currentMonth = date.getMonth(); int currentYear = date.getYear(); int nextLabourYear = (currentMonth.getValue() >= 5) ? currentYear + 1 : currentYear; LocalDate nextlabourDate = LocalDate.of(nextLabourYear, 5, 1); return nextlabourDate.toEpochDay() - date.toEpochDay(); } }
package co.nos.noswallet.network.nosModel; import com.google.gson.annotations.SerializedName; import java.io.Serializable; import co.nos.noswallet.util.Extensions; public abstract class BaseWebsocketRequest implements Serializable { @SerializedName("action") public String action = getActionName(); @SerializedName("currency") public String currency = getCurrencyCode(); public abstract String getActionName(); public abstract String getCurrencyCode(); @Override public String toString() { return Extensions.GSON.toJson(this); } }
package com.tencent.tencentmap.mapsdk.a; import android.content.Context; import android.content.SharedPreferences; public class r { private static r a; private SharedPreferences b = null; public static r a(Context context) { if (a == null) { synchronized (r.class) { if (a == null) { a = new r(context.getApplicationContext()); } } } return a; } private r(Context context) { this.b = context.getSharedPreferences("com.tencent.tencentmap.mapsdk.maps.offlinemap", 0); } public int a() { return this.b.getInt("mapConfigVersion", -1); } public boolean a(int i) { return this.b.edit().putInt("mapConfigVersion", i).commit(); } public boolean a(long j) { return this.b.edit().putLong("mapConfigLastCheckTime", j).commit(); } public int b() { return this.b.getInt("mapPoiIcon", -1); } public boolean b(int i) { return this.b.edit().putInt("mapPoiIcon", i).commit(); } public int c() { return this.b.getInt("mapIconVersion", -1); } public boolean c(int i) { return this.b.edit().putInt("mapIconVersion", i).commit(); } public int d() { return this.b.getInt("rttConfigVersion", 0); } public boolean d(int i) { return this.b.edit().putInt("rttConfigVersion", i).commit(); } public String e() { return this.b.getString("sdkVersion", null); } public boolean a(String str) { return this.b.edit().putString("sdkVersion", str).commit(); } public boolean a(boolean z) { return this.b.edit().putBoolean("worldMapEnabled", z).commit(); } public boolean f() { return this.b.getBoolean("worldMapEnabled", false); } public boolean b(boolean z) { return this.b.edit().putBoolean("specialDistrictEnable", z).commit(); } public boolean g() { return this.b.getBoolean("specialDistrictEnable", false); } public boolean e(int i) { return this.b.edit().putInt("worldMapStyle", i).commit(); } public int h() { return this.b.getInt("worldMapStyle", -1); } public boolean f(int i) { return this.b.edit().putInt("worldMapVersion", i).commit(); } public int i() { return this.b.getInt("worldMapVersion", -1); } public boolean g(int i) { return this.b.edit().putInt("worldMapScene", i).commit(); } public int j() { return this.b.getInt("worldMapScene", -1); } public boolean b(String str) { return this.b.edit().putString("mapSourceType", str).commit(); } public String k() { return this.b.getString("mapSourceType", null); } public boolean c(String str) { return this.b.edit().putString("taiwanMapName", str).commit(); } public String l() { return this.b.getString("taiwanMapName", null); } public boolean h(int i) { return this.b.edit().putInt("worldMapFrontierVersion", i).commit(); } public int m() { return this.b.getInt("worldMapFrontierVersion", -1); } public boolean d(String str) { return this.b.edit().putString("worldTileURLExpression", str).commit(); } public String n() { return this.b.getString("worldTileURLExpression", null); } public boolean e(String str) { return this.b.edit().putString("taiwanTileURLExpression", str).commit(); } public String o() { return this.b.getString("taiwanTileURLExpression", null); } public boolean i(int i) { return this.b.edit().putInt("mapConfigIndoorVersion", i).commit(); } public int p() { return this.b.getInt("mapConfigIndoorVersion", 0); } public boolean j(int i) { return this.b.edit().putInt("mapPoiIconIndoorVersion", i).commit(); } public int q() { return this.b.getInt("mapPoiIconIndoorVersion", 0); } public boolean f(String str) { return this.b.edit().putString("mapConfigZipMd5", str).commit(); } public String r() { return this.b.getString("mapConfigZipMd5", null); } public boolean g(String str) { return this.b.edit().putString("mapPoiIconZipMd5", str).commit(); } public String s() { return this.b.getString("mapPoiIconZipMd5", null); } public boolean h(String str) { return this.b.edit().putString("mapIconZipMd5", str).commit(); } public String t() { return this.b.getString("mapIconZipMd5", null); } public boolean k(int i) { return this.b.edit().putInt("closeRoadSytleNomalModeVersion", i).commit(); } public int u() { return this.b.getInt("closeRoadSytleNomalModeVersion", 0); } public boolean l(int i) { return this.b.edit().putInt("closeRoadStyleTrafficModeVersion", i).commit(); } public int v() { return this.b.getInt("closeRoadStyleTrafficModeVersion", 0); } public int w() { return this.b.getInt("handDrawMapVer", 0); } public boolean m(int i) { return this.b.edit().putInt("handDrawMapVer", i).commit(); } }
package com.example.abidemi.seniorproject; import java.util.LinkedList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class DatabaseHandler extends SQLiteOpenHelper { // Database Version private static final int DATABASE_VERSION = 1; // Database Name private static final String DATABASE_NAME = "STOCKDB"; public DatabaseHandler(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // SQL statement to create book table String CREATE_STOCK_TABLE = "CREATE TABLE table_A ( " + "id INTEGER PRIMARY KEY AUTOINCREMENT,"+ "SYMBOL TEXT PRIMARY KEY, " + "LAST_TRADE TEXT, "+ "LAST_TRADE_TIME TEXT, " + "CHANGE TRADE_TIME TEXT, " + "OPEN TEXT, " + "DAY_HIGH TEXT, " + "DAY_LOW TEXT, " + "VOLUME TEXT, " + "PREVIOUS_CLOSE TEXT" + ")"; // create books table db.execSQL(CREATE_STOCK_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Drop older books table if existed db.execSQL("DROP TABLE IF EXISTS table_A"); // create fresh books table this.onCreate(db); } //--------------------------------------------------------------------- /** * CRUD operations (create "add", read "get", update, delete) book + get all books + delete all books */ // Books table name private static final String TABLE_STOCKS = "table_A"; // Stocks Table Columns names private static final String KEY_ID = "id"; private static final String SYMBOL = "symbol"; private static final String LAST_TRADE = "last_trade"; private static final String DATE = "date"; private static final String LAST_TRADE_TIME = "last_trade_time"; private static final String CHANGE = "change"; private static final String OPEN = "open"; private static final String DAY_HIGH = "day_high"; private static final String DAY_LOW = "day_low"; private static final String VOLUME = "volume"; private static final String PREVIOUS_CLOSE = "previous_close"; private static final String[] COLUMNS = {SYMBOL,LAST_TRADE, DATE, LAST_TRADE_TIME, CHANGE, OPEN, DAY_HIGH, DAY_LOW, VOLUME, PREVIOUS_CLOSE}; public void addStock(Stock stock) { Log.d("addStock", stock.toString()); // 1. get reference to writable DB SQLiteDatabase db = this.getWritableDatabase(); ContentValues values2 = new ContentValues(); values2.put(SYMBOL, stock.getSymbol()); values2.put(LAST_TRADE, stock.getLast_trade()); values2.put(LAST_TRADE_TIME, stock.getLast_trade_time()); values2.put(CHANGE, stock.getChange()); values2.put(OPEN, stock.getOpen()); values2.put(DAY_HIGH, stock.getDay_high()); values2.put(DAY_LOW, stock.getDay_low()); values2.put(VOLUME, stock.getVolume()); values2.put(PREVIOUS_CLOSE, stock.getPrevious_close()); db.insert(TABLE_STOCKS, // table null, //nullColumnHack values2); // key/value -> keys = column names/ values = column values // Log.d("This content", ""); db.close(); } /* public Book getBook(int id) { // 1. get reference to readable DB SQLiteDatabase db = this.getReadableDatabase(); // 2. build query Cursor cursor = db.query(TABLE_BOOKS, // a. table COLUMNS, // b. column names " id = ?", // c. selections new String[] { String.valueOf(id) }, // d. selections args null, // e. group by null, // f. having null, // g. order by null); // h. limit // 3. if we got results get the first one if (cursor != null) cursor.moveToFirst(); // 4. build book object Book book = new Book(); book.setId(Integer.parseInt(cursor.getString(0))); book.setTitle(cursor.getString(1)); book.setAuthor(cursor.getString(2)); Log.d("getBook("+id+")", book.toString()); // 5. return book return book; } // Get All Books public List<Book> getAllBooks() { List<Book> books = new LinkedList<Book>(); // 1. build the query String query = "SELECT * FROM " + TABLE_BOOKS; // 2. get reference to writable DB SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(query, null); // 3. go over each row, build book and add it to list Book book = null; if (cursor.moveToFirst()) { do { book = new Book(); book.setId(Integer.parseInt(cursor.getString(0))); book.setTitle(cursor.getString(1)); book.setAuthor(cursor.getString(2)); // Add book to books books.add(book); } while (cursor.moveToNext()); } Log.d("getAllBooks()", books.toString()); // return books return books; } // Updating single book public int updateBook(Book book) { // 1. get reference to writable DB SQLiteDatabase db = this.getWritableDatabase(); // 2. create ContentValues to add key "column"/value ContentValues values = new ContentValues(); values.put("title", book.getTitle()); // get title values.put("author", book.getAuthor()); // get author // 3. updating row int i = db.update(TABLE_BOOKS, //table values, // column/value KEY_ID+" = ?", // selections new String[] { String.valueOf(book.getId()) }); //selection args // 4. close db.close(); return i; } // Deleting single book public void deleteBook(Book book) { // 1. get reference to writable DB SQLiteDatabase db = this.getWritableDatabase(); // 2. delete db.delete(TABLE_BOOKS, KEY_ID+" = ?", new String[] { String.valueOf(book.getId()) }); // 3. close db.close(); Log.d("deleteBook", book.toString()); }*/ }
package com.example.android.dreamdestinations.Model; import android.os.Parcel; import android.os.Parcelable; import com.google.gson.annotations.SerializedName; /** * Created by joycelin12 on 9/21/18. */ public class OperatingCarriers implements Parcelable { @SerializedName("0") private String OperatingCarriers; public OperatingCarriers(String operatingCarriers) { OperatingCarriers = operatingCarriers; } public String getOperatingCarriers() { return OperatingCarriers; } public void setOperatingCarriers(String operatingCarriers) { OperatingCarriers = operatingCarriers; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.OperatingCarriers); } protected OperatingCarriers(Parcel in) { this.OperatingCarriers = in.readString(); } public static final Creator<OperatingCarriers> CREATOR = new Creator<OperatingCarriers>() { @Override public OperatingCarriers createFromParcel(Parcel source) { return new OperatingCarriers(source); } @Override public OperatingCarriers[] newArray(int size) { return new OperatingCarriers[size]; } }; }
/*자동차를 정의해본다*/ class Car{ String name="벤츠"; int price=9000; String color="sliver"; public void setPrice(int price){ this.price=price; //this.price는 멤버 변수 price는 지역변수 } public static void main(String[] args){ Car c1=new Car(); Car c2=new Car(); Car c3=c2; //c3은 c2를 가리키는 용도기때문에 메모리엔 c1,c2 2대만 올라감 c1.setPrice(8000); //첫번째 자동차의 가격을 8000으로 내림 System.out.println(c2.price);//두번째 자동차가 영향을 받았는지 여부를 체크 //결론 : 메모리에 올라간 인스턴스들은 서로 다른 별개의 객체들이다..!!!! c3.setPrice(7000);//c3=c2이기때문에 두번째 자동차 가격을 7000으로 변경한거임 System.out.println(c2.price); } }
/* * 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 edu.eci.arsw.webstore.persistence; import edu.eci.arsw.webstore.model.User; import java.util.List; /** * * @author jmvillatei */ public interface UserPersistence { /** * Este metodo permite obtener todos los usuarios * * @return Una lista con todos los usuarios */ public List<User> getAllUsers(); /** * Este metodo permite la creacion de un nuevo usuario * * @param us Es el nuevo usuario a crear. */ public void createNewUser(User us); /** * Este metodo permite obtener un usuario por su nickname * * @param userNickname nickname del usuario a obtener * @return El usuario que pertenece a ese nickname */ public User getUserByUserNickname(String userNickname); /** * Metodo que permite consultar un usuario por su correo. * @param email Es el correo con el cual se quiere encontrar un usuario. * @return Retorna el usuario correspondiente */ public User getUserByEmail(String email); /** * Este metodo permite obtener un usuario por su id * * @param id Es el id del usuario que se quiere obtener * @return Retorna el usuario correspondiente al id. */ public User getUserById(String id); /** * Este metodo permite eliminar un usuario por su nickname * * @param userNickname Es el nickname del usuario que se quiere eliminar. */ public void deleteUserByUserNickname(String userNickname); /** * Metodo que permite actualizar un usuario. * @param user Es el usuario a actualizar. */ public void updateUser(User user); }
package dev.schoenberg.kicker_stats.core.domain; public class Credentials { public final String mail; public final String password; public Credentials(String mail, String password) { this.mail = mail; this.password = password; } }
package email; abstract class EmailDecorator implements IEmail { private IEmail email; EmailDecorator(IEmail email) { setEmail(email); } private IEmail getEmail() { return this.email; } private void setEmail(IEmail email) { this.email = email; } abstract String customiseEmail(String contents); @Override public String getContents() { return getEmail().getContents(); } @Override public String getCustomisedDetails(String customisedContents) { return getEmail().getCustomisedDetails(customiseEmail(getContents())); } }
package com.ormuco.technicaltest.questionbrest.dto; import javax.validation.constraints.NotNull; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * Request object fields. * * <p> * Request object contain all fields to evaluate if two version string as input and returns * whether one is greater than, equal, or less than the other. * </p> * * <ul> * <li><b>strNum1</b>: First {@code String} to evaluate. This field is required.</li> * <li><b>strNum2</b>: Second {@code String} to evaluate. This field is required.</li> * <li><b>locale</b>: Locale object represents a specific geographic, cultural, or political region. * This field is not required.</li> * </ul> * * @author Johann David Cabrera Mora * @since 1.0 */ @ToString public class CompareTwoStringRequest { @Getter @Setter @NotNull( message = "The field strNum1 can't be null" ) private String strNum1; @Getter @Setter @NotNull( message = "The field strNum2 can't be null" ) private String strNum2; @Getter @Setter private LocaleRequest locale; }
package javaStudy.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; /* JDBC 실행절차>>> 1. JDBC driver 등록 2. Connection(network) 객체 얻어내기:Driver Manager의 getConnection()를 이용 3. Statement객체 얻어내기: Connection 객체의 createStatement()를 이용 4. SQL을 DB에 전송: Statement객체의 executeQuery()나 executeUpdate()를 이용 5. SQL문장 실행결과 처리: ResultSet 객체의 getXXX()를 이용 6. 자원 반납: Statement객체와 Connection객체의 close()호출 */ public class Delete { public static void main(String[] args) throws Exception { String driver = "com.mysql.cj.jdbc.Driver"; //jdbc url String url = "jdbc:mysql://localhost:3306/scott?characterEncoding=UTF-8&serverTimezone=UTC"; //DB 접속할 계정 String user = "scott"; String password = "scott"; String query = "delete from customer where num=?"; //1.Driver 등록 Class.forName(driver); // 객체를 생성하는 문장. 객체 생성이 유연해 Class.forName("com.test.Car"); // com.test.Car c = new com.test.Car(); //2. Connection 생성 - network 연결 Connection con = DriverManager.getConnection(url, user, password); //3.Statement 생성 PreparedStatement pstat = con.prepareStatement(query); pstat.setInt(1, 729); //4.Query 실행 pstat.executeUpdate(); //5. 마무리 pstat.close(); con.close(); } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.commercefacades.coupon.impl; import de.hybris.platform.commercefacades.coupon.CouponDataFacade; import de.hybris.platform.commercefacades.coupon.data.CouponData; import java.util.Optional; /** * Default Implementation of {@link CouponDataFacade} returning an Optional.empty() * */ public class DefaultCouponDataFacade implements CouponDataFacade { @Override public Optional<CouponData> getCouponDetails(final String couponCode) { return Optional.empty(); } }
package com.javaconceptprograms; public class CountNoOfObjectsCreated { public static void main(String[] args) { // Whenever we are creating Object The Class will start as the new one // Even the class is having the another Object also // For Example Here we have created 6 Objects // When we try to call the 'count' variable it will be called once , So the value of 'count' always be 1 // To overcome this we need to mention the count variable as static A a = new A(); A a1 = new A(); A a2 = new A(); A a3 = new A(); A a4 = new A(); A a5 = new A(); int count = a.count; System.out.println(count); } } class A { static int count = 0; public A() { count++; } }
package com.esprit.lyricsplus.entities; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.ParseException; import java.text.SimpleDateFormat; public class Comments { private int id ; private java.sql.Date dateComment ; private String text ; private Share share ; private User user ; public Comments(int id, java.sql.Date dateComment, String text, Share share, User user) { this.id = id; this.dateComment = dateComment; this.text = text; this.share = share; this.user = user; } public Comments() { } public Comments(JSONObject j) { JSONArray jsonArray1; JSONArray jsonArray; id = j.optInt("id"); try { jsonArray = new JSONArray(j.optString("id_user")); JSONObject jsonObject = jsonArray.getJSONObject(0); user = new User( jsonObject); jsonArray1 = new JSONArray(j.optString("id_share")); JSONObject jsonObject1 = jsonArray1.getJSONObject(0); share = new Share( jsonObject1); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); java.util.Date parsed = format.parse(j.optString("date_comment")); java.sql.Date sql = new java.sql.Date(parsed.getTime()); dateComment = sql ; text=j.optString("text"); } catch (JSONException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } } public int getId() { return id; } public void setId(int id) { this.id = id; } public java.sql.Date getDateComment() { return dateComment; } public void setDateComment(java.sql.Date dateComment) { this.dateComment = dateComment; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Share getShare() { return share; } public void setShare(Share share) { this.share = share; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } @Override public String toString() { return "Comments{" + "id=" + id + ", dateComment=" + dateComment + ", text='" + text + '\'' + ", share=" + share + ", user=" + user + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Comments)) return false; Comments comments = (Comments) o; return id == comments.id; } @Override public int hashCode() { return id; } }
package com.rawls.ai; public class GMAI implements iManagementAI{ }
package co.aurasphere.courseware.java.jaxb.model; import java.util.Set; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "persona") @XmlAccessorType(XmlAccessType.FIELD) public class Person { @XmlAttribute private int id; @XmlElement private String name; @XmlElement private String surname; @XmlElement private String role; @XmlElement private Set<Movie> movies; public Person() { } public Person(String name, String surname) { super(); this.name = name; this.surname = surname; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCognome() { return surname; } public void setSurname(String surname) { this.surname = surname; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public Set<Movie> getMovies() { return movies; } public void setMovies(Set<Movie> movies) { this.movies = movies; } @Override public String toString() { return "Person [id=" + id + ", name=" + name + ", surname=" + surname + ", role=" + role + ", movies=" + movies + "]"; } }
package com.mo.mohttp.executor; import com.mo.mohttp.*; import com.mo.mohttp.constant.Headers; import com.mo.mohttp.entity.Entity; import com.mo.mohttp.entity.FileMultipartEntity; import com.mo.mohttp.entity.FormUrlencodedEntity; import com.mo.mohttp.entity.StringEntity; import com.mo.mohttp.pair.NameFilePair; import com.mo.mohttp.pair.NameValuePair; import com.mo.mohttp.misc.TextUtils; import com.mo.mohttp.response.UrlConnectionResponse; import java.io.DataOutputStream; import java.io.IOException; import java.net.*; import java.nio.charset.Charset; import java.util.List; import java.util.Map; public class UrlConnectionExecutor implements Executor { private UrlConnectionExecutor(){} public static UrlConnectionExecutor getInstance(){ synchronized (UrlConnectionExecutor.class){ if(instance == null){ instance = new UrlConnectionExecutor(); } return instance; } } private static UrlConnectionExecutor instance ; @Override @SuppressWarnings("deprecated") public Response execute(Request request) throws IOException, URISyntaxException { boolean writeData = request.getMethod().writeData(); Client client = request.getClient(); Charset charset = request.getCharset(); if(request.getCharset() == null){ charset = Charset.defaultCharset(); } List<NameValuePair> paramList = request.getParamList(); List<NameFilePair> fileList = request.getFileList(); StringBuilder stringEntity = request.getStringEntity(); if(!writeData&&!fileList.isEmpty()){ throw new IllegalStateException("GET method does not support file upload request!"); } if(stringEntity!=null&&(!fileList.isEmpty()||!paramList.isEmpty())){ throw new IllegalStateException("cannot get string entity while file or param entity is not empty!"); } URI u = null; if(writeData){ u = request.getUri(); }else{ u = TextUtils.buildURI(request.getUri(),charset,request.getParamList()); } URLConnection connection = null; try { URL url = u.toURL(); Proxy proxy = null; if(client!=null&&client.getProxy()!=null){ proxy = client.getProxy(); } if(request.getProxy()!=null){ proxy = request.getProxy(); } connection = proxy == null?url.openConnection():url.openConnection(proxy); // open url connection connection.setDoInput(true); if(writeData){ connection.setDoOutput(true); connection.setUseCaches(false); } if(connection instanceof HttpURLConnection){ // this will always happen. HttpURLConnection httpURLConnection = (HttpURLConnection)connection; httpURLConnection.setRequestMethod(request.getMethod().name()); if(request.getAllowRedirect()!=null){ httpURLConnection.setInstanceFollowRedirects(request.getAllowRedirect()); }else { httpURLConnection.setInstanceFollowRedirects(false); } } if(request.getTimeout()!=null){ connection.setConnectTimeout(request.getTimeout()); connection.setReadTimeout(request.getTimeout()); } if(request.getAgent()!=null){ connection.setRequestProperty(Headers.agent,request.getAgent()); } if(request.getClient()!=null){ if(request.getAgent()==null&&client.getUserAgent()!=null){ connection.setRequestProperty(Headers.agent,client.getUserAgent()); } for(NameValuePair pair:client.getHeaders()){ connection.setRequestProperty(pair.getName(),pair.getValue()); } //set cookies if(client.getCookieManager()!=null){ CookieManager cookieManager = client.getCookieManager(); Map<String, List<String>> map = cookieManager.get(u,connection.getRequestProperties()); for(Map.Entry<String,List<String>> entry:map.entrySet()){ String key = entry.getKey(); for(String value:entry.getValue()){ connection.addRequestProperty(key,value); } } } } boolean flag = true; // whether contentType has been written in header fields; for(NameValuePair pair:request.getHeaderList()){ connection.setRequestProperty(pair.getName(),pair.getValue()); if(Headers.contentType.equalsIgnoreCase(pair.getName())){ flag = false; } } if(writeData){ connection.setDoOutput(true); Entity entity = null; // data entity if(fileList.isEmpty()){ entity = new FormUrlencodedEntity(paramList,charset); }else{ entity = new FileMultipartEntity(paramList,fileList,charset); } if(stringEntity!=null){ entity = new StringEntity(stringEntity.toString()); } if(flag) connection.setRequestProperty(Headers.contentType,entity.getContentType()); // if content type has not been written in header fields,write entity default content type ( always ContentType.FORM_DEFAULT). DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); entity.writeTo(outputStream); } if (request.getClient()!=null){ Map<String, List<String>> headerFields = connection.getHeaderFields(); request.getClient().getCookieManager().put(u,headerFields); //automatically put cookies in response headers to cookie store. } return new UrlConnectionResponse(connection,request); }finally { if(connection!=null&&connection instanceof HttpURLConnection){ ((HttpURLConnection) connection).disconnect(); } } } }
package clib.javafx.i18n; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.charset.StandardCharsets; import java.util.MissingResourceException; import java.util.ResourceBundle; import javafx.beans.property.SimpleStringProperty; public class I18NString extends SimpleStringProperty { private String key; private Object[] arguments; private ResourceBundle bundle; private static Method translateMethod; static { int jvnumber = Character.getNumericValue(System.getProperty("java.version").charAt(0)); try { translateMethod = jvnumber < 9 ? I18NString.class.getDeclaredMethod("translate", ResourceBundle.class, String.class) : I18NString.class.getDeclaredMethod("translate9", ResourceBundle.class, String.class); } catch (NoSuchMethodException e) { e.printStackTrace(); } } private static ResourceBundle getBundle(String bundleKey) { return I18N.getBundles().get(I18N.getLocale().toLanguageTag() + ':' + bundleKey); } private static String translate(ResourceBundle bundle, String key) { try { byte[] byteArray = bundle.getString(key).getBytes(StandardCharsets.ISO_8859_1); return new String(byteArray, StandardCharsets.UTF_8); } catch (MissingResourceException e) { return String.format("null::%s", key); } } private static String translate9(ResourceBundle bundle, String key) { try { return bundle.getString(key); } catch (MissingResourceException e) { return String.format("null::%s", key); } } I18NString(String bundleKey) { I18N.LOCALEProperty().addListener((observable, oldValue, newValue) -> { bundle = getBundle(bundleKey); if (arguments != null) set(key, arguments); else set(key); }); bundle = getBundle(bundleKey); } @Override public void set(String newValue) { key = newValue; arguments = null; try { super.set((String) translateMethod.invoke(I18NString.class, bundle, newValue)); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } void set(String newValue, Object... args) { key = newValue; arguments = args; try { super.set(String.format((String) translateMethod.invoke(I18NString.class, bundle, newValue), args)); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } void update(Object... args) { set(key, args); } }
package com.faac.occupancy.service; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.faac.occupancy.dao.CompanyRepository; import com.faac.occupancy.dao.OccupancyRepository; import com.faac.occupancy.domain.Company; import com.faac.occupancy.model.Occupancy; import com.faac.occupancy.model.Response; import com.faac.occupancy.model.ResponseType; @RestController public class OccupancyService { private Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private SimpMessagingTemplate template; @Autowired private OccupancyRepository occupancyRepository; @Autowired private CompanyRepository companyRepository; @RequestMapping(value = "/occupancy", method = RequestMethod.PUT) public Response pushOccupancy(@RequestBody Occupancy occupancy) { logger.info("pushing occupancy..."); Company domainCompany = companyRepository.findByName(occupancy.getCompanyName()); if (domainCompany == null) { domainCompany = companyRepository.save(new Company(occupancy.getCompanyName())); } com.faac.occupancy.domain.Occupancy domainOccupancy = occupancyRepository.findByParkingId(occupancy.getParkingId()); if (domainOccupancy == null) { domainOccupancy = new com.faac.occupancy.domain.Occupancy(occupancy.getParkingId(), occupancy.getTotalPlaces(), occupancy.getFreeSpaces(), domainCompany.getId()); } else { domainOccupancy.setFreeSpaces(occupancy.getFreeSpaces()); } occupancyRepository.save(domainOccupancy); template.convertAndSend("/topic/occupancy", occupancy); return new Response(); } @RequestMapping(value = "/companies", method = RequestMethod.GET) public Response getCompanies() { List<Company> companies = (List<Company>)companyRepository.findAll(); return new Response(companies, ResponseType.ok); } @RequestMapping(value = "/occupancies", method = RequestMethod.GET) public Response getOccupancies(@RequestParam("companyId") long companyId) { List<com.faac.occupancy.domain.Occupancy> occupancies = (List<com.faac.occupancy.domain.Occupancy>)occupancyRepository.findByCompanyId(companyId); return new Response(occupancies, ResponseType.ok); } }
package itri.io.emulator.experiment; import itri.io.emulator.parameter.FileSize; public class BlockTemporalLocalityManager { private BlockWithTemporalLocality[] blocks; public BlockTemporalLocalityManager(FileSize size) { int len = (int) (size.getSize() / Block.UNIT_4K); len = (int) (size.getSize() % Block.UNIT_4K == 0 ? len : len + 1); blocks = new BlockWithTemporalLocality[len]; for (int i = 0; i < blocks.length; i++) { blocks[i] = new BlockWithTemporalLocality(i); } } public int getBlocksSize() { return blocks.length; } public BlockWithTemporalLocality[] getBlocks() { return blocks; } public void updateBlocksTemporalLocality(long offset, int length,long accessTime) { int startBlock = (int) (offset / Block.UNIT_4K); int endBlock = (int) ((offset + length) / Block.UNIT_4K); int remainder = (int) ((offset + length) % Block.UNIT_4K); if (remainder == 0) endBlock--; for (int i = startBlock; i <= endBlock; i++) { blocks[i].updateAvgIntervalTime(accessTime); } } }
package jp.co.tau.web7.admin.supplier.dao.mappers; import static org.assertj.core.api.Assertions.fail; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.List; 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 jp.co.tau.web7.admin.supplier.dto.LoginDTO; import jp.co.tau.web7.admin.supplier.dto.UserInfoDTO; import jp.co.tau.web7.admin.supplier.entity.TVsmUserEntity; import jp.co.tau.web7.admin.supplier.mappers.TVsmUserMapper; @RunWith(SpringRunner.class) @SpringBootTest public class TVsmUserMapperTest extends MapperBaseTest { @Autowired TVsmUserMapper tVsmUserMapper; /** * {@link TVsmUserMapper#findVsmUserInfo(LoginDTO)}のテスト * <p> * Parameter:[2, 1] * Pattern:0 record(parameter1 not match in where condition) * </p> */ @Test public void testFindVsmUserInfo_001() { try { // 対象メソッドを呼び出し、テストを行う Object actualResult = tVsmUserMapper.findVsmUserInfo((LoginDTO) parameter); assertTrue(compareObj(actualResult, expectedResult)); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage(), e); } } /** * {@link TVsmUserMapper#findVsmUserInfo(LoginDTO)}のテスト * <p> * Parameter:[1, 2] * Pattern:0 record(parameter2 not match in where condition) * </p> */ @Test public void testFindVsmUserInfo_002() { try { // 対象メソッドを呼び出し、テストを行う Object actualResult = tVsmUserMapper.findVsmUserInfo((LoginDTO) parameter); assertTrue(compareObj(actualResult, expectedResult)); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage(), e); } } /** * {@link TVsmUserMapper#findVsmUserInfo(LoginDTO)}のテスト * <p> * Parameter:[1, 1] * Pattern:1 record(all parameter match in where condition) * </p> */ @Test public void testFindVsmUserInfo_003() { try { // 対象メソッドを呼び出し、テストを行う Object actualResult = tVsmUserMapper.findVsmUserInfo((LoginDTO) parameter); assertTrue(compareObj(actualResult, expectedResult)); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage(), e); } } /** * {@link TVsmUserMapper#updateVsmUser(TVsmUserEntity)}のテスト * <p> * Pattern:0 record(parameter1:@userId not exist) * </p> */ @Test public void testUpdateVsmUser_001() { try { // 対象メソッドを呼び出し、テストを行う int insertCount = tVsmUserMapper.updateVsmUser((TVsmUserEntity) parameter); assertEquals(0, insertCount); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage(), e); } } /** * {@link TVsmUserMapper#updateVsmUser(TVsmUserEntity)}のテスト * <p> * Pattern:1 record(all parameter exist) * </p> */ @Test public void testUpdateVsmUser_002() { try { // 対象メソッドを呼び出し、テストを行う int insertCount = tVsmUserMapper.updateVsmUser((TVsmUserEntity) parameter); assertEquals(1, insertCount); Object tableresult = getActualTableResult("M_VSM_USER"); assertTrue(compareObj(tableresult, expectedResult)); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage(), e); } } /** * {@link TVsmUserMapper#updateVsmUser(TVsmUserEntity)}のテスト * <p> * パターン:異常系 * </p> */ @Test(expected = org.springframework.dao.DataIntegrityViolationException.class) public void testUpdateVsmUser_003() { // 対象メソッドを呼び出し、テストを行う tVsmUserMapper.updateVsmUser((TVsmUserEntity) parameter); } /** * {@link TVsmUserMapper#findUserRole(String, String)}のテスト * <p> * Parameter:[0,1] * Pattern:0 record(parameter1 not match in where condition) * </p> */ @Test public void testFindUserRole_001() { try { // 対象メソッドを呼び出し、テストを行う Object actualResult = tVsmUserMapper.findUserRole((LoginDTO) parameter); assertTrue(compareObj(actualResult, expectedResult)); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage(), e); } } /** * {@link TVsmUserMapper#findUserRole(String, String)}のテスト * <p> * Parameter:[1,0] * Pattern:0 record(parameter2 not match in where condition) * </p> */ @Test public void testFindUserRole_002() { try { // 対象メソッドを呼び出し、テストを行う Object actualResult = tVsmUserMapper.findUserRole((LoginDTO) parameter); assertTrue(compareObj(actualResult, expectedResult)); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage(), e); } } /** * {@link TVsmUserMapper#findUserRole(String, String)}のテスト * <p> * Parameter:[1, 1] * Pattern:1 record(all parameter match in where condition) * </p> */ @Test public void testFindUserRole_003() { try { // 対象メソッドを呼び出し、テストを行う Object actualResult = tVsmUserMapper.findUserRole((LoginDTO) parameter); assertTrue(compareObj(actualResult, expectedResult)); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage(), e); } } /** * {@link TVsmUserMapper#getUserID(String, String)}のテスト * <p> * Parameter:[0,a] * Pattern:0 record(parameter1 not match in where condition) * </p> */ @Test public void testGetUserID_001() { try { // 対象メソッドを呼び出し、テストを行う @SuppressWarnings("unchecked") List<Object> params = (List<Object>) parameter; int tauAucBd = tVsmUserMapper.getUserID((String) params.get(0), (String) params.get(1)); assertTrue(compareObj(tauAucBd, 0)); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage(), e); } } /** * {@link TVsmUserMapper#getUserID(String, String)}のテスト * <p> * Parameter:[1,b] * Pattern:0 record(parameter1 not match in where condition) * </p> */ @Test public void testGetUserID_002() { try { // 対象メソッドを呼び出し、テストを行う @SuppressWarnings("unchecked") List<Object> params = (List<Object>) parameter; int tauAucBd = tVsmUserMapper.getUserID((String) params.get(0), (String) params.get(1)); assertTrue(compareObj(tauAucBd, 0)); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage(), e); } } /** * {@link TVsmUserMapper#getUserID(String, String)}のテスト * <p> * Parameter:[1,a] * Pattern:1 record(all parameter match in where condition) * </p> */ @Test public void testGetUserID_003() { try { // 対象メソッドを呼び出し、テストを行う @SuppressWarnings("unchecked") List<Object> params = (List<Object>) parameter; int tauAucBd = tVsmUserMapper.getUserID((String) params.get(0), (String) params.get(1)); assertTrue(compareObj(tauAucBd, 1)); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage(), e); } } /** * {@link TVsmUserMapper#insertUser(UserInfoDTO)}のテスト * <p> * パターン:正常系 * </p> */ @Test public void testInsertUser_001() { try { // 対象メソッドを呼び出し、テストを行う int insertCount = tVsmUserMapper.insertUser((UserInfoDTO) parameter); assertEquals(1, insertCount); Object tableresult = getActualTableResult("M_VSM_USER"); assertTrue(compareObj(tableresult, expectedResult)); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage(), e); } } /** * {@link TVsmUserMapper#insertUser(UserInfoDTO)}のテスト * <p> * パターン:異常系 * </p> */ @Test(expected = org.springframework.dao.DataIntegrityViolationException.class) public void testInsertUser_002() { // 対象メソッドを呼び出し、テストを行う tVsmUserMapper.insertUser((UserInfoDTO) parameter); } /** * {@link TVsmUserMapper#findUserInfo(String, String)}のテスト * <p> * Parameter:[1,a] * Pattern:0 record(join 1 not condition) * </p> */ @Test public void testFindUserInfo_001() { try { // 対象メソッドを呼び出し、テストを行う @SuppressWarnings("unchecked") List<Object> params = (List<Object>) parameter; Object tauAucBd = tVsmUserMapper.findUserInfo((String) params.get(0), (String) params.get(1)); assertTrue(compareObj(tauAucBd, 0)); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage(), e); } } /** * {@link TVsmUserMapper#findUserInfo(String, String)}のテスト * <p> * Parameter:[1,a] * Pattern:0 record(join 2 not condition) * </p> */ @Test public void testFindUserInfo_002() { try { // 対象メソッドを呼び出し、テストを行う @SuppressWarnings("unchecked") List<Object> params = (List<Object>) parameter; Object tauAucBd = tVsmUserMapper.findUserInfo((String) params.get(0), (String) params.get(1)); assertTrue(compareObj(tauAucBd, 0)); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage(), e); } } /** * {@link TVsmUserMapper#findUserInfo(String, String)}のテスト * <p> * Parameter:[5,a] * Pattern:0 record(parameter1 not match in where condition) * </p> */ @Test public void testFindUserInfo_003() { try { // 対象メソッドを呼び出し、テストを行う @SuppressWarnings("unchecked") List<Object> params = (List<Object>) parameter; Object tauAucBd = tVsmUserMapper.findUserInfo((String) params.get(0), (String) params.get(1)); assertTrue(compareObj(tauAucBd, 0)); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage(), e); } } /** * {@link TVsmUserMapper#findUserInfo(String, String)}のテスト * <p> * Parameter:[1,b] * Pattern:0 record(parameter2 not match in where condition) * </p> */ @Test public void testFindUserInfo_004() { try { // 対象メソッドを呼び出し、テストを行う @SuppressWarnings("unchecked") List<Object> params = (List<Object>) parameter; Object tauAucBd = tVsmUserMapper.findUserInfo((String) params.get(0), (String) params.get(1)); assertTrue(compareObj(tauAucBd, 0)); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage(), e); } } /** * {@link TVsmUserMapper#findUserInfo(String, String)}のテスト * <p> * Parameter:[1,a] * Pattern:1 record(all parameter match in where condition) * </p> */ @Test public void testFindUserInfo_005() { try { // 対象メソッドを呼び出し、テストを行う @SuppressWarnings("unchecked") List<Object> params = (List<Object>) parameter; Object tauAucBd = tVsmUserMapper.findUserInfo((String) params.get(0), (String) params.get(1)); assertTrue(compareObj(tauAucBd, 0)); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage(), e); } } }
package LeetCode.BitManipulation; public class MissingNumber { public int missingNumber(int[] a) { int xor = a.length; for (int i = 0; i < a.length; i++) { xor ^= a[i] ^ i; } return xor; } public int gauss(int[] a) { int expected = (a.length * (a.length + 1)) / 2; int sum = 0; for (int i = 0; i < a.length; i++) { sum += a[i]; } return expected - sum; } public static void main(String[] args) { MissingNumber m = new MissingNumber(); System.out.println(m.missingNumber(new int[] {0,1,2,3,4,5,6,7,9})); System.out.println(m.gauss(new int[] {0,1,2,3,4,5,6,7,9})); } }
package com.revature.abstraction; public interface Anfibious { void swim(); }
package com.github.vinja.debug; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.github.vinja.compiler.CompilerContext; import com.github.vinja.omni.ClassInfo; import com.github.vinja.omni.ClassMetaInfoManager; import com.sun.jdi.AbsentInformationException; import com.sun.jdi.Field; import com.sun.jdi.Location; import com.sun.jdi.ReferenceType; import com.sun.jdi.ThreadReference; import com.sun.jdi.VirtualMachine; import com.sun.jdi.request.BreakpointRequest; import com.sun.jdi.request.ClassPrepareRequest; import com.sun.jdi.request.EventRequest; import com.sun.jdi.request.EventRequestManager; import com.sun.jdi.request.WatchpointRequest; public class BreakpointManager { private Debugger debugger; private List<Breakpoint> allBreakpoints = new ArrayList<Breakpoint>(); public BreakpointManager(Debugger debugger) { this.debugger = debugger; } public List<Breakpoint> getAllBreakpoints() { return allBreakpoints; } public String allBreakpointsInfo() { StringBuilder sb = new StringBuilder(); for (Breakpoint bp : allBreakpoints) { sb.append(bp.getMainClass()).append(" ").append(bp.getLineNum()); sb.append("\n"); } return sb.toString(); } public void verifyBreakpoint(String mainClass) { CompilerContext ctx = debugger.getCompilerContext(); if (ctx == null) return ; ClassMetaInfoManager cmm =ctx.getClassMetaInfoManager(); List<Breakpoint> invalidBreakPoints = new ArrayList<Breakpoint>(); for (Breakpoint bp : allBreakpoints) { if (bp.getMainClass().equals(mainClass)) { if (!classContainsLineNum(cmm, mainClass, bp.getLineNum())) { invalidBreakPoints.add(bp); } } } allBreakpoints.removeAll(invalidBreakPoints); } public boolean classContainsLineNum(ClassMetaInfoManager cmm, String className, int lineNum) { ClassInfo metaInfo = cmm.getMetaInfo(className); if (metaInfo == null) return false; if (metaInfo.getLineNums().contains(lineNum)) return true; for (String innerClassName : metaInfo.getInnerClasses()) { ClassInfo innerClass = cmm.getMetaInfo(innerClassName); if (innerClass !=null && innerClass.getLineNums().contains(lineNum)) return true; } return false; } public String addTempBreakpoint(String mainClass, String lineNums,boolean resumeThread) { StringBuilder sb = new StringBuilder(); for (String lineNumStr : lineNums.split(",")) { int lineNum = Integer.parseInt(lineNumStr); sb.append(addTempBreakpoint(mainClass, lineNum,resumeThread)).append("\n"); } return sb.toString(); } public String addTempBreakpoint(String mainClass, int lineNum,boolean resumeThread) { ThreadReference threadRef = null; SuspendThreadStack threadStack = null; if (resumeThread ) { debugger.checkVm(); debugger.checkSuspendThread(); threadStack = debugger.getSuspendThreadStack(); threadRef = threadStack.getCurThreadRef(); } String result =this.addBreakpoint(mainClass, lineNum, null,true); if (result.indexOf(Debugger.CMD_SUCCESS) < 0 ) return result; if (resumeThread ) { threadStack.clean(); threadRef.resume(); } return Debugger.CMD_SUCCESS + ":add temp breakpoint at class \"" + mainClass + "\", line " + lineNum ; } public String addWatchpoint(String mainClass, String fieldName, int accessMode) { CompilerContext ctx = debugger.getCompilerContext(); ClassMetaInfoManager cmm = ctx.getClassMetaInfoManager(); ClassInfo metaInfo = cmm.getMetaInfo(mainClass); if (metaInfo == null) return "failure"; for (Breakpoint bp : allBreakpoints) { if (bp.getKind() == Breakpoint.Kind.WATCH_POINT && bp.getMainClass().equals(mainClass) && bp.getField().equals(fieldName) && bp.getAccessMode() == accessMode) { return "watchpoint at class \"" + mainClass + "\", field " + fieldName+ "already exists"; } } Breakpoint breakpoint = new Breakpoint(mainClass, fieldName); breakpoint.setAccessMode(accessMode); allBreakpoints.add(breakpoint); tryCreateRequest(breakpoint); return Debugger.CMD_SUCCESS + ": add watchpoint at class \"" + mainClass + "\", field " + fieldName; } public String addBreakpoint(String mainClass, int lineNum,String conExp) { return this.addBreakpoint(mainClass, lineNum, conExp,false); } public String addBreakpoint(String cmdLine) { Pattern pat = Pattern.compile("^(.*?)\\s+(\\d+(,\\d+)*)\\s+(.*?)(\\s+if\\s+\\{.*?\\})?(\\s+do\\s+\\{.*?\\})?\\s*" ); Matcher matcher = pat.matcher(cmdLine); if (! matcher.matches()) return "parse do command error"; String rowNums = matcher.group(2); List<String> results = new ArrayList<String>(); for (String lineNumStr : rowNums.split(",")) { int lineNum = Integer.parseInt(lineNumStr); String mainClass = matcher.group(4); Breakpoint breakpoint = createBreakpoint(mainClass, lineNum); if (breakpoint == null) { results.add(Debugger.CMD_FAIL + ":no source line " + lineNum +" in class \"" + mainClass+"\""); continue; } String ifClause = matcher.group(5); if (ifClause !=null) { ifClause = ifClause.trim(); String condition = ifClause.substring(ifClause.indexOf("{")+1, ifClause.length()-1); breakpoint.setConExp(condition); } String doClause = matcher.group(6); if (doClause != null) { doClause =doClause.trim(); String[] cmds = doClause.substring(doClause.indexOf("{")+1, doClause.length()-1).split(";"); for (String cmd: cmds) { cmd = cmd.trim(); if (cmd.equals("")) continue; breakpoint.addAutoCmd(cmd); } } tryCreateRequest(breakpoint); results.add(Debugger.CMD_SUCCESS + ": add breakpoint at class \"" + mainClass + "\", line " + lineNum); } StringBuilder sb = new StringBuilder(); for (String item : results) { sb.append(item).append("\n"); } return sb.toString(); } public String addBreakpoint(String mainClass, int lineNum,String conExp,boolean temp) { Breakpoint breakpoint = createBreakpoint(mainClass, lineNum); if (breakpoint == null) { return "no source line " + lineNum +" in class \"" + mainClass+"\""; } breakpoint.setConExp(conExp); breakpoint.setTemp(temp); tryCreateRequest(breakpoint); return Debugger.CMD_SUCCESS + ": add breakpoint at class \"" + mainClass + "\", line " + lineNum; } private Breakpoint createBreakpoint(String mainClass, int lineNum) { Breakpoint breakpoint = null; for (Breakpoint bp : allBreakpoints) { if (bp.getKind() == Breakpoint.Kind.WATCH_POINT) continue; if (bp.getMainClass().equals(mainClass) && bp.getLineNum() == lineNum) { breakpoint = bp; break; } } if (breakpoint != null) return breakpoint; CompilerContext ctx = debugger.getCompilerContext(); ClassMetaInfoManager cmm = ctx.getClassMetaInfoManager(); ClassInfo metaInfo = cmm.getMetaInfo(mainClass); if (metaInfo == null) return null; if (!metaInfo.getLineNums().contains(lineNum)) { for (String innerclassName : metaInfo.getInnerClasses() ) { ClassInfo innerClassInfo = cmm.getMetaInfo(innerclassName); if (innerClassInfo !=null && innerClassInfo.getLineNums().contains(lineNum)) { breakpoint = new Breakpoint(mainClass, innerclassName, lineNum); break; } } } else { breakpoint = new Breakpoint(mainClass, lineNum); } if (breakpoint != null) { allBreakpoints.add(breakpoint); } return breakpoint; } public String removeBreakpoint(String mainClass, String lineNums) { StringBuilder sb = new StringBuilder(); for (String lineNumStr : lineNums.split(",")) { int lineNum = Integer.parseInt(lineNumStr); sb.append(removeBreakpoint(mainClass, lineNum)).append("\n"); } return sb.toString(); } public String removeBreakpoint(String mainClass, int lineNum) { Breakpoint breakpoint = null; for (Breakpoint bp : allBreakpoints) { if (bp.getKind() == Breakpoint.Kind.WATCH_POINT) continue; if (bp.getMainClass().equals(mainClass) && bp.getLineNum() == lineNum) { breakpoint = bp; break; } } if (breakpoint != null) { tryRemoveRequest(breakpoint); allBreakpoints.remove(breakpoint); return Debugger.CMD_SUCCESS + ": remove breakpoint at class \"" + mainClass + "\", line " + lineNum; } return Debugger.CMD_SUCCESS + ": breakpoint at class \"" + mainClass + "\", line " + lineNum + " not exists."; } public String setBreakpointEnable(String mainClass, String loc, boolean enabled) { if (loc.equals("all")) { for (Breakpoint bp : allBreakpoints) { setBreakpointEnable(bp,enabled); } } else { int lineNum = Integer.parseInt(loc); Breakpoint breakpoint = null; for (Breakpoint bp : allBreakpoints) { if (bp.getKind() == Breakpoint.Kind.WATCH_POINT) continue; if (bp.getMainClass().equals(mainClass) && bp.getLineNum() == lineNum) { breakpoint = bp; break; } } if (breakpoint != null) { setBreakpointEnable(breakpoint,enabled); } } return "success"; } private void setBreakpointEnable(Breakpoint bp, boolean enabled) { bp.setEnabled(enabled); for (EventRequest bpRequest : bp.getRequests()) { if (enabled) { bpRequest.enable(); } else { bpRequest.disable(); } } } public String removeWatchpoint(String mainClass, String field) { Breakpoint breakpoint = null; for (Breakpoint bp : allBreakpoints) { if (bp.getKind() == Breakpoint.Kind.BREAK_POINT) continue; if (bp.getMainClass().equals(mainClass) && bp.getField().equals(field)) { breakpoint = bp; break; } } if (breakpoint != null) { tryRemoveRequest(breakpoint); allBreakpoints.remove(breakpoint); return Debugger.CMD_SUCCESS + ": remove watchpoint at class \"" + mainClass + "\", field " + field; } return Debugger.CMD_SUCCESS + ": watchpoint at class \"" + mainClass + "\", field " + field + " not exists."; } public void tryCreatePrepareRequest() { VirtualMachine vm = debugger.getVm(); if (vm==null) return ; EventRequestManager erm = vm.eventRequestManager(); if (erm == null) return; HashSet<String> names = new HashSet<String>(); for (Breakpoint bp : allBreakpoints) { String className = bp.getMainClass(); if (bp.getInnerClass() !=null) { className = bp.getInnerClass(); } if (names.contains(className)) continue; names.add(className); ClassPrepareRequest classPrepareRequest = erm.createClassPrepareRequest(); classPrepareRequest.addClassFilter(className); classPrepareRequest.addCountFilter(1); classPrepareRequest.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD); classPrepareRequest.enable(); } } public void tryRemoveRequest(Breakpoint breakpoint) { VirtualMachine vm = debugger.getVm(); if (vm == null) return; List<EventRequest> requests = breakpoint.getRequests(); if (requests == null || requests.size() == 0) return; for (EventRequest bp : requests) { try { vm.eventRequestManager().deleteEventRequest(bp); } catch (Exception e) { e.printStackTrace(); } } } public void tryCreateBreakpointRequest() { for (Breakpoint bp : allBreakpoints) { tryCreateRequest(bp); } } public void tryResetBreakpointRequest(String className) { for (Breakpoint bp : allBreakpoints) { if (bp.getMainClass().equals(className)) { tryRemoveRequest(bp); tryCreateRequest(bp); } } } public void tryCreateBreakpointRequest(String className) { for (Breakpoint bp : allBreakpoints) { if (bp.getMainClass().equals(className) || (bp.getInnerClass()!=null && bp.getInnerClass().equals(className))) { tryCreateRequest(bp); } } } public void tryCreateRequest(Breakpoint breakpoint) { if (breakpoint.getKind() == Breakpoint.Kind.WATCH_POINT) { _tryCreateWatchpointRequest(breakpoint); } else { _tryCreateBreakpointRequest(breakpoint); } } private void _tryCreateBreakpointRequest(Breakpoint breakpoint) { String className = breakpoint.getMainClass(); if (breakpoint.getInnerClass() !=null) { className = breakpoint.getInnerClass(); } int lineNum = breakpoint.getLineNum(); VirtualMachine vm = debugger.getVm(); if (vm == null) return; List<ReferenceType> refTypes = vm.classesByName(className); if (refTypes == null) return; for (int i = 0; i < refTypes.size(); i++) { ReferenceType rt = refTypes.get(i); if (!rt.isPrepared()) { continue; } List<Location> lines; try { lines = rt.locationsOfLine(lineNum); if (lines.size() == 0) { continue; } Location loc = lines.get(0); BreakpointRequest request = vm.eventRequestManager().createBreakpointRequest(loc); request.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD); request.setEnabled(breakpoint.isEnabled()); request.putProperty("breakpointObj", breakpoint); breakpoint.addRequest(request); } catch (AbsentInformationException e) { e.printStackTrace(); } } } private void _tryCreateWatchpointRequest(Breakpoint breakpoint) { String className = breakpoint.getMainClass(); if (breakpoint.getInnerClass() !=null) { className = breakpoint.getInnerClass(); } breakpoint.clearRequests(); String fieldName = breakpoint.getField(); VirtualMachine vm = debugger.getVm(); if (vm == null) return; List<ReferenceType> refTypes = vm.classesByName(className); if (refTypes == null) return; for (int i = 0; i < refTypes.size(); i++) { ReferenceType rt = refTypes.get(i); if (!rt.isPrepared()) { continue; } Field field =rt.fieldByName(fieldName); if (field == null ) { continue; } if ( (breakpoint.getAccessMode() & Breakpoint.ACCESS_READ) == Breakpoint.ACCESS_READ ) { WatchpointRequest request = vm.eventRequestManager().createAccessWatchpointRequest(field); request.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD); request.setEnabled(breakpoint.isEnabled()); request.putProperty("breakpointObj", breakpoint); breakpoint.addRequest(request); } if ( (breakpoint.getAccessMode() & Breakpoint.ACCESS_WRITE) == Breakpoint.ACCESS_WRITE ) { WatchpointRequest request = vm.eventRequestManager().createModificationWatchpointRequest(field); request.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD); request.setEnabled(breakpoint.isEnabled()); request.putProperty("breakpointObj", breakpoint); breakpoint.addRequest(request); } } } public void clean() { for (Breakpoint bp : allBreakpoints) { bp.clearRequests(); } } }
package com.yoeki.kalpnay.hrporatal.Request; import android.app.Activity; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.yoeki.kalpnay.hrporatal.HomeMenu.Menuitemmodel; import com.yoeki.kalpnay.hrporatal.R; import com.yoeki.kalpnay.hrporatal.Request.Leave.LeaveRequest; import com.yoeki.kalpnay.hrporatal.Request.Leave.NewLeaveFragment; import java.util.ArrayList; public class Attachmentview_adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private static final int TYPE_HEADER = 0; private static final int TYPE_FOOTER = 1; private static final int TYPE_ITEM = 2; private ArrayList<Menuitemmodel> stringArrayList; private Activity activity; NewLeaveFragment fragment; Context context; public Attachmentview_adapter(Activity activity, ArrayList<Menuitemmodel> strings) { this.activity = activity; this.stringArrayList = strings; // this.fragment=fragment; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == TYPE_ITEM) { //Inflating recycle view item layout View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.homeactivity_adapter, parent, false); return new ItemViewHolder(itemView); } else if (viewType == TYPE_FOOTER) { //Inflating footer view View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.footerview, parent, false); return new FooterViewHolder(itemView); } else return null; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { if (holder instanceof FooterViewHolder) { FooterViewHolder footerHolder = (FooterViewHolder) holder; footerHolder.footerimage.setImageResource(R.drawable.plusicon_new); /* footerHolder.footerText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(activity, "You clicked at Footer View", Toast.LENGTH_SHORT).show(); } });*/ } else if (holder instanceof ItemViewHolder) { ItemViewHolder itemViewHolder = (ItemViewHolder) holder; itemViewHolder.imageViewIcon.setImageBitmap(stringArrayList.get(position).getImageid()); itemViewHolder.img_mainmenucross.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { stringArrayList.remove(position); // Toast.makeText(context, String.valueOf(listPosition), Toast.LENGTH_SHORT).show(); notifyDataSetChanged(); } }); } } @Override public int getItemViewType(int position) { if (position == stringArrayList.size()) { return TYPE_FOOTER; } return TYPE_ITEM; } @Override public int getItemCount(){ return stringArrayList.size()+1; } private class FooterViewHolder extends RecyclerView.ViewHolder { ImageView footerimage; public FooterViewHolder(View view) { super(view); footerimage = (ImageView) view.findViewById(R.id.img_footer); footerimage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new NewLeaveFragment().uploadattachmentdialog(activity); /*if(fragment instanceof NewLeaveFragment){ fragment.uploadattachmentdialog(); }else if (activity instanceof ClaimActivity){ ((ClaimActivity)activity).uploadattachmentdialog(); }*/ } }); } } private class ItemViewHolder extends RecyclerView.ViewHolder { TextView itemText; ImageView imageViewIcon,img_mainmenucross; public ItemViewHolder(View itemView) { super(itemView); imageViewIcon =itemView.findViewById(R.id.img_mainmenuitemimage); img_mainmenucross=itemView.findViewById(R.id.img_mainmenucross); } } }
package pajacyk; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import java.io.*; import java.sql.Time; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.Scanner; public class PajacykMain { WebDriver driver = new ChromeDriver(); private File fileToSaveData; PajacykMain(){ System.setProperty("webdriver.chrome.driver", "chromedriver.exe"); driver.navigate().to("https://www.pajacyk.pl"); } private String getUserInputFromPrompt (){ Scanner scanner = new Scanner(System.in); System.out.print("Write down ur name plz- "); String a= scanner.next(); System.out.println("ur name is : " + a); return a; } private void saveUserNameToFile (String StringToSave) throws IOException { try (FileWriter fileWriter = new FileWriter("test.txt")) { fileWriter.write(StringToSave); } } private void checkIfFileExistAndIfNoMakeOne () throws IOException { fileToSaveData = new File("test.txt"); boolean fileExists = fileToSaveData.exists(); System.out.println("attempt to make a file"); if(!fileExists){ FileWriter fileWriter = new FileWriter("test.txt"); System.out.println("there was no file but now its made"); }else{ System.out.println("there is file already"); } } private void makeAClickOnPajacyk (){ driver.findElement(By.xpath("/html/body/div[2]/section/div[5]")).click(); } private void closeConnection (){ driver.close(); } private void getCountOfClicks (){ String a = driver.findElement(By.xpath("//html/body/div[2]/section/div[6]/div[1]")).getText(); System.out.println(a); } private LocalDateTime getTimeDateNow (){ LocalDateTime localDateTime = LocalDateTime.now(); return localDateTime; } private static void readFileContents() throws IOException { System.out.println("Reading contents of file using Scanner class:"); try (FileReader fileReader = new FileReader("test.txt"); Scanner scanner=new Scanner(fileReader)){ while (scanner.hasNext()) { System.out.println("zawartość pliku : " + scanner.next()); } } } public static void main(String[] args) throws InterruptedException, IOException { System.setProperty("webdriver.chrome.driver", "chromedriver.exe"); PajacykMain pajacykMain = new PajacykMain(); pajacykMain.checkIfFileExistAndIfNoMakeOne(); pajacykMain.saveUserNameToFile(pajacykMain.getUserInputFromPrompt()); pajacykMain.readFileContents(); for (int i = 0; i < 10000; i++) { System.out.println("ilość naszych kliknięć: "+ i ); System.out.println("czas kliknięcia : " + pajacykMain.getTimeDateNow()); pajacykMain.makeAClickOnPajacyk(); Thread.sleep(1000); pajacykMain.getCountOfClicks(); Thread.sleep(10000); } pajacykMain.closeConnection(); } }
package com.hesoyam.pharmacy.pharmacy.dto; import com.hesoyam.pharmacy.pharmacy.model.InventoryItemPrice; import com.hesoyam.pharmacy.util.DateTimeRange; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; public class InventoryItemPriceDTO { private Long id; @Min(0) private double price; @NotNull private DateTimeRange range; public InventoryItemPriceDTO(){ //Empty ctor for JSON serializer } public InventoryItemPriceDTO(InventoryItemPrice itemPrice){ this.id = itemPrice.getId(); this.price = itemPrice.getPrice(); this.range = itemPrice.getValidThrough(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public DateTimeRange getRange() { return range; } public void setRange(DateTimeRange range) { this.range = range; } }
package oop; public class App { public static void main(String[] args) { Dog dog=new Dog(); dog.setName("Fido"); System.out.println(dog.getName()); dog.beFriendly(); dog.play(); Ball ball=new Ball(); ball.setupBall(); } }
package com.example.hp.ournetwork; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class BackView extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_back_view); } }
package me.oscardoras.pistonsoverhaul; public class Counter { public int id = 0; public boolean cancel = false; public boolean rotated = false; public int tick = 0; public void up() { tick++; } public void down() { tick--; } }
package app.extension; import magnet.Implementation; @Implementation(forType = Tab.class, forTarget = "2") class UnknownTypeTab2 implements Tab {}
package router; import java.util.Arrays; public class IPAddress { private int[] components; public IPAddress(int[] copy) { // components = Arrays.copyOf(copy, copy.length); components = new int[4]; if (copy.length >= 4) { for (int i = 0; i < 4; ++i) { components[i] = copy[i]; } } else if (copy.length < 4) { for (int i = 0; i < copy.length; ++i) { components[i] = copy[i]; } } this.components = components.clone(); } public static IPAddress fromString(String address) { String[] splitted = address.split("\\."); int[] ip = new int[4]; if (splitted.length == 4) { for (int i = 0; i < ip.length; ++i) { ip[i] = Integer.parseInt(splitted[i]); } return new IPAddress(ip); } else { return null; } } public boolean isTheSame(IPAddress other) { /* if (this.equals(other)) { // konsi szivárogtat return true; } else { return false; }*/ return Arrays.equals(this.components, other.components); } public boolean insideRng(IPAddress ip1, IPAddress ip2) { boolean left = false; boolean right = false; int i = 0; while (i < 4 && !left && ip1.components[i] <= components[i]) { if (ip1.components[i] < components[i]) { left = true; } else { i++; } } int j = 0; while (j < 4 && !right && ip2.components[j]>=components[j]) { if (ip2.components[j]>components[j]) { right=true; } else j++; } if ((i == 4 && j == 4) || (i == 4 && right) || (j == 4 && left) || (left && right)) { return true; } return false; } public String toString() { return components[0] + "." + components[1] + "." + components[2] + "." + components[3]; } }
package com.companyname.springapp.business; import org.springframework.jdbc.datasource.DriverManagerDataSource; public class Conexion { public DriverManagerDataSource Conectar() { DriverManagerDataSource dataSource=new DriverManagerDataSource(); dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost:3306/nomina"); dataSource.setUsername("root"); dataSource.setPassword("j1j2j3j4j5"); return dataSource; } }
package cn.edu.hebtu.software.sharemate.Bean; import android.graphics.Bitmap; import java.util.List; import cn.edu.hebtu.software.sharemate.R; public class NoteBean { private int noId; private int noPhoto; private String title; private int noteImage; private String noteDetail,noteTitle; private UserBean user; private String noteTime; private List<CommentBean> comment; private int zancount,sharecount,collectcount,pingluncount; private String noteImagePath; private Bitmap noteImage1; private CommentBean commentBean; private String zancount1; private String commentDetail = ""; private int zan=R.drawable.xin; private int col=R.drawable.xingxing; private int fol=R.drawable.cancelfollowedbutton_style; private int islike=-1; private int iscollect=-1; private int isfollow;//1表示关注了该用户 -1表示未关注该用户 private UserBean userContent; private int typeid; public NoteBean() { } public NoteBean(String noteDetail, String noteTitle, UserBean user, int typeid) { this.noteDetail = noteDetail; this.noteTitle = noteTitle; this.user = user; this.typeid = typeid; } public NoteBean(int noteImage, String noteDetail, String noteTitle, UserBean user, String noteTime, int zancount, int sharecount, int collectcount, int pingluncount) { this.noteImage = noteImage; this.noteDetail = noteDetail; this.noteTitle = noteTitle; this.user = user; this.noteTime = noteTime; this.zancount = zancount; this.sharecount = sharecount; this.collectcount = collectcount; this.pingluncount = pingluncount; } public NoteBean(int noteImage, String noteDetail, String noteTitle, UserBean user, String noteTime, List<CommentBean> comment, int zancount, int sharecount, int collectcount, int pingluncount) { this.noteImage = noteImage; this.noteDetail = noteDetail; this.noteTitle = noteTitle; this.user = user; this.noteTime = noteTime; this.comment = comment; this.zancount = zancount; this.sharecount = sharecount; this.collectcount = collectcount; this.pingluncount = pingluncount; } public NoteBean(int noPhoto, String title) { this.noPhoto = noPhoto; this.title = title; } public int getTypeid() { return typeid; } public void setTypeid(int typeid) { this.typeid = typeid; } public int getNoPhoto() { return noPhoto; } public void setNoPhoto(int noPhoto) { this.noPhoto = noPhoto; } public String getTitle() { return title; } public void setTitle(String content) { this.title = content; } public int getNoId() { return noId; } public void setNoId(int noId) { this.noId = noId; } public int getNoteImage() { return noteImage; } public void setNoteImage(int noteImage) { this.noteImage = noteImage; } public String getNoteDetail() { return noteDetail; } public void setNoteDetail(String noteDetail) { this.noteDetail = noteDetail; } public String getNoteTitle() { return noteTitle; } public void setNoteTitle(String noteTitle) { this.noteTitle = noteTitle; } public UserBean getUser() { return user; } public void setUser(UserBean user) { this.user = user; } public String getNoteTime() { return noteTime; } public void setNoteTime(String noteTime) { this.noteTime = noteTime; } public List<CommentBean> getComment() { return comment; } public void setComment(List<CommentBean> comment) { this.comment = comment; } public int getZancount() { return zancount; } public void setZancount(int zancount) { this.zancount = zancount; } public int getSharecount() { return sharecount; } public void setSharecount(int sharecount) { this.sharecount = sharecount; } public int getCollectcount() { return collectcount; } public void setCollectcount(int collectcount) { this.collectcount = collectcount; } public int getPingluncount() { return pingluncount; } public void setPingluncount(int pingluncount) { this.pingluncount = pingluncount; } public String getNoteImagePath() { return noteImagePath; } public void setNoteImagePath(String noteImagePath) { this.noteImagePath = noteImagePath; } public Bitmap getNoteImage1() { return noteImage1; } public void setNoteImage1(Bitmap noteImage1) { this.noteImage1 = noteImage1; } public CommentBean getCommentBean() { return commentBean; } public void setCommentBean(CommentBean commentBean) { this.commentBean = commentBean; } public String getZancount1() { return zancount1; } public void setZancount1(String zancount1) { this.zancount1 = zancount1; } public String getCommentDetail() { return commentDetail; } public void setCommentDetail(String commentDetail) { this.commentDetail = commentDetail; } public int getZan() { return zan; } public void setZan(int zan) { this.zan = zan; } public int getCol() { return col; } public void setCol(int col) { this.col = col; } public int getFol() { return fol; } public void setFol(int fol) { this.fol = fol; } public int isIslike() { return islike; } public void setIslike(int islike) { this.islike = islike; } public int getIscollect() { return iscollect; } public void setIscollect(int iscollect) { this.iscollect = iscollect; } public int getIsfollow() { return isfollow; } public void setIsfollow(int isfollow) { this.isfollow = isfollow; } public UserBean getUserContent() { return userContent; } public void setUserContent(UserBean userContent) { this.userContent = userContent; } }
package com.tencent.mm.plugin.card.model; import com.tencent.mm.bt.h.d; class am$9 implements d { am$9() { } public final String[] xb() { return h.diD; } }
package aspect.sample.fm; public class PickleFeature extends AtomicFeature { public PickleFeature() { super("Pickle"); } }
package com.kingfish.show.mybatis.model; import java.io.Serializable; import java.util.Date; public class Msg implements Serializable { /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column msg.id * * @mbg.generated */ private Long id; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column msg.gmt_create * * @mbg.generated */ private Date gmtCreate; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column msg.gmt_modify * * @mbg.generated */ private Date gmtModify; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column msg.show_id * * @mbg.generated */ private Long showId; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column msg.from_user_id * * @mbg.generated */ private Long fromUserId; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column msg.to_user_id * * @mbg.generated */ private Long toUserId; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column msg.content * * @mbg.generated */ private String content; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column msg.parent_msg_id * * @mbg.generated */ private Long parentMsgId; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column msg.agree_num * * @mbg.generated */ private Integer agreeNum; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column msg.ip * * @mbg.generated */ private String ip; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table msg * * @mbg.generated */ private static final long serialVersionUID = 1L; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column msg.id * * @return the value of msg.id * * @mbg.generated */ public Long getId() { return id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column msg.id * * @param id the value for msg.id * * @mbg.generated */ public void setId(Long id) { this.id = id; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column msg.gmt_create * * @return the value of msg.gmt_create * * @mbg.generated */ public Date getGmtCreate() { return gmtCreate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column msg.gmt_create * * @param gmtCreate the value for msg.gmt_create * * @mbg.generated */ public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column msg.gmt_modify * * @return the value of msg.gmt_modify * * @mbg.generated */ public Date getGmtModify() { return gmtModify; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column msg.gmt_modify * * @param gmtModify the value for msg.gmt_modify * * @mbg.generated */ public void setGmtModify(Date gmtModify) { this.gmtModify = gmtModify; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column msg.show_id * * @return the value of msg.show_id * * @mbg.generated */ public Long getShowId() { return showId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column msg.show_id * * @param showId the value for msg.show_id * * @mbg.generated */ public void setShowId(Long showId) { this.showId = showId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column msg.from_user_id * * @return the value of msg.from_user_id * * @mbg.generated */ public Long getFromUserId() { return fromUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column msg.from_user_id * * @param fromUserId the value for msg.from_user_id * * @mbg.generated */ public void setFromUserId(Long fromUserId) { this.fromUserId = fromUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column msg.to_user_id * * @return the value of msg.to_user_id * * @mbg.generated */ public Long getToUserId() { return toUserId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column msg.to_user_id * * @param toUserId the value for msg.to_user_id * * @mbg.generated */ public void setToUserId(Long toUserId) { this.toUserId = toUserId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column msg.content * * @return the value of msg.content * * @mbg.generated */ public String getContent() { return content; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column msg.content * * @param content the value for msg.content * * @mbg.generated */ public void setContent(String content) { this.content = content == null ? null : content.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column msg.parent_msg_id * * @return the value of msg.parent_msg_id * * @mbg.generated */ public Long getParentMsgId() { return parentMsgId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column msg.parent_msg_id * * @param parentMsgId the value for msg.parent_msg_id * * @mbg.generated */ public void setParentMsgId(Long parentMsgId) { this.parentMsgId = parentMsgId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column msg.agree_num * * @return the value of msg.agree_num * * @mbg.generated */ public Integer getAgreeNum() { return agreeNum; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column msg.agree_num * * @param agreeNum the value for msg.agree_num * * @mbg.generated */ public void setAgreeNum(Integer agreeNum) { this.agreeNum = agreeNum; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column msg.ip * * @return the value of msg.ip * * @mbg.generated */ public String getIp() { return ip; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column msg.ip * * @param ip the value for msg.ip * * @mbg.generated */ public void setIp(String ip) { this.ip = ip == null ? null : ip.trim(); } }
package pages; import static com.codeborne.selenide.CollectionCondition.texts; import static com.codeborne.selenide.Condition.text; import static com.codeborne.selenide.Selectors.byText; import static com.codeborne.selenide.Selenide.*; public class StudentRegistrationFormPage { public void openPage() { open("/automation-practice-form"); $(".practice-form-wrapper").shouldHave(text("Student Registration Form")); } public void typeFirstName(String value) { $("#firstName").setValue(value); } public void typeSecondName(String value) { $("#lastName").setValue(value); } public void typeEmail(String value) { $("#userEmail").setValue(value); } public void chooseGender(String value) { $(byText(value)).click(); } public void typePhoneNumber(String value) { $("#userNumber").setValue(value); } public void chooseDateOfBirth(String day, String month, String year) { $("#dateOfBirthInput").click(); $(".react-datepicker__year-select").selectOption(year); $(".react-datepicker__month-select").selectOption(month); $(String.format(".react-datepicker__day--0%s:not(.react-datepicker__day--outside-month)", day)).click(); } public void typeSubject(String value) { $("#subjectsInput").setValue(value).pressEnter(); } public void chooseHobby(String value) { $(byText(value)).click(); } public void uploadImage(String value) { $("#uploadPicture").uploadFromClasspath("images/" + value); } public void typeAddress(String value) { $("#currentAddress").setValue(value).scrollTo(); } public void chooseStateAndCity(String state, String city) { $(byText("Select State")).click(); $(byText(state)).click(); $(byText("Select City")).click(); $(byText(city)).click(); } public void pressSubmit() { $("#submit").click(); } public void checkResults(String firstName, String lastName, String email, String gender, String mobile, String dayOfBirth, String monthOfBirth, String yearOfBirth, String subject, String hobby, String picture, String currentAddress, String state, String city) { $("#example-modal-sizes-title-lg").shouldHave(text("Thanks for submitting the form")); $$("tbody tr").filter(text("Student name")).shouldHave(texts(firstName + " " + lastName)); $$("tbody tr").filter(text("Student Email")).shouldHave(texts(email)); $$("tbody tr").filter(text("Gender")).shouldHave(texts(gender)); $$("tbody tr").filter(text("Mobile")).shouldHave(texts(mobile)); $$("tbody tr").filter(text("Date of Birth")).shouldHave(texts(dayOfBirth + " " + monthOfBirth + "," + yearOfBirth)); $$("tbody tr").filter(text("Subjects")).shouldHave(texts(subject)); $$("tbody tr").filter(text("Hobbies")).shouldHave(texts(hobby)); $$("tbody tr").filter(text("Picture")).shouldHave(texts(picture)); $$("tbody tr").filter(text("Address")).shouldHave(texts(currentAddress)); $$("tbody tr").filter(text("State and City")).shouldHave(texts(state + " " + city)); } }
package com.example.marek.komunikator.controllers.config; /** * Created by marek on 20.01.18. */ public abstract class Controller { protected Response response; protected static String JWT; public Controller(Response response) { this.response = response; } public abstract void proceed(); }
package com.rofour.baseball.dao.store.bean; import java.io.Serializable; /** * 爱学派门店dto类 * * @author WJ * */ public class AxpBean implements Serializable{ /** * @Fields serialVersionUID */ private static final long serialVersionUID = 6175543863110225702L; /** * 就是商户编码Store_id */ private Long stoAxpId; /** * 商户名字store_name */ private String stoAxpName; /** * 学校id */ private Long collegeId; /** * 学校名字 */ private String collegeName; public AxpBean() { } public AxpBean(Long stoAxpId, String stoAxpName,Long collegeId,String collegeName) { super(); this.stoAxpId = stoAxpId; this.stoAxpName = stoAxpName; this.collegeId = collegeId; this.collegeName = collegeName; } public Long getStoAxpId() { return stoAxpId; } public void setStoAxpId(Long stoAxpId) { this.stoAxpId = stoAxpId; } public String getStoAxpName() { return stoAxpName; } public void setStoAxpName(String stoAxpName) { this.stoAxpName = stoAxpName; } public Long getCollegeId() { return collegeId; } public void setCollegeId(Long collegeId) { this.collegeId = collegeId; } public String getCollegeName() { return collegeName; } public void setCollegeName(String collegeName) { this.collegeName = collegeName; } @Override public String toString() { return "Axp [stoAxpId=" + stoAxpId + ", stoAxpName=" + stoAxpName + "]"; } }
package com.yjjyjy.yjj.controller.account; import java.awt.image.BufferedImage; import java.io.OutputStream; import java.util.Map; import javax.annotation.Resource; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.mobile.device.Device; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.util.WebUtils; import com.yjjyjy.yjj.common.utils.ImageCodeUtils; import com.yjjyjy.yjj.common.utils.ResponseUtil; import com.yjjyjy.yjj.entity.User; import com.yjjyjy.yjj.repository.UserRepository; import com.yjjyjy.yjj.service.impl.UserServiceImpl; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @RestController @EnableAutoConfiguration @RequestMapping("/login") @Api(value="用户登录") public class LoginController { @Autowired private UserServiceImpl userServiceImpl; // @RequestMapping(value="/test", method = RequestMethod.GET) // @ResponseBody // public String test(){ // return "hello"; // } // @RequestMapping(value="/login", method = RequestMethod.POST) // public String login(HttpServletRequest request){ // String name = request.getParameter("name"); // String psd = request.getParameter("psd"); // // return "name:" + name + " " + "password:" + psd; // } @RequestMapping(value="/checklogin",method = RequestMethod.POST) @ApiOperation(value = "用户登录", notes = "用户登录") @ResponseBody public Map<String, Object> checkLogin(@RequestParam("cellphone") String cellphone, @RequestParam("password") String pwd, HttpServletRequest request,HttpServletResponse response,HttpSession httpSession) { //解决跨域问题出 response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET,POST"); // String cellphone = request.getParameter("cellphone"); // String pwd = request.getParameter("password"); boolean flag = userServiceImpl.checkLoginCommon(cellphone, pwd); if(flag){ httpSession.setAttribute("cellphone", cellphone); return ResponseUtil.responseResultByBoolean(flag); } else { return ResponseUtil.responseResultByBoolean(false); } } @RequestMapping(value="/getUserSession",method = RequestMethod.POST) @ApiOperation(value = "获取信息", notes = "") @ResponseBody public String getUserSession( HttpServletRequest request,HttpServletResponse response,HttpSession httpSession) { //解决跨域问题出 response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET,POST"); // String cellphone = request.getParameter("cellphone"); // String pwd = request.getParameter("password"); String result = null; String cellphone = null; if(httpSession!=null) { cellphone = (String)httpSession.getAttribute("cellphone"); } result = "{\"cellphone\":"+cellphone + "}"; return result; } @RequestMapping(value="/logoutuser",method = RequestMethod.GET) @ApiOperation(value = "获取信息", notes = "") @ResponseBody public String logoutUserSession( HttpServletRequest request,HttpServletResponse response,HttpSession httpSession) { //解决跨域问题出 response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET,POST"); // String cellphone = request.getParameter("cellphone"); // String pwd = request.getParameter("password"); String result = null; if(httpSession!=null) { httpSession.removeAttribute("cellphone"); //cellphone = (String)httpSession.getAttribute("cellphone"); } result = "{\"flag\":"+"\"success\"" + "}"; return result; } @RequestMapping(value="/checkloginManager",method = RequestMethod.POST) @ApiOperation(value = "管理员登录", notes = "管理员登录") @ResponseBody public Map<String, Object> checkLoginManager(@RequestParam("username") String nickname, @RequestParam("password") String pwd, HttpServletRequest request,HttpServletResponse response,HttpSession httpSession) { //解决跨域问题出 response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET,POST"); // String nickname = request.getParameter("username"); // String pwd = request.getParameter("password"); // return ResponseUtil.responseResultByBoolean(); // return userServiceImpl.getPasswordByCellphone(cellphone); boolean flag = userServiceImpl.checkLoginManager(nickname, pwd); if(flag){ httpSession.setAttribute("nickname", nickname); return ResponseUtil.responseResultByBoolean(flag); } else { return ResponseUtil.responseResultByBoolean(false); } } @RequestMapping(value="/getManagerSession",method = RequestMethod.POST) @ApiOperation(value = "获取信息", notes = "") @ResponseBody public String getManagerSession( HttpServletRequest request,HttpServletResponse response,HttpSession httpSession) { //解决跨域问题出 response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET,POST"); // String cellphone = request.getParameter("cellphone"); // String pwd = request.getParameter("password"); String result = null; String nickname = null; if(httpSession!=null) { nickname = (String)httpSession.getAttribute("nickname"); } result = "{\"nickname\":"+ nickname + "}"; return result; } @RequestMapping(value="/logoutmanager",method = RequestMethod.GET) @ApiOperation(value = "获取信息", notes = "") @ResponseBody public String logoutManagerSession( HttpServletRequest request,HttpServletResponse response,HttpSession httpSession) { //解决跨域问题出 response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET,POST"); String result = null; if(httpSession!=null) { httpSession.removeAttribute("nickname"); } result = "{\"flag\":"+"\"success\"" + "}"; return result; } }
package com.yixin.kepler.v1.service.capital.yntrust; import javax.annotation.Resource; import com.yixin.kepler.enity.AssetContractTask; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSONObject; import com.yixin.common.utils.JsonObjectUtils; import com.yixin.dsc.common.exception.BzException; import com.yixin.dsc.util.PropertiesManager; import com.yixin.dsc.v1.service.capital.yntrust.YTCommonService; import com.yixin.kepler.common.RestTemplateUtil; import com.yixin.kepler.common.UrlConstant; import com.yixin.kepler.common.enums.BankPhaseEnum; import com.yixin.kepler.core.constant.CommonConstant; import com.yixin.kepler.dto.BaseMsgDTO; import com.yixin.kepler.enity.AssetBankTran; import com.yixin.kepler.v1.common.enumpackage.YNTrustUrlEnum; import com.yixin.kepler.v1.datapackage.dto.yntrust.YTCommonResponseDTO; import com.yixin.kepler.v1.datapackage.dto.yntrust.YTOrderCancelDto; import java.util.List; /** * 云信取消订单 * @author YixinCapital -- chenjiacheng * 2018年09月20日 9:56 **/ @Service public class YTOrderCancelRequest { private static final Logger logger = LoggerFactory.getLogger(YTOrderCancelRequest.class); @Resource private YTCommonService ytCommonService; @Resource private PropertiesManager propertiesManager; /** * 云信订单取消 * @param assetMainInfo 主表信息 * @return 取消结果 * @author YixinCapital -- chenjiacheng * 2018/9/20 10:01 */ public BaseMsgDTO sendResult(String venusApplyNo,String applyNo,String assetMainId) { try { YTOrderCancelDto orderCancelDto = new YTOrderCancelDto(); orderCancelDto.setRequestId(ytCommonService.getRequestId()); orderCancelDto.setUniqueId(venusApplyNo); orderCancelDto.setUrl(YNTrustUrlEnum.CANCEL_LOAN.getUrl()); String osbUrl = this.propertiesManager.getOsbEnvironment() + UrlConstant.OsbSystemUrl.ynTrustInterface; //================ 银行交互记录 =================================== AssetBankTran assetBankTran = new AssetBankTran(); assetBankTran.setReqBody(JsonObjectUtils.objectToJson(orderCancelDto)); assetBankTran.setApplyNo(applyNo); assetBankTran.setAssetId(assetMainId); assetBankTran.setAssetNo(CommonConstant.BankName.YNTRUST_BANK); assetBankTran.setPhase(BankPhaseEnum.ORDER_CANCEL.getPhase()); assetBankTran.setReqUrl(osbUrl); assetBankTran.setApiCode(orderCancelDto.getUrl()); assetBankTran.setSender(CommonConstant.SenderType.YIXIN); assetBankTran.setTranNo(orderCancelDto.getRequestId()); assetBankTran.setBankOrderNo(venusApplyNo); assetBankTran.create(); logger.info("云信取消订单开始,applyNo={},url={},params={}", applyNo, osbUrl, assetBankTran.getReqBody()); String result = RestTemplateUtil.sendRequest(osbUrl, assetBankTran.getReqBody(),CommonConstant.BankName.YNTRUST_BANK); logger.info("云信取消订单结束,applyNo={},result={}", applyNo, result); if(StringUtils.isBlank(result)){ throw new BzException("云信订单取消失败"); } assetBankTran.setRepBody(result); YTCommonResponseDTO responseDTO = JSONObject.parseObject(ytCommonService.parseResponse(result), YTCommonResponseDTO.class); if (responseDTO == null || responseDTO.getStatus() == null || Boolean.FALSE.equals(responseDTO.getStatus().getIsSuccess())) { assetBankTran.setApprovalCode((responseDTO == null || responseDTO.getStatus() == null) ? "null" : responseDTO.getStatus().getResponseCode()); assetBankTran.setApprovalDesc((responseDTO == null || responseDTO.getStatus() == null) ? "null" : responseDTO.getStatus().getResponseMessage()); assetBankTran.update(); return new BaseMsgDTO(CommonConstant.FAILURE,"云信取消订单失败"); } assetBankTran.setApprovalCode(responseDTO.getStatus().getResponseCode()); assetBankTran.setApprovalDesc(responseDTO.getStatus().getResponseMessage()); assetBankTran.update(); //@autor sukang 如果存在,将获取合同任务取消 List<AssetContractTask> contractTasks = AssetContractTask.getContractTask(venusApplyNo); if (CollectionUtils.isNotEmpty(contractTasks)){ contractTasks.forEach(t -> { t.setDeleted(true); t.update(); }); } } catch (Exception e) { throw new BzException(e); } return new BaseMsgDTO(CommonConstant.SUCCESS,"云信取消订单成功"); } }
package dados; import java.util.ArrayList; import beans.Fornecedor; import java.util.List; import java.util.Collections; public class RepositorioFornecedor implements IRepositorioFornecedor { private ArrayList<Fornecedor> listaFornecedores; private static RepositorioFornecedor instance; public RepositorioFornecedor(){ this.listaFornecedores = new ArrayList<Fornecedor>(); } public static RepositorioFornecedor getInstance(){ if(instance == null){ instance = new RepositorioFornecedor(); } return instance; } public ArrayList<Fornecedor> getListaFornecedores() { return listaFornecedores; } public void setListaFornecedores(ArrayList<Fornecedor> listaFornecedores) { this.listaFornecedores = listaFornecedores; } public boolean cadastrarFornecedor(Fornecedor fornecedor) { try { listaFornecedores.add(fornecedor); } catch (Exception e){ return false; } return true; } public boolean alterarFornecedor(Fornecedor fornAlterado, Fornecedor novoFornecedor) { boolean alt = false; for(Fornecedor fornecedor : listaFornecedores){ if(fornecedor.getCodigo() == fornAlterado.getCodigo()) { listaFornecedores.remove(fornecedor); listaFornecedores.add(novoFornecedor); alt = true; } } return alt; } public Fornecedor buscarFornecedor(int codigo) { for(Fornecedor fornecedor : listaFornecedores) { if(fornecedor.getCodigo() == codigo) { return fornecedor; } } return null; } public boolean removerFornecedor(int codigo) { boolean igual = false; for(int i =0;i<listaFornecedores.size();i++){ if(listaFornecedores.get(i).getCodigo()==codigo){ listaFornecedores.remove(i); igual=true; } } return igual; } public boolean fornecedorExiste(int codigo) { int f; boolean x = false; for(Fornecedor fornecedor : listaFornecedores) { f = fornecedor.getCodigo(); if(f == codigo) { x = true; } } return x; } public List<Fornecedor> listar(){ return Collections.unmodifiableList(this.listaFornecedores); } @Override public String toString() { return "RepositorioFornecedor [listaFornecedores = " + listaFornecedores +"]"; } }
package com.tencent.mm.ac; import com.tencent.mm.protocal.c.cgc; import java.util.LinkedList; public interface h$a { String MQ(); void d(LinkedList<cgc> linkedList); }
package com.yida.design.responsibility.generator; /** ********************* * 处理者返回的数据 * * @author yangke * @version 1.0 * @created 2018年5月12日 下午3:37:42 *********************** */ public class Response { }
/* * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.openrtb.util; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.collect.AbstractIterator; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.openrtb.OpenRtb.BidRequest; import com.google.openrtb.OpenRtb.BidRequest.Imp; import com.google.openrtb.OpenRtb.BidRequest.Imp.Banner; import com.google.openrtb.OpenRtb.BidResponse; import com.google.openrtb.OpenRtb.BidResponse.SeatBid; import com.google.openrtb.OpenRtb.BidResponse.SeatBid.Bid; import com.google.openrtb.OpenRtb.BidResponse.SeatBidOrBuilder; import com.google.openrtb.OpenRtb.ContentCategory; import java.util.Iterator; import java.util.List; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import java.util.stream.StreamSupport; import javax.annotation.Nullable; /** * Utilities to manipulate {@link BidRequest} and * {@link com.google.openrtb.OpenRtb.BidResponse.Builder}. */ public final class OpenRtbUtils { /** * Special value for the {@code seat} parameter of some methods. Notice that you can't * pass any string with the same value, you need to pass a reference to this unique object. */ public static final String SEAT_ANY = "*"; /** * Special value for for {@code impFilter} parameter of some methods, will be more efficient * than an equivalent {@code imp -> false} predicate. */ public static final Predicate<Imp> IMP_NONE = imp -> false; /** * Special value for for {@code impFilter} parameter of some methods, will be more efficient * than an equivalent {@code imp -> true} predicate. */ public static final Predicate<Imp> IMP_ALL = imp -> true; private static final ImmutableMap<Object, String> CAT_TO_JSON; private static final ImmutableMap<String, ContentCategory> NAME_TO_CAT; static { ImmutableMap.Builder<Object, String> catToJson = ImmutableMap.builder(); ImmutableMap.Builder<String, ContentCategory> nameToCat = ImmutableMap.builder(); for (ContentCategory cat : ContentCategory.values()) { String json = cat.name().replace('_', '-'); catToJson.put(cat.name(), json); catToJson.put(cat, json); nameToCat.put(cat.name(), cat); if (!json.equals(cat.name())) { catToJson.put(json, json); nameToCat.put(json, cat); } } CAT_TO_JSON = catToJson.build(); NAME_TO_CAT = nameToCat.build(); } /** * Get a {@link ContentCategory} from its name (either Java or JSON name). */ @Nullable public static ContentCategory categoryFromName(@Nullable String catName) { return NAME_TO_CAT.get(catName); } /** * Get a {@link ContentCategory}'s JSON name, from its Java name. */ @Nullable public static String categoryToJsonName(@Nullable String catName) { return CAT_TO_JSON.get(catName); } /** * Get a {@link ContentCategory}'s JSON name. */ @Nullable public static String categoryToJsonName(@Nullable ContentCategory cat) { return CAT_TO_JSON.get(cat); } /** * @return The OpenRTB SeatBid with the specified ID; will be created if not existent. * The ID should be present in the request's wseat. * * @see #seatBid(com.google.openrtb.OpenRtb.BidResponse.Builder) * Use for the anonymous seat */ public static SeatBid.Builder seatBid(BidResponse.Builder response, String seat) { checkNotNull(seat); for (SeatBid.Builder seatbid : response.getSeatbidBuilderList()) { if (seatbid.hasSeat() && seat.equals(seatbid.getSeat())) { return seatbid; } } return response.addSeatbidBuilder().setSeat(seat); } /** * @return The anonymous OpenRTB SeatBid, used by non-seat-specific bids (the seat ID is not set). * Will be created if not existent. */ public static SeatBid.Builder seatBid(BidResponse.Builder response) { for (SeatBid.Builder seatbid : response.getSeatbidBuilderList()) { if (!seatbid.hasSeat()) { return seatbid; } } return response.addSeatbidBuilder(); } /** * Iterates all bids. * * @return Read-only sequence of all bis in the response. * May have bids from multiple seats, grouped by seat */ public static Iterable<Bid.Builder> bids(BidResponse.Builder response) { return new ResponseBidsIterator(response, SEAT_ANY, null); } /** * Iterates all bids from a specific seat. * * @param seatFilter Filter for seatFilter. You can use {@code null} to select the anonymous seat, * or {@link #SEAT_ANY} to not filter by seat * @return View for the seat's internal sequence of bids; or an empty, read-only * view if that seat doesn't exist. */ public static List<Bid.Builder> bids(BidResponse.Builder response, @Nullable String seatFilter) { for (SeatBid.Builder seatbid : response.getSeatbidBuilderList()) { if (filterSeat(seatbid, seatFilter)) { return seatbid.getBidBuilderList(); } } return ImmutableList.of(); } /** * Finds a bid by ID. * * @param id Bid ID, assumed to be unique within the response * @return Matching bid's builder, or {@code null} if not found */ @Nullable public static Bid.Builder bidWithId(BidResponse.Builder response, String id) { checkNotNull(id); for (SeatBid.Builder seatbid : response.getSeatbidBuilderList()) { for (Bid.Builder bid : seatbid.getBidBuilderList()) { if (id.equals(bid.getId())) { return bid; } } } return null; } /** * Finds a bid by seat and ID. * * @param seatFilter Filter for seatFilter. You can use {@code null} to select the anonymous seat, * or {@link #SEAT_ANY} to not filter by seat * @param id Bid ID, assumed to be unique within the filtered seats * @return Matching bid's builder, or {@code null} if not found */ @Nullable public static Bid.Builder bidWithId( BidResponse.Builder response, @Nullable String seatFilter, String id) { checkNotNull(id); for (SeatBid.Builder seatbid : response.getSeatbidBuilderList()) { if (filterSeat(seatbid, seatFilter)) { for (Bid.Builder bid : seatbid.getBidBuilderList()) { if (id.equals(bid.getId())) { return bid; } } return null; } } return null; } /** * Finds bids by a custom criteria. * * @param bidFilter Filter for bids * @param seatFilter Filter for seat. You can use {@code null} to select the anonymous seat, * or {@link #SEAT_ANY} to not filter by seat * @return Read-only sequence of bids that satisfy the filter. * May have bids from multiple seats, grouped by seat */ public static Stream<Bid.Builder> bidStreamWith( BidResponse.Builder response, @Nullable String seatFilter, @Nullable Predicate<Bid.Builder> bidFilter) { return StreamSupport.stream( new ResponseBidsIterator(response, seatFilter, bidFilter).spliterator(), false); } /** * Finds bids by a custom criteria. * * @param bidFilter Filter for bids * @param seatFilter Filter for seat. You can use {@code null} to select the anonymous seat, * or {@link #SEAT_ANY} to not filter by seat * @return Sequence of all bids that satisfy the filter. * May have bids from multiple seats, grouped by seat */ public static Iterable<Bid.Builder> bidsWith( BidResponse.Builder response, @Nullable String seatFilter, @Nullable Predicate<Bid.Builder> bidFilter) { return new ResponseBidsIterator(response, seatFilter, bidFilter); } /** * Updates bids, from all seats. * * @param updater Update function. The {@code apply()} method can decide or not to update each * object, and it's expected to return {@code true} for objects that were updated * @return {@code true} if at least one bid was updated * @see ProtoUtils#update(Iterable, Function) for more general updating support */ public static boolean updateBids( BidResponse.Builder response, Function<Bid.Builder, Boolean> updater) { checkNotNull(updater); boolean updated = false; for (SeatBid.Builder seatbid : response.getSeatbidBuilderList()) { updated |= ProtoUtils.update(seatbid.getBidBuilderList(), updater); } return updated; } /** * Updates bids from a given seat. * * @param seatFilter Seat ID, or {@code null} to select the anonymous seat * @param updater Update function. The {@code apply()} method can decide or not to update each * object, and it's expected to return {@code true} for objects that were updated * @return {@code true} if at least one bid was updated * @see ProtoUtils#update(Iterable, Function) for more general updating support */ public static boolean updateBids( BidResponse.Builder response, @Nullable String seatFilter, Function<Bid.Builder, Boolean> updater) { checkNotNull(updater); for (SeatBid.Builder seatbid : response.getSeatbidBuilderList()) { if (filterSeat(seatbid, seatFilter)) { return ProtoUtils.update(seatbid.getBidBuilderList(), updater); } } return false; } /** * Remove bids by bid. * * @param filter Returns {@code true} to keep bid, {@code false} to remove * @return {@code true} if any bid was removed * @see ProtoUtils#filter(List, Predicate) for more general filtering support */ public static boolean removeBids(BidResponse.Builder response, Predicate<Bid.Builder> filter) { checkNotNull(filter); boolean updated = false; for (SeatBid.Builder seatbid : response.getSeatbidBuilderList()) { updated |= removeBids(seatbid, filter); } return updated; } private static boolean removeBids(SeatBid.Builder seatbid, Predicate<Bid.Builder> filter) { List<Bid.Builder> oldBids = seatbid.getBidBuilderList(); Iterable<Bid.Builder> newBids = ProtoUtils.filter(oldBids, filter); if (newBids == oldBids) { return false; } else { seatbid.clearBid(); for (Bid.Builder bid : newBids) { seatbid.addBid(bid); } return true; } } /** * Remove bids by seat and bid. * * @param seatFilter Seat ID, or {@code null} to select the anonymous seat * @param bidFilter Returns {@code true} to keep bid, {@code false} to remove * @return {@code true} if any bid was removed * @see ProtoUtils#filter(List, Predicate) for more general filtering support */ public static boolean removeBids( BidResponse.Builder response, @Nullable String seatFilter, Predicate<Bid.Builder> bidFilter) { checkNotNull(bidFilter); boolean updated = false; for (SeatBid.Builder seatbid : response.getSeatbidBuilderList()) { if (filterSeat(seatbid, seatFilter)) { updated |= removeBids(seatbid, bidFilter); } } return updated; } /** * Finds an {@link Imp} by ID. * * @return The {@link Imp}s that has the given id, or {@code null} if not found. */ @Nullable public static Imp impWithId(BidRequest request, String id) { checkNotNull(id); for (Imp imp : request.getImpList()) { if (imp.getId().equals(id)) { return imp; } } return null; } /** * Find an {@link Imp} by its ID and its {@link Banner}'s ID. * * @param impId Imp ID; optional if the Banner IDs are unique within the request * @param bannerId Banner ID * @return The {@link Imp} for a given impression ID x banner ID, or {@code null} if not found */ @Nullable public static Imp bannerImpWithId( BidRequest request, @Nullable String impId, String bannerId) { checkNotNull(bannerId); for (Imp imp : request.getImpList()) { if ((impId == null || imp.getId().equals(impId)) && imp.hasBanner() && imp.getBanner().getId().equals(bannerId)) { return imp; } } return null; } /** * Optimized code for most filtered lookups. This is worth the effort * because bidder code may invoke these lookup methods intensely; * common cases like everything-filtered or nothing-filtered are very dominant; * and simpler code previously used needed lots of temporary collections. * * @param request Container of impressions * @param impFilter Filters impressions; will be executed exactly once, * and only for impressions that pass the banner/video type filters. * The constants {@link #IMP_NONE} and {@link #IMP_ALL} allow * more efficient execution when you want to filter none/all impressions. * @return Immutable or unmodifiable view for the filtered impressions */ public static Iterable<Imp> impsWith(BidRequest request, Predicate<Imp> impFilter) { checkNotNull(impFilter); List<Imp> imps = request.getImpList(); if (imps.isEmpty() || impFilter == IMP_ALL) { return imps; } else if (impFilter == IMP_NONE) { return ImmutableList.of(); } boolean included = impFilter.test(imps.get(0)); int size = imps.size(), i; for (i = 1; i < size; ++i) { if (impFilter.test(imps.get(i)) != included) { break; } } if (i == size) { return included ? imps // Unmodifiable, comes from protobuf : ImmutableList.<Imp>of(); } int headingSize = i; return new FluentIterable<Imp>() { @Override public Iterator<Imp> iterator() { Iterator<Imp> unfiltered = imps.iterator(); return new AbstractIterator<Imp>() { private int heading = 0; @Override protected Imp computeNext() { while (unfiltered.hasNext()) { Imp imp = unfiltered.next(); if ((heading++ < headingSize) ? included : impFilter.test(imp)) { return imp; } } return endOfData(); }}; }}; } public static Stream<Imp> impStreamWith(BidRequest request, Predicate<Imp> impFilter) { return StreamSupport.stream(impsWith(request, impFilter).spliterator(), false); } /** * Adds "impression type" subfilters to a base filter, to further restricts impressions * that contain a banner, video and/or native object. * * @param baseFilter base filter for impressions * @param banner {@code true} to include impressions with * {@link com.google.openrtb.OpenRtb.BidRequest.Imp.Banner}s * @param video {@code true} to include impressions with * {@link com.google.openrtb.OpenRtb.BidRequest.Imp.Video}s * @param nativ {@code true} to include impressions with * {@link com.google.openrtb.OpenRtb.BidRequest.Imp.Native}s * @return A filter in the form: {@code baseFilter AND (banner OR video OR native)} */ public static Predicate<Imp> addFilters( Predicate<Imp> baseFilter, boolean banner, boolean video, boolean nativ) { int orCount = (banner ? 1 : 0) + (video ? 1 : 0) + (nativ ? 1 : 0); if (baseFilter == IMP_NONE || orCount == 0) { return baseFilter; } Predicate<Imp> typeFilter = null; if (banner) { typeFilter = Imp::hasBanner; } if (video) { typeFilter = typeFilter == null ? Imp::hasVideo : typeFilter.or(Imp::hasVideo); } if (nativ) { typeFilter = typeFilter == null ? Imp::hasNative : typeFilter.or(Imp::hasNative); } return baseFilter == IMP_ALL ? typeFilter : baseFilter.and(typeFilter); } /** * Performs a filter by seat. * * @param seatbid Seat to filter * @param seatFilter Filter for seat. You can use {@code null} to select the anonymous seat, * or {@link #SEAT_ANY} to not filter by seat * @return {@code true} if the seat passes the filter */ public static boolean filterSeat(SeatBidOrBuilder seatbid, @Nullable String seatFilter) { return seatFilter == null ? !seatbid.hasSeat() : seatFilter == SEAT_ANY || seatFilter.equals(seatbid.getSeat()); } }
/* * 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 loc.daos; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import loc.db.DBConnection; import loc.dtos.CommentDTO; /** * * @author hi */ public class CommentDAO { private Connection conn = null; private PreparedStatement pre = null; private ResultSet rs = null; public CommentDAO() { } public void closeConnection() throws Exception { if (rs != null) { rs.close(); } if (pre != null) { pre.close(); } if (conn != null) { conn.close(); } } public String getCommentID() throws Exception { String count = null; try { String sql = "SELECT COUNT(ID)+1 as Count From tblComment"; conn = DBConnection.getMyConnection(); pre = conn.prepareStatement(sql); rs = pre.executeQuery(); if (rs.next()) { count = rs.getString("Count"); } } catch (Exception e) { } finally { closeConnection(); } return count; } public String getCommentDate(String id) throws Exception { String count = null; try { String sql = "SELECT Convert(varchar,date,0) From tblComment WHERE ID = ?"; conn = DBConnection.getMyConnection(); pre = conn.prepareStatement(sql); pre.setString(1, id); rs = pre.executeQuery(); if (rs.next()) { count = rs.getString(1); } } catch (Exception e) { } finally { closeConnection(); } return count; } public String getCommentPostID(String id) throws Exception { String result = null; try { String sql = "SELECT postID From tblComment WHERE ID = ?"; conn = DBConnection.getMyConnection(); pre = conn.prepareStatement(sql); pre.setString(1, id); rs = pre.executeQuery(); if (rs.next()) { result = rs.getString(1); } } catch (Exception e) { } finally { closeConnection(); } return result; } public List<CommentDTO> getArticleComment(String id) throws Exception { List<CommentDTO> list = null; try { String sql = "SELECT ID, email, comment, Convert(varchar,date,0) FROM tblComment WHERE postID = ? AND status = 1 "; conn = DBConnection.getMyConnection(); pre = conn.prepareStatement(sql); pre.setString(1, id); rs = pre.executeQuery(); list = new ArrayList<CommentDTO>(); while (rs.next()) { String ID = rs.getString("ID"); String email = rs.getString("email"); String comment = rs.getString("comment"); String date = rs.getString(4); list.add(new CommentDTO(ID, email, comment, date)); } } catch (Exception e) { } finally { closeConnection(); } return list; } public boolean updateCommentStatus(String ID, String email) throws Exception { boolean result = false; try { String sql = "UPDATE tblComment SET status = 0 WHERE ID = ? AND email = ?"; conn = DBConnection.getMyConnection(); pre = conn.prepareStatement(sql); pre.setString(1, ID); pre.setString(2, email); result = pre.executeUpdate() > 0; } catch (Exception e) { } finally { closeConnection(); } return result; } public boolean insertComment(String id, String postID, String email, String comment) throws Exception { boolean result = false; try { String sql = "INSERT INTO tblComment(ID,postID,email,comment,date,status) VALUES(?,?,?,?,GETDATE(),1)"; conn = DBConnection.getMyConnection(); pre = conn.prepareStatement(sql); pre.setString(1, id); pre.setString(2, postID); pre.setString(3, email); pre.setString(4, comment); result = pre.executeUpdate() > 0; } catch (Exception e) { } finally { closeConnection(); } return result; } }
package kr.co.ecommerce.repository.jpa.interfaces; public interface AuthorityRepositoryCustom { }
package spring4.aopdemo; import org.springframework.stereotype.Service; /** * 使用注解的被拦截类 * @author yrz * */ @Service public class DemoAnnotionService { @Action(name="注解式拦截的add操作") public void add() {} }
package smart.lib.express; import java.util.ArrayList; import java.util.List; public class ProvincePrice { private final List<Long> provinces; // 首重价格 private long firstPrice; // 续重价格 private long additionalPrice; public ProvincePrice() { provinces = new ArrayList<>(); } public List<Long> getProvinces() { return provinces; } public long getAdditionalPrice() { return additionalPrice; } public void setAdditionalPrice(long additionalPrice) { this.additionalPrice = additionalPrice; } public long getFirstPrice() { return firstPrice; } public void setFirstPrice(long firstPrice) { this.firstPrice = firstPrice; } }
package ru.stoloto.protocol.lotos.requests; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.*; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import ru.stoloto.httptester.config.MysqlLocalConfig; import ru.stoloto.protocol.https.entities.DrawSaleTrans; import ru.stoloto.protocol.https.entities.DrawWinner; import ru.stoloto.protocol.https.repositores.DrawSaleTransRepository; import ru.stoloto.protocol.lotos.core.LotosGate; import ru.stoloto.protocol.utils.GateErrorCollector; import java.util.List; import java.util.concurrent.*; import java.util.stream.Collectors; import static java.util.concurrent.CompletableFuture.supplyAsync; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; /** * Created by iy.kapralov on 10.02.2016. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {AppConfigTest.class, MysqlLocalConfig.class}) public class WinInfoRequestTest { public static final String ANSI_RESET = "\u001B[0m"; public static final String ANSI_RED = "\u001B[31m"; public static final String ANSI_GREEN = "\u001B[32m"; protected final Log logger = LogFactory.getLog(getClass()); List<DrawSaleTrans> tickets; @Value("${terminalId}") private int terminalId; @Value("${playerInfo}") private String playerInfo; @Value("${terminal.login:#{null}}") private Long login; @Value("${terminal.password:#{null}}") private Long password; @Autowired private LotosGate lotosGate; @Autowired private DrawSaleTransRepository repository; @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Rule public GateErrorCollector collector = new GateErrorCollector(); @Before public void setUp() { tickets = repository.findAllUnchecked() .stream() //.limit(500) /*.filter(entity -> fastGames.stream() .map(gameType -> gameType.getCode()) .collect(Collectors.toList()).contains(entity.getGameId()) )*/ .collect(Collectors.toList()); } @After public void tearDown() { } //Нагрузка //@Ignore @Test public void multiThreadWinInfoTest() { final CountDownLatch latch = new CountDownLatch(tickets.size()); BlockingQueue<DrawSaleTrans> queue = new ArrayBlockingQueue<>(tickets.size()); ExecutorService service = Executors.newFixedThreadPool(100); queue.addAll(tickets); for (int i = 0; i < latch.getCount(); i++) { DrawSaleTrans ticket = queue.poll(); WinInfoRequest request = new WinInfoRequest(); request.setTerminalId(terminalId); request.setIdTicketType(1); request.setLogin(login); request.setPassword(password); request.setTicketId(ticket.getTicketId()); supplyAsync(() -> { try { return lotosGate.execute(request); } catch (Exception e) { collector.checkThat(e.getMessage(),e, nullValue()); return null; } },service) .thenAccept(response -> { latch.countDown(); DrawWinner entity = new DrawWinner(); entity.setTicketId(request.getTicketId()); entity.setDividend(response.getDividend()); entity.setGameId((ticket.getGameId())); switch (response.getRequestSign()){ case 0: entity.setWin(true); entity.setRequestSign(response.getRequestSign()); entity.setFullTicket(ticket); ticket.setDrawWinner(entity); repository.save(ticket); break; case 4465: entity.setWin(false); entity.setRequestSign(response.getRequestSign()); entity.setFullTicket(ticket); ticket.setDrawWinner(entity); repository.save(ticket); break; case 4472: case 4466: case 4499: logger.info(ANSI_RED + response.getRequestSign() + ANSI_RESET); break; default: collector.checkThat("UnUsual_sign -> "+ request.toString(),response.getRequestSign(), is(0)); break; } }); } try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException("Interrupted during execution", e); } } }
package com.pacific.domain; import java.util.Date; /** * Created by yadavm on 04/06/14. */ public class OptionChain extends StockDate { private Long optionChainId; private Date expirationDate; public Long getOptionChainId() {return optionChainId;} public void setOptionChainId(Long optionChainId) {this.optionChainId = optionChainId;} public Date getExpirationDate() {return expirationDate;} public void setExpirationDate(Date expirationDate) { this.expirationDate = expirationDate; } }
package com.tt.miniapp.msg.ad; import com.tt.miniapphost.host.HostDependManager; import com.tt.option.ad.c; import com.tt.option.e.e; public abstract class BannerAdCtrl extends BaseAdCtrl { public BannerAdCtrl(String paramString, int paramInt, e parame) { super(paramString, paramInt, parame); } protected String getEventType() { return "onBannerAdStateChange"; } protected boolean isSupportGameBannerAd() { return HostDependManager.getInst().isSupportAd(c.GAME_BANNER); } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\msg\ad\BannerAdCtrl.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package org.gmart.devtools.java.serdes.codeGenExample.openApiExample.generatedFiles; import javax.annotation.processing.Generated; import org.gmart.devtools.java.serdes.codeGen.javaGen.model.classTypes.AbstractClassDefinition; import org.gmart.devtools.java.serdes.codeGen.javaGen.model.classTypes.ClassInstance; import org.gmart.devtools.java.serdes.codeGen.javaGen.model.classTypes.ClassSerializationToYamlDefaultImpl; import org.gmart.devtools.java.serdes.codeGenExample.openApiExample.generatedFilesCustomizationStubs.SchemaOrRef; @Generated("") public class HttpMethodParameter implements ClassSerializationToYamlDefaultImpl, ClassInstance { private static AbstractClassDefinition classSpecification; private String name; private ParameterLocation in; private String description; private boolean required; private HttpMethodParameterStyle style; private boolean explode; private SchemaOrRef schema; public HttpMethodParameter() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public ParameterLocation getIn() { return in; } public void setIn(ParameterLocation in) { this.in = in; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean getRequired() { return required; } public void setRequired(boolean required) { this.required = required; } public HttpMethodParameterStyle getStyle() { return style; } public void setStyle(HttpMethodParameterStyle style) { this.style = style; } public boolean getExplode() { return explode; } public void setExplode(boolean explode) { this.explode = explode; } public SchemaOrRef getSchema() { return schema; } public void setSchema(SchemaOrRef schema) { this.schema = schema; } public AbstractClassDefinition getClassDefinition() { return classSpecification; } }
package com.tencent.mm.plugin.talkroom.component; import com.tencent.mm.sdk.platformtools.bd; class g$7 extends bd<e> { final /* synthetic */ c ovI; final /* synthetic */ g ovy; g$7(g gVar, c cVar) { this.ovy = gVar; this.ovI = cVar; super(3000, null, (byte) 0); } protected final /* synthetic */ Object run() { return new h(g.a(this.ovy), this.ovI); } }
package at.fhj.swd.data.impl; import java.util.List; import javax.inject.Inject; import javax.persistence.EntityManager; import at.fhj.swd.data.UserDAO; import at.fhj.swd.data.entity.User; import at.fhj.swd.data.exceptions.DataSourceLayerException; import javax.inject.Named; /** * DAO Implementation for User entity * * @author Jörg Huber * */ @Named public class UserDAOImpl implements UserDAO { @Inject public EntityManager em; @Override public User proveUserPassswordCombination(String username, String password) { User user = findByName(username); // check password, if user is not null if (user != null) { if (user.getPassword().equals(password)) { return user; } } return null; } @Override public void insert(User user) { em.persist(user); } @Override public User findByName(String username) { List<User> users = em .createQuery("from User user where user.username=:username", User.class).setParameter("username", username) .getResultList(); return getUserFromList(users); } @Override public User findById(long id) { List<User> users = em .createQuery("from User user where user.id=:id", User.class) .setParameter("id", id).getResultList(); return getUserFromList(users); } @Override public User findByToken(String token) { List<User> users = em .createQuery("from User user where user.token=:token", User.class).setParameter("token", token) .getResultList(); return getUserFromList(users); } private User getUserFromList(List<User> users) { if (users.size() == 1) { return users.get(0); } else if (users.size() == 0) { return null; } throw new DataSourceLayerException("inavlid database state in user table"); } @Override public User update(User user) { if (user != null) return em.merge(user); else return null; } }
package org.mlgb.dsps.analysis_plan; /** * Online parameter optimization. * @author Leo * */ public interface Optimizer { /** * Optimizing method. */ void optimizing(); }
package fiscal; public enum FiscalAcaoAutuacaoEnum { NAO_INFORMADO(0L), AUTUADO(1L); FiscalAcaoAutuacaoEnum(Long value) { this.value = value; } private Long value; public void setValue(Long value) { this.value = value; } public Long getValue() { return value; } }
package com.tpnote.pointet.controller; import com.tpnote.pointet.model.DarkSkyAPI.Currently; import com.tpnote.pointet.model.DarkSkyAPI.Weather; import com.tpnote.pointet.model.GeoAPI.GeoRequest; import com.tpnote.pointet.model.GeoAPI.Geometry; import com.tpnote.pointet.model.GeoAPI.Properties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import java.util.List; @Controller public class MeteoController { private GeoRequest geoRequest; private Weather weather; private String apiAddr = "https://api-adresse.data.gouv.fr/search/?q="; private String darkApiAddr = "https://api.darksky.net/forecast/032b61dc256584a9f1b4a105d7c755b0/"; @Autowired private RestTemplate restTemplate; @PostMapping("/meteo") public String postMeteo(@RequestParam("address") String search, Model model) { geoRequest = restTemplate.getForObject(apiAddr + search, GeoRequest.class); Properties properties = geoRequest.getFeatures().get(0).getProperties(); Geometry geometry = geoRequest.getFeatures().get(0).getGeometry(); model.addAttribute("search", search); model.addAttribute("label", properties.getLabel()); List<Double> coords = geometry.getCoordinates(); String darkAddr = darkApiAddr + coords.get(1) + "," + coords.get(0) + "?units=si&lang=fr"; weather = restTemplate.getForObject(darkAddr, Weather.class); Currently currently = weather.getCurrently(); model.addAttribute("humidity", currently.getHumidity() * 100); model.addAttribute("temperature", currently.getTemperature()); model.addAttribute("summary", currently.getSummary()); return "weather"; } }
package com.leetcode.oj; // 52 https://leetcode.com/problems/n-queens-ii/ public class NQuensII_52 { private int solve; public int totalNQueens(int n) { solve = 0; if (n == 0) { return solve; } boolean[] cols = new boolean[n]; boolean[] diagonal = new boolean[(n << 1) - 1]; boolean[] backDiagonal = new boolean[(n << 1) - 1]; dfs(n, 0, cols, diagonal, backDiagonal); return solve; } private void dfs(int n, int step, boolean[] cols, boolean[] diagonal, boolean[] backDiagonal) { if (step == n) { solve++; return; } for (int i = 0; i < n; i++) { if (cols[i] == false && diagonal[step - i + n - 1] == false && backDiagonal[step + i] == false) { cols[i] = true; diagonal[step - i + n - 1] = true; backDiagonal[step + i] = true; dfs(n, step + 1, cols, diagonal, backDiagonal); cols[i] = false; diagonal[step - i + n - 1] = false; backDiagonal[step + i] = false; } } } }