text
stringlengths
10
2.72M
package co.sblock.events.listeners.player; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World.Environment; import org.bukkit.block.Block; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerPortalEvent; import co.sblock.Sblock; import co.sblock.chat.Language; import co.sblock.events.listeners.SblockListener; import co.sblock.events.region.SblockTravelAgent; import co.sblock.micromodules.Protections; import co.sblock.micromodules.protectionhooks.ProtectionHook; /** * Listener for PlayerPortalEvents. * * @author Jikoo */ public class PortalListener extends SblockListener { private final Language lang; private final Protections protections; private final SblockTravelAgent agent; public PortalListener(Sblock plugin) { super(plugin); this.lang = plugin.getModule(Language.class); this.protections = plugin.getModule(Protections.class); this.agent = new SblockTravelAgent(); } /** * EventHandler for PlayerPortalEvents. * * @param event the PlayerPortalEvent */ @EventHandler(ignoreCancelled = true) public void onPlayerPortal(PlayerPortalEvent event) { if (!event.useTravelAgent()) { // Generally, end portals do not use travel agents, nether portals do. return; } Environment fromEnvironment = event.getFrom().getWorld().getEnvironment(); agent.reset(); Block fromPortal = agent.getAdjacentPortalBlock(event.getFrom().getBlock()); Location fromCenter = agent.findCenter(fromPortal); if (fromPortal == null) { if (fromEnvironment != Environment.THE_END && event.getTo().getWorld().getEnvironment() != Environment.THE_END) { event.setCancelled(true); } return; } if (fromEnvironment == Environment.THE_END) { if (fromCenter.getBlock().getType() == Material.PORTAL) { // No using nether portals in the End event.setCancelled(true); } // If we do another End implementation (Medium, etc.), it belongs here. return; } if (fromEnvironment == Environment.NETHER) { agent.setSearchRadius(8); } else { agent.setSearchRadius(1); } fromCenter.setPitch(event.getFrom().getPitch()); fromCenter.setYaw(event.getFrom().getYaw()); event.setPortalTravelAgent(agent); event.setFrom(fromCenter); agent.setFrom(fromCenter.getBlock()); Location to = agent.getTo(event.getFrom()); if (to == null) { event.setCancelled(true); return; } Location toPortal = agent.findPortal(to); if (toPortal == null) { for (ProtectionHook hook : protections.getHooks()) { if (!hook.canBuildAt(event.getPlayer(), to)) { event.setCancelled(true); event.getPlayer().sendMessage(lang.getValue("events.portal.protected")); return; } } } event.setTo(toPortal != null ? toPortal : to); } }
package com.proky.booking.persistence.dao; import com.proky.booking.persistence.entities.Invoice; public interface IInvoiceDao extends IDao<Invoice> { }
package com.jeeconf.kafka.sample; import com.jeeconf.kafka.sample.configs.RouteConfiguration; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.kafka.KafkaConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration; import org.springframework.context.annotation.Bean; @SpringBootApplication( exclude = {ProjectInfoAutoConfiguration.class} ) public class ProductionRouteContext { private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired RouteConfiguration configuration; @Bean public RouteBuilder productionRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from(configuration.helloTopicEndpoint()) .process(exchange -> { logger.info("------------------ BEGIN OF RECEIVED MESSAGE --------------"); logger.info("Hello " + exchange.getIn().getBody().toString() + "!"); logger.info("Message ID " + exchange.getIn().getHeader(KafkaConstants.KEY)); logger.info("------------------- END OF RECEIVED MESSAGE ---------------"); }) .end() .setId("productionRoute"); } }; } public static void main(String[] args) { SpringApplication.run(ProductionRouteContext.class, args); } }
package com.agharibi.hibernate.demo; import com.agharibi.hibernate.inheritance.Instructor; import com.agharibi.hibernate.Utils; import com.agharibi.hibernate.inheritance.Student; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; public class SingleTableInheritance { public static void main(String[] args) { SessionFactory sessionFactory = Utils.getSessionFactory(); Session session = sessionFactory.getCurrentSession(); Transaction transaction = session.getTransaction(); try { transaction.begin(); Student student = new Student("Paul", "Wall", "paul@gmail.com", "Hibernate"); Instructor instructor = new Instructor("John", "Doe", "john@gmail.com", 2000.00); session.save(student); session.save(instructor); transaction.commit(); System.err.println("All done!"); } finally { session.close(); sessionFactory.close(); } } }
package fr.utt.if26.memoria; import androidx.annotation.NonNull; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.PrimaryKey; @Entity(tableName = "times") public class TimeEntity { @PrimaryKey(autoGenerate = true) @NonNull @ColumnInfo(name = "id") private int id; @NonNull @ColumnInfo(name = "time") private int time; @NonNull @ColumnInfo(name = "cardsCount") private int cardsCount; public int getId() { return this.id; } public int getTime() { return this.time; } public int getCardsCount() { return this.cardsCount; } public void setId(int id0) { this.id = id0; } public void setTime(int time0) { this.time = time0; } public void setCardsCount(int cardsCount0) { this.cardsCount = cardsCount0; } }
package pe.cibertec.dao.mysql; import com.sun.javafx.scene.control.skin.LabeledImpl; import pe.cibertec.dao.interfaces.UsuarioDao; import pe.cibertec.excepciones.ExcepcionGeneral; import pe.cibertec.modelos.Usuario; import java.sql.*; import java.util.ArrayList; import java.util.List; public class MySqlUsuario implements UsuarioDao{ private final String INSERTAR = "INSERT INTO usuarios(idUsuario, usuario, clave, correo) VALUES(null, ?, md5(?), ?)"; private final String MODIFICAR = "UPDATE usuarios SET usuario =?, clave=md5(?), correo=? WHERE idUsuario = ? "; private final String ELIMINAR = "DELETE FROM usuarios WHERE idUsuario=?"; private final String OBTENER_POR_ID = "SELECT idUsuario, usuario, clave, correo FROM usuarios WHERE idUsuario=?"; private final String OBTENER = "SELECT idUsuario, usuario, clave, correo FROM usuarios"; private Connection conexion; private PreparedStatement sentencia; private ResultSet resultados; @Override public void insertar(Usuario usuario) { try { conexion = new MySqlConexion().conectar(); sentencia = conexion.prepareStatement(INSERTAR, Statement.RETURN_GENERATED_KEYS); sentencia.setString(1,usuario.getUsuario()); sentencia.setString(2,usuario.getClave()); sentencia.setString(3,usuario.getCorreo()); //executeUpdate = Insert, Update, Delete //executeQuery = Select // executeUpdate() --> Devuelve la cantidad de registros que fueron afectados. if(sentencia.executeUpdate() == 0){ throw new ExcepcionGeneral("No se insertó el registro"); } resultados = sentencia.getGeneratedKeys(); if(resultados.next()){ usuario.setIdUsuario(resultados.getInt(1)); } } catch (SQLException e) { throw new ExcepcionGeneral(e.getMessage()); }finally { cerrarConexiones(); } } @Override public void modificar(Usuario usuario) { try { conexion = new MySqlConexion().conectar(); sentencia = conexion.prepareStatement(MODIFICAR); sentencia.setString(1,usuario.getUsuario()); sentencia.setString(2,usuario.getClave()); sentencia.setString(3,usuario.getCorreo()); sentencia.setInt(4,usuario.getIdUsuario()); if(sentencia.executeUpdate()==0){ throw new ExcepcionGeneral("No se actualizó ningún registro"); } } catch (Exception e) { throw new ExcepcionGeneral(e.getMessage()); }finally { cerrarConexiones(); } } @Override public void eliminar(Usuario usuario) { try { conexion = new MySqlConexion().conectar(); sentencia = conexion.prepareStatement(ELIMINAR); sentencia.setInt(1,usuario.getIdUsuario()); if(sentencia.executeUpdate() == 0){ throw new ExcepcionGeneral("No se eliminó el registro"); } } catch (SQLException e) { throw new ExcepcionGeneral(e.getMessage()); }finally { cerrarConexiones(); } } @Override public Usuario obtenerPorId(Integer llave) { Usuario usuario = null; try { conexion = new MySqlConexion().conectar(); sentencia = conexion.prepareStatement(OBTENER_POR_ID); resultados = sentencia.executeQuery(); if(resultados.next()){ usuario = new Usuario(); usuario.setIdUsuario(resultados.getInt(1)); usuario.setUsuario(resultados.getString(2)); usuario.setClave(resultados.getString(3)); usuario.setCorreo(resultados.getString(4)); } } catch (SQLException e) { throw new ExcepcionGeneral("No se obtuvo al usuario"); }finally { cerrarConexiones(); } return usuario; } @Override public List<Usuario> listar() { List<Usuario> listado = new ArrayList<>(); try { conexion = new MySqlConexion().conectar(); sentencia = conexion.prepareStatement(OBTENER); resultados = sentencia.executeQuery(); while (resultados.next()){ Usuario usuario = new Usuario(); usuario.setIdUsuario(resultados.getInt(1)); usuario.setUsuario(resultados.getString(2)); usuario.setClave(resultados.getString(3)); usuario.setCorreo(resultados.getString(4)); listado.add(usuario); } } catch (SQLException e) { throw new ExcepcionGeneral(e.getMessage()); }finally { cerrarConexiones(); } return listado; } private void cerrarConexiones(){ try { if (resultados != null) resultados.close(); if (sentencia != null) sentencia.close(); if (conexion != null) conexion.close(); } catch (SQLException e) { e.printStackTrace(); } } }
/** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.regionserver; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.CellComparator; import org.apache.hadoop.hbase.classification.InterfaceAudience; /** * A mutable segment in memstore, specifically the active segment. */ @InterfaceAudience.Private public class MutableSegment extends Segment { protected MutableSegment(CellSet cellSet, CellComparator comparator, MemStoreLAB memStoreLAB, long size) { super(cellSet, comparator, memStoreLAB, size); } /** * Adds the given cell into the segment * @return the change in the heap size */ public long add(Cell cell) { return internalAdd(cell); } /** * Removes the given cell from the segment * @return the change in the heap size */ public long rollback(Cell cell) { Cell found = getCellSet().get(cell); if (found != null && found.getSequenceId() == cell.getSequenceId()) { long sz = AbstractMemStore.heapSizeChange(cell, true); getCellSet().remove(cell); incSize(-sz); return sz; } return 0; } //methods for test /** * Returns the first cell in the segment * @return the first cell in the segment */ Cell first() { return this.getCellSet().first(); } }
/* * Created on Mar 29, 2007 * */ package com.citibank.ods.modules.product.player.functionality.valueobject; /** * @author atilio.l.araujo * */ public class PlayerListFncVO extends BasePlayerListFncVO { }
package com.eegeo.mapapi.widgets; import com.eegeo.mapapi.geometry.LatLng; import java.util.List; class RoutingPolylineCreateParams { public List<LatLng> path; public boolean isForwardColor; public String indoorMapId; public int indoorFloorId; public List<Double> perPointElevations; public boolean isIndoor; RoutingPolylineCreateParams( List<LatLng> path, boolean isForwardColor, String indoorMapId, int indoorFloorId, List<Double> perPointElevations) { this.path = path; this.isForwardColor = isForwardColor; this.indoorMapId = indoorMapId; this.indoorFloorId = indoorFloorId; this.perPointElevations = perPointElevations; this.isIndoor = !indoorMapId.isEmpty(); } }
/** * */ /** * <!-- begin-UML-doc --> * <!-- end-UML-doc --> * @author sdownwar * @generated "UML to Java (com.ibm.xtools.transform.uml2.java5.internal.UML2JavaTransform)" */ import java.util.Date; public class ViewMarksControl { /** * <!-- begin-UML-doc --> * <!-- end-UML-doc --> * @generated "UML to Java (com.ibm.xtools.transform.uml2.java5.internal.UML2JavaTransform)" */ private DataManager dataManager; public ViewMarksControl(DataManager dm) { dataManager = dm; } public AssignmentSubmission[] getAssSubs() { return dataManager.getAssSubs(); } /** * <!-- begin-UML-doc --> * <!-- end-UML-doc --> * @generated "UML to Java (com.ibm.xtools.transform.uml2.java5.internal.UML2JavaTransform)" */ public void markFeedbackRead() { // begin-user-code // TODO Auto-generated method stub // end-user-code } }
package uk.co.liammartin.cs2001_task1; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void goToSecondScreen(View view) { Intent getSecondScreenIntent = new Intent(this, SecondScreen.class); EditText name = (EditText)findViewById(R.id.name_box); final int result = 1; getSecondScreenIntent.putExtra("callingActivity", this.getClass().getSimpleName()); getSecondScreenIntent.putExtra("Name", name.getText().toString()); startActivityForResult(getSecondScreenIntent, result); } }
package com.sshfortress.common.enums; import org.apache.commons.lang.StringUtils; /** <p class="detail"> * 功能:这里写类描述 * </p> * @ClassName: RegCodeType * @version V1.0 */ public enum RegCodeType { REGIST("REGIST", "注册"), BACK_PASSWORD("BACK_PASSWORD", "找回密码"), BIND_PHONE("BIND_PHONE", "绑定手机号"), BIND_EMAIL("BIND_EMAIL", "绑定email"), FAST_LOGIN("FAST_LOGIN","快捷登录"), MODIFY_PHONE("MODIFY_PHONE","修改手机号"); private String code; private String detail; RegCodeType(String code, String detail) { this.code = code; this.detail = detail; } /** * 获得枚举 * * @param code * @return */ public static RegCodeType getEnumByCode(String code) { for (RegCodeType activitie : RegCodeType.values()) { if (StringUtils.equals(code, activitie.getCode())) { return activitie; } } return null; } /** * @return code */ public String getCode() { return code; } /** * @param code */ public void setCode(String code) { this.code = code; } /** * @return the detail */ public String getDetail() { return detail; } /** * @param detail * the detail to set */ public void setDetail(String detail) { this.detail = detail; } }
package com.example.todo.note; import com.example.todo.user.UserEntity; import javax.persistence.*; @Entity(name="Note") public class NoteEntity { @Id @GeneratedValue private int id; private String note; private String color; @ManyToOne @JoinColumn private UserEntity user; public NoteEntity() { } public NoteEntity(String note, String color, UserEntity user) { this.note = note; this.color = color; this.user = user; } public NoteEntity(Integer id, String note, String color, UserEntity user) { this.id = id; this.note = note; this.color = color; this.user = user; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public UserEntity getUser() { return user; } public void setUser(UserEntity user) { this.user = user; } }
package com.paragon.utils.anim; /** * Created by Rupesh Saxena */ public interface SpringListener { /* * hits when Spring is Active * */ void onSpringStart(); /* * hits when Spring is inActive * */ void onSpringStop(); }
package com.capgemini.greatoutdoors.ui; import java.util.Scanner; import com.capgemini.greatoutdoors.dto.Address; import com.capgemini.greatoutdoors.dto.PlaceAnOrder; import com.capgemini.greatoutdoors.exception.InputMisMatchException; import com.capgemini.greatoutdoors.service.AddressService; import com.capgemini.greatoutdoors.service.AddressServiceImpl; import com.capgemini.greatoutdoors.service.PlaceOrderServiceImpl; import com.capgemini.greatoutdoors.util.AddressRepository; import com.capgemini.greatoutdoors.util.PlaceOrderRepository; public class UserInterface { public static void main(String[] args) { new AddressRepository(); new PlaceOrderRepository(); AddressService addressService=new AddressServiceImpl(); System.out.println("choose"+"\n"+"1: view a address "+"\n"+"2: add a address "+"\n"+"3 update address"+"\n"+"4 : delete a address" + "\n"+"5 : place a order"); String choose ; Scanner scan = new Scanner(System.in); choose = scan.next(); switch(choose) { case "1": System.out.println("enter addressId"); String addressId; Scanner viewScan = new Scanner(System.in); addressId = viewScan.next(); try { Address result=addressService.viewAllAddress(addressId); System.out.println("Address for given address ID : "); System.out.println(result.getAddressId()+" "+result.getBuildingNo()+" "+result.getCity()+" "+result.getState()); } catch(InputMisMatchException e) { System.out.println(e.getMessage()); } //System.out.println(obj.viewAllAddress(addressId)); break; case "2": String addressId1; Scanner AddressScan = new Scanner(System.in); System.out.println("enter address id"); addressId1 = AddressScan.next(); System.out.println("enter retailer id"); String retailer = AddressScan.next(); System.out.println("enter your building No"); String building = AddressScan.next(); System.out.println("enter your city"); String city = AddressScan.next(); System.out.println("enter your state"); String state = AddressScan.next(); System.out.println("enter your feild"); String feild = AddressScan.next(); System.out.println("enter zip code"); String zip = AddressScan.next(); Address address1 = new Address(); address1.setAddressId(addressId1); address1.setBuildingNo(building); address1.setCity(city); address1.setFeild(feild); address1.setRetailerId(retailer); address1.setState(state); address1.setZip(zip); try { boolean addAddress = addressService.addAddress(address1); if(addAddress) { System.out.println("Address Added Successfully"); } } catch(InputMisMatchException e) { System.out.println(e.getMessage()); } break; case "3": System.out.println("enter an addressId to update"); Scanner updateScan = new Scanner(System.in); String choice; choice = updateScan.next(); String updateaddressId; System.out.println("enter update address id"); updateaddressId = updateScan.next(); System.out.println("enter update retailer id"); String updateretailer = updateScan.next(); System.out.println("enter your update building No"); String updatebuilding = updateScan.next(); System.out.println("enter update city"); String updatecity = updateScan.next(); System.out.println("enter your state"); String updatestate = updateScan.next(); System.out.println("enter update feild"); String updatefeild = updateScan.next(); System.out.println("enter update code"); String updatezip = updateScan.next(); Address address = new Address(); address.setAddressId(updateaddressId); address.setBuildingNo(updatebuilding); address.setCity(updatecity); address.setFeild(updatefeild); address.setRetailerId(updateretailer); address.setState(updatestate); address.setZip(updatezip); try { boolean result = addressService.updateAddress(address,choice); if(result) { System.out.println("data updated successfully"); } } catch (InputMisMatchException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } break; case "4": System.out.println("enter an address id to delete"); Scanner deleteScan = new Scanner(System.in); String delete = deleteScan.next(); try { boolean deleteAddress = addressService.deleteAddress(delete); if(deleteAddress) { System.out.println("Address Deleted Successfully"); } } catch (InputMisMatchException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; case "5": System.out.println("enter addressId"); String checkAddressId; Scanner checkScan = new Scanner(System.in); checkAddressId = checkScan.next(); PlaceOrderServiceImpl impl = new PlaceOrderServiceImpl(); try { PlaceAnOrder output = impl.placeOrderPrice(checkAddressId); System.out.println("order placed Successfully : "); System.out.println("AddressId: "+output.getAddressId()+"\n"+"price : "+output.getPrice()+" \n"+"ProductId: "+output.getProductId()+" \n"+"UserId: "+output.getUserId()); } catch (InputMisMatchException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; default: System.out.println("choose correct Number"); } } }
package Helpers; import javax.swing.*; import java.util.concurrent.ThreadLocalRandom; /** * La classe Presenter estente ogni file del package Presenter e contiene dei metodi comuni a tutti i file */ public class Presenter { public Presenter() { } /** * Il metodo è responsabile della visibilità del menu laterale di accesso alle varie sezioni di Health Me! * @param menuPanel Pannello del menu laterale */ public void MenuVisibility(JPanel menuPanel){ if (menuPanel.isVisible()) { menuPanel.setVisible(false); } else menuPanel.setVisible(true); } /** * Il metodo è responsabile della visibilità del sotto menu laterale delle sezioni di Alimentazione e Allenamento * @param subPanel Sotto Pannelli della sezione */ public void SubMenuVisibility(JPanel subPanel){ if (subPanel.isVisible()) { subPanel.setVisible(false); } else subPanel.setVisible(true); } /** * Il metodo verifica se la stringa presa come parametro rispetta la regola definita * @param elemento Stringa di cui si vuole verificare la validità * @return true se rispetta la regola, false se non la rispetta */ public boolean checkIntero(String elemento){ boolean ritorno = false; String regola = "[0-9]*"; if (elemento.matches(regola) && elemento.length()>0) ritorno=true; return ritorno; } /** * Il metodo estrae un numero casuale tra 0 e un numero preso come parametro * @param size Limite massimo da cui estrapolare il numero casuale * @return Un numero casuale tra 0 e size */ protected int randomize(int size){ return ThreadLocalRandom.current().nextInt(0, size); } }
package com.cn.ouyjs.thread.lock.productAndCustomer; import java.math.BigDecimal; /** * @author ouyjs * @date 2019/8/9 10:48 */ public class Test { public static void main(String[] args) { Warehouse warehouse = new Warehouse(10); /*Producer producer = new Producer(warehouse); producer.addGoods(goods);*/ for (int i=0; i< 3; i++){ Goods goods = new Goods(); goods.setName("苹果"+i); goods.setNumber(1); goods.setPrice(new BigDecimal(1)); new Thread(new ProducerThread(warehouse, goods)).start(); } new Thread(new CustomerThread(warehouse)).start(); } }
class Project { String name; Date startDate; Date endDate; String role; int res; String[] respon; Project(String n,Date sd,Date ed,String ro,int re,String[] rep) { name=n; startDate=sd; endDate=ed; role=ro; res=re; respon=new String[res]; for(int i=0;i<res;i++) { respon[i]=rep[i]; } } Project(String a,Date b,Date c,String d) { name=a; startDate=b; endDate=c; role=d; } Project() { name=null; startDate=new Date(); endDate=new Date(); role=null; respon=null; res=0; } void display() { System.out.println(name); startDate.display(); endDate.display(); System.out.println("\nRole: "+role); if(res>=1) { System.out.println("Respon: "); for(int i=0;i<res;i++) { System.out.println((i+1)+" "+respon[i]); } } } }
package com.em.service; import java.io.Serializable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.em.dao.DepartmentDaoInterface; import com.em.dto.DepartmentDto; @Service public class DepartmentServiceImpl implements DepartmentServiceInterface{ @Autowired DepartmentDaoInterface dao; public Serializable saveDeptInDb(DepartmentDto dept) { return dao.saveDeptInDb(dept); } }
public class MaxProductionSubArray { public int maxProduct(int[] nums) { int length = nums.length; double[] maxPositive = new double[length]; double[] maxNegative = new double[length]; maxPositive[0] = maxNegative[0] = nums[0]; double max = nums[0]; for (int index = 1; index < length; ++index) { maxPositive[index] = Math.max(Math.max( maxNegative[index - 1] * nums[index], maxPositive[index - 1] * nums[index]), nums[index]); maxNegative[index] = Math.min(Math.min( maxNegative[index - 1] * nums[index], maxPositive[index - 1] * nums[index]), nums[index]); if (maxPositive[index] > max) max = maxPositive[index]; } return (int) max; } public static void main(String[] args) { System.out.println(new MaxProductionSubArray().maxProduct(new int[]{2, 3, -2, 4})); } }
/** * URL: https://www.hackerrank.com/challenges/ctci-merge-sort/problem */ package hackerrank.sorting; import java.io.IOException; import java.util.Scanner; public class CountingInversions { static long cntInv; // Complete the countInversions function below. static long countInversions(int[] arr) { cntInv = 0L; partition(arr, 0, arr.length-1); return cntInv; } static void partition(int []arr, int low, int high){ if(low<high){ int mid = (low+high)/2; partition(arr, low, mid); partition(arr, mid+1, high); mergeSort(arr, low, mid, high); } } static void mergeSort(int[] arr, int low, int mid, int high){ int n1 = mid - low + 1; int n2 = high - mid; int L[] = new int[n1]; int R[] = new int[n2]; for(int i=0;i<n1;i++){ L[i] = arr[low+i]; } for(int i=0;i<n2;i++){ R[i] = arr[mid+i+1]; } int i = 0, j= 0; int k = low; while(i<n1 && j<n2){ if(L[i]<= R[j]){ arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; cntInv += (mid + 1) - (low + i); } k++; } while (i<n1){ arr[k] = L[i]; i++; k++; } while (j<n2){ arr[k] = R[j]; k++; j++; } } private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) throws IOException { int t = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int tItr = 0; tItr < t; tItr++) { int n = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); int[] arr = new int[n]; String[] arrItems = scanner.nextLine().split(" "); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int i = 0; i < n; i++) { int arrItem = Integer.parseInt(arrItems[i]); arr[i] = arrItem; } long result = countInversions(arr); System.out.println("Result:"+result); } scanner.close(); } }
package org.squonk.core.camel; import org.apache.camel.component.servletlistener.CamelContextLifecycle; import org.apache.camel.component.servletlistener.ServletCamelContext; import org.apache.camel.impl.SimpleRegistry; /** * * @author timbo */ public class ServletCamelLifeCycle implements CamelContextLifecycle<SimpleRegistry> { private final CamelLifeCycle worker = new CamelLifeCycle(); @Override public void beforeStart(ServletCamelContext scc, SimpleRegistry r) throws Exception { worker.beforeStart(scc, r); } @Override public void afterStart(ServletCamelContext scc, SimpleRegistry r) throws Exception { worker.afterStart(scc, r); } @Override public void beforeStop(ServletCamelContext scc, SimpleRegistry r) throws Exception { worker.beforeStop(scc, r); } @Override public void afterStop(ServletCamelContext scc, SimpleRegistry r) throws Exception { worker.afterStop(scc, r); } @Override public void beforeAddRoutes(ServletCamelContext scc, SimpleRegistry r) throws Exception { worker.beforeAddRoutes(scc, r); } @Override public void afterAddRoutes(ServletCamelContext scc, SimpleRegistry r) throws Exception { worker.afterAddRoutes(scc, r); } }
package com.siokagami.application.mytomato.utils; import android.databinding.BindingConversion; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateParseUtil { public static final long minute = 1000 * 60; public static final long hour = minute * 60; public static final long day = hour * 24; public static final long month = day * 30; public static final long year = month * 12; private static final String DAY_DESC = "天"; private static final String HOUR_DESC = "时"; private static final String MINUTE_DESC = "分"; private static final String SECOUND_DESC = "秒"; public static final String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"}; public static final String[] weekDaysForShort = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"}; public static final String[] weekDaysAbb = {"日", "一", "二", "三", "四", "五", "六"}; public static final String[] monthAbb = {"Jan.", "Feb.", "Mar.", "Apr.", "May.", "Jun.", "Jul.", "Aug.", "Sep.", "Oct.", "Nov.", "Dec."}; public static final String[] monthWords = {"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十月", "十二月",}; private final static int[] dayArr = new int[]{20, 19, 21, 20, 21, 22, 23, 23, 23, 24, 23, 22}; private final static String[] constellationArr = new String[]{"摩羯座", "水瓶座", "双鱼座", "白羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座", "摩羯座"}; public static String parse2mean(Date date) { return parse2mean(date, "yyyy-MM-dd"); } public static String parseCourseTime(Date date) { Calendar nowCalender = Calendar.getInstance(); Calendar startTime = Calendar.getInstance(); startTime.setTime(date); long now = System.currentTimeMillis(); long diffValue = date.getTime() - now; StringBuilder result = new StringBuilder(); if (diffValue > 0) { if (startTime.get(Calendar.YEAR) != nowCalender.get(Calendar.YEAR)) { return dateFormate(date, "yyyy-MM-dd HH:mm"); } else if (startTime.get(Calendar.DAY_OF_MONTH) == nowCalender.get(Calendar.DAY_OF_MONTH)) { result.append("今天 "); } else if (startTime.get(Calendar.DAY_OF_MONTH) - nowCalender.get(Calendar.DAY_OF_MONTH) == 1) { result.append("明天 "); } else { result.append(dateFormate(date, "yyyy-MM-dd ")); } result.append(dateFormate(date, "HH:mm")); return result.toString(); } else { return parse2mean(date, "yyyy-MM-dd HH:mm"); } } public static String parse2mean(Date date, String dateFormat) { if (date == null) { return ""; } String result = "刚刚"; long now = System.currentTimeMillis(); long diffValue = now - date.getTime(); long yearC = diffValue / year; long monthC = diffValue / month; long weekC = diffValue / (7 * day); long dayC = diffValue / day; long hourC = diffValue / hour; long minC = diffValue / minute; if (yearC < 1 && dayC > 2) { result = dateFormate(date, "MM-dd"); } else if (dayC > 2) { result = dateFormate(date, "yyyy-MM-dd"); } else if (dayC >= 1 && dayC <= 2) { result = dayC + "天前"; } else if (hourC >= 1) { result = hourC + "小时前"; } else if (minC >= 1) { result = minC + "分钟前"; } // if (monthC >= 1) { // result = monthC + "个月前"; // } else if (weekC >= 1) { // result = weekC + "周前"; // } return result; } /** * time的单位是秒 * * @param time * @return */ public static String parse60(long time) { long hour = time / 3600; long min = (time - hour * 3600) / 60; long second = time - hour * 3600 - min * 60; StringBuilder result = new StringBuilder(); if (hour > 0) { if (hour >= 10) result.append(hour); else result.append("0" + hour); result.append(":"); } if (min < 10) result.append("0" + min); else result.append(min); result.append(":"); if (second < 10) result.append("0" + second); else result.append(second); return result.toString(); } public static String dateFormate(Date date) { if (date == null) { return StringUtils.EMPTY; } java.text.DateFormat formate = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return formate.format(date); } public static String dateFormateYmdHm(Date date) { if (date == null) { return StringUtils.EMPTY; } java.text.DateFormat formate = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm"); return formate.format(date); } public static String dateFormateYmdHm2(Date date) { if (date == null) { return StringUtils.EMPTY; } java.text.DateFormat formate = new java.text.SimpleDateFormat("yyyy年MM月dd日 HH:mm"); return formate.format(date); } public static String dateFormatYmdHm(Date date) { if (date == null) { return StringUtils.EMPTY; } java.text.DateFormat formate = new java.text.SimpleDateFormat("yyyy.MM.dd HH:mm"); return formate.format(date); } public static String dateFormatStringmd(Date date) { if (date == null) { return StringUtils.EMPTY; } java.text.DateFormat formate = new java.text.SimpleDateFormat("MM月dd日"); return formate.format(date); } public static String dateFormatStringYmd(Date date) { if (date == null) { return StringUtils.EMPTY; } java.text.DateFormat formate = new java.text.SimpleDateFormat("yyyy年MM月dd日"); return formate.format(date); } public static String dateFormatMdHm(Date date) { if (date == null) { return StringUtils.EMPTY; } java.text.DateFormat formate = new java.text.SimpleDateFormat("MM-dd HH:mm"); return formate.format(date); } public static String dateFormatHm(Date date) { if (date == null) { return StringUtils.EMPTY; } java.text.DateFormat formate = new java.text.SimpleDateFormat("HH:mm"); return formate.format(date); } public static String dateFormatStringMdHm(Date date) { if (date == null) { return StringUtils.EMPTY; } java.text.DateFormat formate = new java.text.SimpleDateFormat("MM月dd日 HH:mm"); return formate.format(date); } public static String dateFormate(Date date, String format) { if (date == null) { return StringUtils.EMPTY; } java.text.DateFormat formate = new java.text.SimpleDateFormat(format); return formate.format(date); } public static Date stringToDate(String date, String format) { SimpleDateFormat sdf = new SimpleDateFormat(format); try { return sdf.parse(date); } catch (ParseException e) { return null; } } public static String stringToDateString(String date, String oldFormat, String currentFormat) { Date dateTime = stringToDate(date, oldFormat); if (dateTime != null) { return dateFormate(dateTime, currentFormat); } else { return StringUtils.EMPTY; } } public static String dateFormatTransform(String data, String inputFormat, String outputForamt) { Date date = stringToDate(data, inputFormat); return dateFormate(date, outputForamt); } /* **将 ms 秒转换为 * 天时分 或 * 时分秒 */ public static String millSecFormat(long millSec) { if ((millSec / day) < 1) { return millSec2HourMinSec(millSec); } else { return millSec2DayHourMin(millSec); } } /* *将 ms转换为 hh:mm:ss 或者 dd:hh:mm 格式 */ public static String millis2DDHHMMSS(long sec) { if ((sec / day) < 1) { return sec2HHMMSS(sec); } else { return sec2DDHHMMSS(sec); } } /** * 将 毫秒 转为 天时分 * * @param millSecond * @return */ public static String millSec2DayHourMin(long millSecond) { StringBuilder builder = new StringBuilder(); long dd = millSecond / day; long hr = (millSecond - dd * day) / hour; long min = (millSecond - dd * day - hr * hour) / minute; return builder.append(numFormatDate(dd)).append(DAY_DESC).append(numFormatDate(hr)).append(HOUR_DESC) .append(numFormatDate(min)).append(MINUTE_DESC).toString(); } /** * 将毫秒转化为DD:HH:MM:SS */ public static String sec2DDHHMMSS(long sec) { StringBuilder builder = new StringBuilder(); long dd = sec / day; long hr = (sec - dd * day) / hour; long min = (sec - dd * day - hr * hour) / minute; long second = (sec - dd * day - hr * hour - min * minute) / 1000; return builder.append(numFormatDate(dd)).append(":").append(numFormatDate(hr)).append(":") .append(numFormatDate(min)).append(":").append(numFormatDate(second)).toString(); } /** * 将毫秒转为 时分秒 * * @param millSecond * @return */ public static String millSec2HourMinSec(long millSecond) { StringBuilder builder = new StringBuilder(); long hr = millSecond / hour; long min = (millSecond - hr * hour) / minute; long second = (millSecond - hr * hour - min * minute) / 1000; return builder.append(numFormatDate(hr)).append(HOUR_DESC).append(numFormatDate(min)).append(MINUTE_DESC) .append(numFormatDate(second)).append(SECOUND_DESC).toString(); } public static String millSec2HourMin(long millSecond) { StringBuilder builder = new StringBuilder(); long hr = millSecond / hour; long min = (millSecond - hr * hour) / minute; long second = (millSecond - hr * hour - min * minute) / 1000; return builder.append(numFormatDate(hr)).append(HOUR_DESC).append(numFormatDate(min)).append(MINUTE_DESC) .append(numFormatDate(second)).append(SECOUND_DESC).toString(); } public static String millSec2Min(long millSecond) { StringBuilder builder = new StringBuilder(); long min = millSecond / minute; return builder.append(numFormatDate(min)).append(MINUTE_DESC) .toString(); } /** * 将毫秒转换为 hh:mm:ss -> 是毫秒!!!! */ public static String sec2HHMMSS(long sec) { StringBuilder builder = new StringBuilder(); long hr = sec / hour; long min = (sec - hr * hour) / minute; long second = (sec - hr * hour - min * minute) / 1000; return builder.append(numFormatDate(hr)).append(":").append(numFormatDate(min)).append(":") .append(numFormatDate(second)).toString(); } /** * 数字转换为 00 * * @param num * @return */ private static String numFormatDate(long num) { if (num / 10 > 0) { return String.valueOf(num); } else { return "0" + num; } } /** * 毫秒转换成分钟:秒 */ public static String millSec2MinSec(long millSecond) { StringBuilder builder = new StringBuilder(); long min = millSecond / minute; long second = millSecond % minute / 1000; String minStr = min > 9 ? String.valueOf(min) : "0" + min; String secStr = second > 9 ? String.valueOf(second) : "0" + second; return builder.append(minStr).append(":").append(secStr).toString(); } public static Date time2Date(long millSeconds) { Date date = new Date(); date.setTime(millSeconds); return date; } /** * 根据用户生日计算年龄 */ public static String getAgeByBirthday(String strBirth, boolean needConstellation) { if (StringUtils.isEmpty(strBirth)) return ""; Date birthday = null; try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); birthday = sdf.parse(strBirth); Calendar cal = Calendar.getInstance(); if (cal.before(birthday)) { throw new IllegalArgumentException( "The birthDay is before Now.It's unbelievable!"); } int yearNow = cal.get(Calendar.YEAR); int monthNow = cal.get(Calendar.MONTH) + 1; int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); cal.setTime(birthday); int yearBirth = cal.get(Calendar.YEAR); int monthBirth = cal.get(Calendar.MONTH) + 1; int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH); int age = yearNow - yearBirth; if (monthNow <= monthBirth) { if (monthNow == monthBirth) { // monthNow==monthBirth if (dayOfMonthNow < dayOfMonthBirth) { age--; } } else { // monthNow>monthBirth age--; } } if (needConstellation) { return age + "岁," + getConstellation(monthBirth, dayOfMonthBirth); } else { return age + "岁"; } } catch (ParseException e) { System.out.println(e.getMessage()); } return ""; } //星座 public static String getConstellation(int month, int day) { return day < dayArr[month - 1] ? constellationArr[month - 1] : constellationArr[month]; } //判断是这个月的几号,不是这个月就屏蔽 public static int getDayOfCurrentMonthFromDate(Date date) { Calendar calendar = Calendar.getInstance(); int month = Calendar.getInstance().get(Calendar.MONTH); calendar.setTime(date); if (calendar.get(Calendar.MONTH) == month) return calendar.get(Calendar.DAY_OF_MONTH); return 0; } public static boolean isToday(Date date) { Calendar calendar = Calendar.getInstance(); int day = calendar.get(Calendar.DAY_OF_MONTH); calendar.setTime(date); return calendar.get(Calendar.DAY_OF_MONTH) == day; } public static boolean isSameDay(Date oneDay, Date otherDay) { if (oneDay == null || otherDay == null) { return false; } return dateFormate(oneDay, "yyyy-MM-dd").equals(dateFormate(otherDay, "yyyy-MM-dd")); } public static boolean beforeToday(Date date) { return compareDateByDay(date, Calendar.getInstance().getTime()) < 0; } public static int compareDateByDay(Date oneDate, Date twoDate) { return dateFormate(oneDate, "yyyy-MM-dd").compareTo(dateFormate(twoDate, "yyyy-MM-dd")); } public static int getTheDayOfMonth(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.DAY_OF_MONTH); } }
package com.twu.biblioteca; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.PrintStream; import static org.junit.Assert.assertEquals; // Integration tests public class BibliotecaAppTest { public void mockInput(String inputData) { InputStream in = new ByteArrayInputStream(inputData.getBytes()); System.setIn(in); } ByteArrayOutputStream outContent; void captureOutput() { outContent = new ByteArrayOutputStream(); System.setOut(new PrintStream(outContent)); } @Test public void userCanSeeAllBooksAvailable() { mockInput("1\n0\n"); captureOutput(); BibliotecaApp app = new BibliotecaApp(); app.run(); assertEquals("Welcome to Biblioteca! Your one-stop-shop for great book titles in Bangalore! \n" + "\n" + "0. Exit Biblioteca \n" + "1. Display list of books: \n" + "2. Checkout a book \n" + "3. Return a book\n" + "4. Display list of movies\n" + "The Count of MonteCristo|Alexandre Dumas|1800\n\n" + "The God Delusion|Richard Dawkins|1980\n\n" + "Sapians|Yuval Herari|2011\n\n", outContent.toString()); } @Test public void userCanCheckoutAndReturnABook(){ mockInput("2\nSapians\n3\nSapians\n0\n"); captureOutput(); BibliotecaApp app = new BibliotecaApp(); app.run(); assertEquals("Welcome to Biblioteca! Your one-stop-shop for great book titles in Bangalore! \n" + "\n" + "0. Exit Biblioteca \n" + "1. Display list of books: \n" + "2. Checkout a book \n" + "3. Return a book\n" + "4. Display list of movies\n" + "Enter the title of the book\n" + "you have checked out Sapians\n" + "Thank you, enjoy the book!\n" + "Enter the title of the book\n" + "Thank you, you have returned Sapians\n", outContent.toString()); } }
package com.kess.redesnowapi.cmds; import com.kess.redesnowapi.others.Static; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class Fly implements CommandExecutor { @Override public boolean onCommand(CommandSender sd, Command cmd, String lb, String[] args) { if (cmd.getName().equalsIgnoreCase("fly")) { if (!(sd instanceof Player)) { Bukkit.getConsoleSender().sendMessage(Static.prefix + "§cO console não pode executar este comando."); return true; } Player p = (Player) sd; if (!p.hasPermission(ClasseMain.pl.getConfig().getString("permission-fly"))) { p.sendMessage(ClasseMain.pl.getConfig().getString("no-permission-fly") .replaceAll("&", "§") .replace("{prefix}", Static.prefix)); return true; } if (args.length == 0) { if (p.getAllowFlight() == true) { p.setAllowFlight(false); p.sendMessage(ClasseMain.pl.getConfig().getString("fly") .replaceAll("&", "§") .replace("{modo}", "Desligado") .replace("{prefix}", Static.prefix)); } else { p.setAllowFlight(true); p.sendMessage(ClasseMain.pl.getConfig().getString("fly") .replaceAll("&", "§") .replace("{modo}", "Ligado") .replace("{prefix}", Static.prefix)); } } } return false; } }
package filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import metier.entities.Utilisateur; @WebFilter(urlPatterns = {"/Liste_Etablissements_Drs", "/Liste_Besoins_Drs", "/Liste_Dons_Drs", "/Liste_Intermediaire_Drs", "/Liste_Donnateurs_Drs", "/Liste_Fournisseurs_Drs", "/Liste_categories_Drs", "/Liste_produits_Drs", "/BesoinDrs", "/ajoutBesoinDrs"}) public class DrsFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; HttpSession session = request.getSession(false); String loginURI = request.getContextPath() + "/"; boolean loggedIn = session != null && session.getAttribute("user") != null; Utilisateur user; if (loggedIn) { user = (Utilisateur) session.getAttribute("user"); System.out.println("**************************** before responsable ******************************************"); if(user.getRole().equals("responsable") && user.getAccepted().equals(true) && user.getEtablissement().getDrs()) { System.out.println("**************************** responsable drs ******************************************"); System.out.println(session.getAttribute("user")); chain.doFilter(request, response); } } else { System.out.println("**************************** No user ******************************************"); response.sendRedirect(loginURI); } } }
package elder.osm; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.w3c.dom.Element; /** * * Manages a collection of Open Street Map elements * * @param Type * of element managed by this library */ public abstract class OSMLibrary<T extends OSMElement> { private final String tag; private final Map<Long, T> library = new HashMap<Long, T>(); private final Map<Long, T> missing = new HashMap<Long, T>(); /** * * @param tag * XML tag corresponding to elements managed in this library */ OSMLibrary(String tag) { this.tag = tag; } /** * * Check if this XML element contains information that can be used to set * the attributes an object tracked by this library. The attributes of the * object are set if so. * * @param element * @param reader * @return */ public boolean check(Element element, OSMReader reader) { if (element.getTagName().equals(getTag())) { long id = Long.parseLong(element.getAttribute("id")); T t = getMissing(id); if (t != null) { t.init(element, reader); missing.remove(id); return true; } } return false; } public abstract T create(long id); /** * Gets object representing open street map element with the given ID. * * Creates an object if one doesn't already exists. Object attributes are * not set. * * @param id * Open street map ID * */ public T get(Long id) { T out = library.get(id); if (out == null) { out = create(id); library.put(id, out); missing.put(id, out); } return out; } T getMissing(Long id) { return missing.get(id); } String getTag() { return tag; } /** * * @return All object managed by this library. */ public Collection<T> getValues() { return library.values(); } /** * * @return How many objects are tracked by this library */ int howMany() { return library.size(); } /** * * @return How many objects tracked by this library have not had their * attributes set */ int howManyMissing() { return missing.size(); } }
package com.controller; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.entity.Book; import com.service.BookService; import com.service.DeliveryService; import com.service.DemandeService; import com.service.UserService; @Controller @RequestMapping("/book") public class BookController { @Resource private UserService userService; @Resource private BookService bookService; @Resource private DemandeService demandeService; @Resource private DeliveryService deliveryService; @ResponseBody @RequestMapping("books") public Map<String, Object> books() { Map<String, Object> result=new HashMap<String,Object>(); if(bookService.listBooks().size()==0) { result.put("status", "0"); result.put("errorMsg","no books"); } else { List<Book> books=bookService.listBooks(); result.put("status", "1"); result.put("data",books); System.out.println(books.size()+"success"); } return result; } @ResponseBody @RequestMapping("booksOnSale") public Map<String, Object> booksOnSale() { Map<String, Object> result=new HashMap<String,Object>(); if(bookService.listBooksOnSale().size()==0) { result.put("status", "0"); result.put("errorMsg","no books"); } else { List<Book> books=bookService.listBooksOnSale(); result.put("status", "1"); result.put("data",books); System.out.println(books.size()+"success"); } return result; } @ResponseBody @RequestMapping(value="booksId",method = RequestMethod.GET) public List<String> getBooksId() { List<String> ids=new ArrayList<>(); List<Book> books=bookService.listBooks(); for(Book book:books) { ids.add(book.getBookId()); } return ids; } @ResponseBody @RequestMapping("readBookName") public String readBookName(@RequestParam (value="bookId") String bookId) { if(bookService.selectBooks(bookId).size()==0) { return "wrong bookId or this book is already deleted."; } else { return bookService.selectBooks(bookId).get(0).getBookName(); } } @ResponseBody @RequestMapping("insertBook") public Map<String, Object> manageInsertBook(@RequestParam(value="bookName") String bookName,@RequestParam(value="bookQuantity") String bookQuantity,@RequestParam(value="bookUnitPrice") String bookUnitPrice,@RequestParam(value="userId") String userId) { Map<String, Object> result=new HashMap<String,Object>(); String id=bookService.setRandomBookId(); Book book=new Book(); book.setBookId(id); book.setBookName(bookName); String pattern="^[0-9]+"; if(!bookQuantity.matches(pattern)||bookQuantity.charAt(0)=='0') { System.out.println("1"); result.put("status", 0); result.put("errorMsg", "wrong input information."); //return "wrong input information."; } else { int quantity=Integer.parseInt(bookQuantity); book.setBookQuantity(quantity); String pattern2="^[0-9\\.]+"; if(!bookUnitPrice.matches(pattern2)) { System.out.println("2"); result.put("status", 0); result.put("errorMsg", "wrong input information."); //return "wrong input information."; } else { String[]temp=bookUnitPrice.split("\\."); if((temp.length==1 && bookUnitPrice.charAt(0)!='0') || (temp.length==2 && bookUnitPrice.charAt(bookUnitPrice.length()-1)!='0')) { float price=Float.parseFloat(bookUnitPrice); book.setBookUnitPrice(price); book.setBookSellerId(userId); book.setSaleOrNot(1); bookService.insertBook(book); System.out.println("4"); result.put("status", 1); result.put("data", id); //return id; } else { System.out.println(temp.length); System.out.println(bookUnitPrice.charAt(0)); System.out.println(bookUnitPrice.charAt(bookUnitPrice.length()-1)); result.put("status", 0); result.put("errorMsg", "wrong input information."); //return "wrong input information."; } } } return result; } @ResponseBody @RequestMapping("update") public String updateBookInformation(@RequestParam(value="bookId")String bookId,@RequestParam(value="bookName")String bookName,@RequestParam(value="bookQuantity")String bookQuantity,@RequestParam(value="bookUnitPrice")String bookUnitPrice,@RequestParam(value="userId")String userId) { if(bookService.selectBooks(bookId).size()==0) { System.out.println("1"); return "wrong bookId."; } else { Book book=bookService.selectBooks(bookId).get(0); if(userId.equals(book.getBookSellerId())) { String pattern="^[0-9]+"; if(!bookQuantity.matches(pattern) || bookQuantity.charAt(0)=='0') { System.out.println("2"); return "wrong input information."; } else { book.setBookName(bookName); book.setBookQuantity(Integer.parseInt(bookQuantity)); String pattern2="^[0-9\\.]+"; if(!bookUnitPrice.matches(pattern2)) { System.out.println("3"); return "wrong input information."; } else { String[]temp=bookUnitPrice.split("\\."); if((temp.length==1 && bookUnitPrice.charAt(0)!='0') || (temp.length==2 && bookUnitPrice.charAt(bookUnitPrice.length()-1)!='0')) { float price=Float.parseFloat(bookUnitPrice); book.setBookUnitPrice(price); book.setBookSellerId(userId); bookService.updateBook(book); System.out.println("5"); return "change successfullt"; } else { System.out.println("4"); return "wrong input information."; } } } } else { return "wrong bookId."; } } } @ResponseBody @RequestMapping(value="buy") // public String buyBooks(@RequestParam(value="bookId") String bookId,@RequestParam(value="quantity") String quantity) { List<Book> books=bookService.selectBooks(bookId); Book book=books.get(0); String pattern="['0-9']+"; if(quantity.matches(pattern) && quantity.charAt(0)!='0') { int eNum=book.getBookQuantity(); if(eNum>=Integer.parseInt(quantity)) { book.setBookQuantity(eNum-Integer.parseInt(quantity)); //bookService.updateBook(book); float cost=(Integer.parseInt(quantity))*(book.getBookUnitPrice()); return String.valueOf(cost); } else { return "no enough books"; } } else { return "wrong input number."; } } @ResponseBody @RequestMapping(value="searchBookName") // public Map<String, Object> searchBookName(@RequestParam(value="bookName")String bookName) { Map<String, Object> result=new HashMap<String,Object>(); System.out.print(bookName); if(bookService.searchBooksByBookName(bookName).size()==0) { result.put("status", "0"); result.put("errorMsg", "no such books"); } else { List<Book> books=bookService.searchBooksByBookName(bookName); result.put("status", "1"); result.put("data",books); } return result; } @ResponseBody @RequestMapping("searchSeller") public Map<String, Object> searchSeller(@RequestParam(value="sellerName")String sellerName) { Map<String, Object> result=new HashMap<String,Object>(); if(bookService.selectBooksBySellerName(sellerName).size()==0) { result.put("status1", "0"); result.put("errorMsg", "no books on sale"); if(bookService.selectBooksNotSaleBySellerName(sellerName).size()==0) { result.put("status2", "0"); result.put("errorMsg", "no books not sale"); } else { result.put("status2", "1"); List<Book> books=bookService.selectBooksNotSaleBySellerName(sellerName); result.put("booksNotSale", books); } } else { List<Book> books=bookService.selectBooksBySellerName(sellerName); result.put("status1", "1"); result.put("booksOnSale", books); if(bookService.selectBooksNotSaleBySellerName(sellerName).size()==0) { result.put("status2", "0"); result.put("errorMsg", "no books not sale"); } else { result.put("status2", "1"); List<Book> bookNotSale=bookService.selectBooksNotSaleBySellerName(sellerName); result.put("booksNotSale", bookNotSale); } } return result; } @ResponseBody @RequestMapping("searchSellerDistinct") public Map<String, Object> searchSellerDistinct(@RequestParam(value="sellerName")String sellerName) { Map<String, Object> result=new HashMap<String,Object>(); if(bookService.selectSellerNameDistinct(sellerName).size()==0) { result.put("status", "0"); result.put("errorMsg", "no books"); } else { List<String> name=bookService.selectSellerNameDistinct(sellerName); result.put("status", "1"); result.put("data", name); } return result; } @ResponseBody @RequestMapping("/{sellerName}/searchSeller2") public Map<String, Object> searchSeller2(@PathVariable String sellerName) { Map<String, Object> result=new HashMap<String,Object>(); if(bookService.selectBooksBySellerName(sellerName).size()==0) { result.put("status", "0"); result.put("errorMsg", "no books"); } else { List<Book> books=bookService.selectBooksBySellerName(sellerName); result.put("status", "1"); result.put("data", books); } return result; } @ResponseBody @RequestMapping("selectBook") public Map<String, Object> selectBook(@RequestParam (value="bookId")String bookId) { Map<String, Object> result=new HashMap<String,Object>(); if(bookService.selectBooks(bookId).size()==0) { result.put("status", 0); result.put("errorMsg", "no such book"); } else { Book book=bookService.selectBooks(bookId).get(0); result.put("status", 1); result.put("data", book); } return result; } /* @ResponseBody @RequestMapping("/{bookId}/select_Book") public Map<String, Object> select_Book(@PathVariable String bookId) { Map<String, Object> result=new HashMap<String,Object>(); if(bookService.selectBooks(bookId).size()==0) { result.put("status", "0"); result.put("errorMsg", "no such book"); } else { Book book=bookService.selectBooks(bookId).get(0); result.put("status", "1"); result.put("data", book); } return result; }*/ @ResponseBody @RequestMapping("deleteBook") public String deleteBook(@RequestParam(value="bookId")String bookId,@RequestParam(value="userId")String userId) { if(bookService.selectBooks(bookId).size()==0) { return "no such books"; } else { Book book=bookService.selectBooks(bookId).get(0); if(userId.equals(book.getBookSellerId())) { book.setSaleOrNot(0); bookService.updateBook(book); String bookName=book.getBookName(); return bookName+" deja delete"; } else { return "wrong bookId."; } } } @ResponseBody @RequestMapping("mostSale") public Map<String, Object>mostSale() { Map<String, Object> result=new HashMap<String,Object>(); if(bookService.bookMostSale().size()==0) { result.put("status", 0); result.put("errorMsg", "can not find."); } else { Book book=bookService.bookMostSale().get(0); result.put("status", 1); result.put("data", book); } return result; } }
package render; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Font; import java.awt.GridLayout; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.ListCellRenderer; import varTypes.Pez; @SuppressWarnings("serial") public class RenderLista extends JLabel implements ListCellRenderer<Pez> { public Component getListCellRendererComponent(JList<? extends Pez> list, Pez pez, int index, boolean isSelected, boolean cellHasFocus) { JPanel panel = new JPanel(new BorderLayout()); if (pez.getGenero().toLowerCase().contains("macho")) { panel.add(new JLabel(new ImageIcon("Iconos/pez/white.png")), BorderLayout.WEST); } else if (pez.getGenero().toLowerCase().contains("hembra")) { panel.add(new JLabel(new ImageIcon("Iconos/pez/orange.png")), BorderLayout.WEST); } else { panel.add(new JLabel(new ImageIcon("Iconos/pez/Blinky.png")), BorderLayout.WEST); } JPanel panelDer = new JPanel(new GridLayout(1, 1)); JLabel nombre = new JLabel(pez.getNombrePez()); nombre.setForeground(Color.MAGENTA); nombre.setFont(new Font("Arial", Font.ITALIC, 16)); panelDer.add(nombre); panel.add(panelDer, BorderLayout.CENTER); panel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2)); if (isSelected) panel.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 3)); return panel; } }
package net.nevinsky.core.app.repos; import net.nevinsky.global.entity.Employee; import org.springframework.data.jpa.repository.JpaRepository; /** * Created by inver on 22.06.14. */ public interface EmployeeRepository extends JpaRepository<Employee, Long> { }
package com.citibank.ods.entity.pl; import com.citibank.ods.common.entity.BaseODSEntity; import com.citibank.ods.entity.pl.valueobject.BaseTplClassCmplcEntityVO; // //©2002-2007 Accenture. All rights reserved. // /** * [Class description] * * @see package com.citibank.ods.entity.pl; * @version 1.0 * @author gerson.a.rodrigues,Mar 13, 2007 * * <PRE> * * <U>Updated by: </U> <U>Description: </U> * * </PRE> */ public class BaseTplClassCmplcEntity extends BaseODSEntity { public static final int C_CLASS_CMPLC_CODE_SIZE = 6; public static final int C_CLASS_CMPLC_TEXT_SIZE = 40; public static final int C_CLASS_CMPLC_CODE_SRC_SIZE = 6; public static final int C_CLASS_CMPLC_TEXT_SRC_SIZE = 40; public static final int C_SENS_IND_SIZE = 1; protected BaseTplClassCmplcEntityVO m_data; public BaseTplClassCmplcEntity() { m_data = new BaseTplClassCmplcEntityVO(); } public BaseTplClassCmplcEntityVO getData() { return m_data; } }
package northwind.dataAccess.concretes; import java.util.ArrayList; import java.util.List; import northwind.dataAccess.abstracts.CategoryRepository; import northwind.dataAccess.abstracts.ProductRepository; import northwind.entities.concretes.Category; public class CategoryDao implements CategoryRepository{ List<Category> categories; public CategoryDao() { categories=new ArrayList<Category>(); } @Override public void add(Category category) { categories=new ArrayList<Category>(); } @Override public void delete(Category category) { // TODO Auto-generated method stub } @Override public void update(Category category) { // TODO Auto-generated method stub } @Override public Category getById(int id) { // TODO Auto-generated method stub return null; } @Override public List<Category> getAll() { // TODO Auto-generated method stub return categories; } }
package com.designurway.idlidosa.model; import com.google.gson.annotations.SerializedName; public class DashComboModel { @SerializedName("combo_id") private String comboId; @SerializedName("combo_name") private String comboName; @SerializedName("image") private String comboImage; public DashComboModel(String comboId, String comboName, String comboImage) { this.comboId = comboId; this.comboName = comboName; this.comboImage = comboImage; } public String getComboId() { return comboId; } public void setComboId(String comboId) { this.comboId = comboId; } public String getComboName() { return comboName; } public void setComboName(String comboName) { this.comboName = comboName; } public String getComboImage() { return comboImage; } public void setComboImage(String comboImage) { this.comboImage = comboImage; } }
package com.example.demo.WeatherObserver_jdk; public class Client { public static void main(String[] args) { ConcreateWeatherSubject subject = new ConcreateWeatherSubject(); ConcreateObserver girl = new ConcreateObserver(); girl.setObserverName("girl"); ConcreateObserver mum = new ConcreateObserver(); mum.setObserverName("mum"); subject.addObserver(girl); subject.addObserver(mum); subject.setContent("天气不好,下雨了"); } }
package com.example.core.threadImpl; import com.example.resource.Counter; import java.util.concurrent.atomic.AtomicInteger; import static java.lang.String.format; /** * email : s.lakhmenev@andersenlab.com * * @author Lakhmenev Sergey * @version 1.1 */ public class RunableImpl { private static Counter counter = new Counter(); private static AtomicInteger result = new AtomicInteger(); private static AtomicInteger valBefore = new AtomicInteger(); //You can use it instead of Atomic (this case not safety) //private static volatile int result, valBefore; public static void main(String[] args) { for (int i = 0; i < 10; i++) { Runnable task = () -> { try { doWork(); } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(format(Thread.currentThread().getName() + ": valBefore = %d, result = %d", valBefore.get(), result.get())); }; Thread thread = new Thread(task); thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Final result = " + result); } private static void doWork() throws InterruptedException { valBefore = result; for (int i = 0; i < 10; i++) { result.addAndGet(counter.count(i)); // result += counter.count(i); } } }
package com.tony.pandemic.report; import java.util.Map; public interface IListItems { Map<String, String> listItens(); }
package view; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.VBox; import javafx.stage.Stage; import model.Game; import java.util.Random; public class PlayerView { private Stage stage = new Stage(); private Scene playerScene; private Label diceLabel; private Button playButton; private Label messageLabel; private PlayerView playerView; private int spelerNummer; private Game game; public PlayerView(int spelerNummer, Game game){ playerView = this; this.game = game; this.spelerNummer = spelerNummer; diceLabel = new Label("beurt 1: "); playButton = new Button("Werp dobbelstenen"); playButton.setOnAction(new ThrowDicesHandler()); playButton.setDisable(true); messageLabel = new Label("Spel nog niet gestart"); layoutComponents(); stage.setScene(playerScene); stage.setTitle("Speler "+ spelerNummer); stage.setResizable(false); stage.setX(100+(spelerNummer-1) * 350); stage.setY(200); stage.show(); } private void layoutComponents() { VBox root = new VBox(10); playerScene = new Scene(root,250,100); root.getChildren().add(playButton); root.getChildren().add(diceLabel); root.getChildren().add(messageLabel); } public void isAanBeurt(boolean aanBeurt){ playButton.setDisable(!aanBeurt); } class ThrowDicesHandler implements EventHandler<ActionEvent> { @Override public void handle(ActionEvent event) { int totaal; int randomdice1 = new Random().nextInt(5) + 1; int randomdice2 = new Random().nextInt(5) + 1; if (randomdice1 == randomdice2){ totaal = (randomdice1 + randomdice2)*2; }else{ totaal = randomdice1 + randomdice2; } game.notifyObservers(game.getSpelers(), playerView, game.getView(), randomdice1, randomdice2, totaal); } } public void setMessageLabel(String tekst) { playerView.messageLabel.setText(tekst); } public int getSpelerNummer() { return spelerNummer; } public void setDiceLabel(String tekst) { this.diceLabel.setText(tekst); } }
package com.mpls.v2.service; import com.mpls.v2.dto.MailBodyDTO; import com.mpls.v2.model.MailBody; import java.util.List; public interface MailBodyService { MailBody save(MailBody mailBody); MailBody update(MailBody mailBody); MailBody update(MailBodyDTO mailBodyDTO); List<MailBody> findAll(); MailBody findOne(Long id); Boolean delete(Long id); MailBody findByName(String name); }
package com.eshop.controller.command; import java.util.List; import java.math.BigDecimal; import javax.servlet.http.HttpServletRequest; import com.eshop.model.dao.DBException; import com.eshop.model.service.ProductsService; import com.eshop.model.entity.Product; import com.eshop.model.entity.ProductState; import com.eshop.model.entity.User; import com.eshop.model.entity.Role; import com.eshop.controller.Attributes; import com.eshop.controller.Path; import java.util.logging.Logger; import java.util.logging.Level; public class UpdateProductCommand implements Command { Logger logger = Logger.getLogger(UpdateProductCommand.class.getName()); @Override public CommandOutput execute (HttpServletRequest req) { ProductsService service = new ProductsService(); try { long id = Long.parseLong(req.getParameter(Attributes.PRODUCT_ID)); Product product = service.getProduct(id); String name = req.getParameter(Attributes.NAME); String category = req.getParameter(Attributes.CATEGORY); String description = req.getParameter(Attributes.DESCRIPTION); String stateParam = req.getParameter(Attributes.STATE); BigDecimal price; int amount; try { price = new BigDecimal(req.getParameter(Attributes.PRICE)); amount = Integer.parseInt(req.getParameter(Attributes.AMOUNT)); } catch (NumberFormatException | NullPointerException e) { throw new IllegalArgumentException ("wrong input"); } ProductState state = product.getState(); for (ProductState ps: ProductState.values()) if (ps.toString().equals(stateParam)) state = ps; //builder?? product.setName(name); product.setCategory(category); product.setDescription(description); product.setPrice(price); product.setAmount(amount); product.setState(state); service.updateProduct(product); return new CommandOutput (Path.PRODUCTS, true); } catch (IllegalArgumentException | DBException e) { logger.log(Level.INFO, e.getMessage(), e); req.getSession().setAttribute(Attributes.EXCEPTION, e); return new CommandOutput (Path.EXCEPTION_PAGE); } } @Override public boolean checkUserRights (User user) { return user != null && user.getRole() == Role.ADMIN; } }
package evolutionYoutube; import java.util.Arrays; import java.util.List; import com.vaadin.navigator.View; import com.vaadin.server.ExternalResource; import com.vaadin.ui.Button; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.UI; import database.BD_general; import database.Usuario_registrado; import database.Videos; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Image; import com.vaadin.ui.Panel; public class Vista_perfil_Registrado extends Vista_perfil_Registrado_ventana implements View { /** * */ private static final long serialVersionUID = 1L; public Usuario_Registrado _unnamed_Usuario_Registrado_; //public Suscribirse _unnamed_Suscribirse_; public Vista_perfil_Registrado(Usuario_registrado user) { user.setNumeroVisitas(user.getNumeroVisitas()+1); Image img = new Image("",new ExternalResource(user.getAvatar())); img.setWidth("100%"); avatar.addComponent(img); apodo.setValue(user.getApodo()); visitas.setValue("Visitas: "+user.getNumeroVisitas()); BD_general bd= new BD_general(); if(bd.cargar_Suscripciones(MyUI.getUsuarioLogged().getID()).contains(user)==true) { suscribirse.setCaption("Abandonar"); } numerosuscriptores.setValue("Suscriptores: "+bd.cargar_Seguidores(user.getID()).size()); HorizontalLayout layout = new HorizontalLayout(); HorizontalLayout layout2 = new HorizontalLayout(); if(user.video_subido!=null) { List<Videos> vide = bd.cargar_Videos_Subidos(user.getID()); Arrays.toString(user.video_subido.toArray()); for(int i=0;i<vide.size();i++) { Video_subido videoo = new Video_subido(vide.get(i)); layout.addComponent(videoo); } } if(user.listas_de_reproduccion!=null) { List<database.Listas_de_reproduccion> listas = bd.cargar_Listas_Reproduccion(user.getID()); for(int i=0;i<listas.size();i++) { Listas_creadas lista2 = new Listas_creadas(listas.get(i)); layout2.addComponent(lista2); } } Panel panel = new Panel("Videos subidos"); panel.setWidth("1000px"); panel.setHeight("400px"); layout.setSizeUndefined(); panel.setContent(layout); videossubidos.addComponent(panel); Panel panel2 = new Panel("Listas"); panel2.setWidth("1000px"); panel2.setHeight("400px"); layout2.setSizeUndefined(); panel2.setContent(layout2); listas_reproduccion.addComponent(panel2); HorizontalLayout layout3 = new HorizontalLayout(); HorizontalLayout layout4 = new HorizontalLayout(); Panel panel3 = new Panel("Suscriptores"); panel3.setWidth("1000px"); panel3.setHeight("400px"); layout3.setSizeUndefined(); layout3.addComponent(new Lista_Suscriptores(user)); panel3.setContent(layout3); seguidores.addComponent(panel3); Panel panel4 = new Panel("Seguidores"); panel4.setWidth("1000px"); panel4.setHeight("400px"); layout4.setSizeUndefined(); layout4.addComponent(new Lista_Seguidores(user)); panel4.setContent(layout4); suscripciones.addComponent(panel4); volver.addClickListener(new Button.ClickListener() { /** * */ private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { ((MyUI) UI.getCurrent()).usuario_registrado(); } }); suscribirse.addClickListener(new Button.ClickListener() { /** * */ private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { //es registrado if(MyUI.getUsuarioLogged()!=null) { if(bd.cargar_Suscripciones(MyUI.getUsuarioLogged().getID()).contains(user)==false) { bd.suscribirse(MyUI.getUsuarioLogged().getID(), user.getID()); ((MyUI) UI.getCurrent()).ver_perfil_registrado(user); } else if(bd.cargar_Suscripciones(MyUI.getUsuarioLogged().getID()).contains(user)==true) { bd.dejar_de_seguir(MyUI.getUsuarioLogged().getID(), user.getID()); ((MyUI) UI.getCurrent()).ver_perfil_registrado(user); } } } }); if(MyUI.getUsuarioLogged()==null) { suscribirse.setEnabled(false); } } }
/* * package kr.or.ddit.controller.mypage; * * import java.net.URL; import java.util.ResourceBundle; import * javafx.event.ActionEvent; import javafx.fxml.FXML; import * javafx.scene.control.Button; import javafx.scene.control.Label; import * javafx.scene.control.TextField; import javafx.scene.input.MouseEvent; import * javafx.scene.layout.AnchorPane; * * // 내정보 화면 public class MyInfomationModifyController { * * * private IMymemberService service; private ObservableList<MemberVO> * memberList; private MemberVO memVO; private String confirmNumber = ""; * private String result; private InterestVO interVO; private InterestArticleVO * intArtiVO; private Article_ResultVO aresutVO; private ImemberInfoService * service; private ObservableList<MemberInfoVO> data; private String * confirmNumber = ""; private MemberInfoVO memInfoVO; private InterestVO * interVO; private InterestArticleVO intArtiVO; private Article_ResultVO * aresutVO; * * private MymemberController mymemberController; * * public MymemberController getMymemberController() { return * mymemberController; } * * public void setMyInfoController(MymemberController mymemberInfoCont) { * this.mymemberController = mymemberInfoCont; } * * @FXML private ResourceBundle resources; * * @FXML private URL location; * * @FXML private AnchorPane memberView; * * @FXML private TextField tfId; * * @FXML private TextField tfPass; * * @FXML private TextField tfRePass; * * @FXML private TextField tfName; * * @FXML private TextField tfReg; * * @FXML private TextField tfAdd; * * @FXML private TextField tfTel; * * @FXML private TextField tfEmail; * * @FXML private TextField tfInputNum; * * @FXML private TextField tfAdd2; * * @FXML private Button btnnumCom; * * @FXML private Button btnAddSerach; * * @FXML private Button btnemailCon; * * @FXML private Button btnModify; * * @FXML private Button btnOut; * * @FXML private Label passLabel; * * @FXML private Label idLabel; * * @FXML private Label nameLabel; * * @FXML private Label telLabel; * * @FXML private Label regLabel; * * * // 주소 검색 버튼 * * @FXML void btnAddSearch(MouseEvent event) { try { * * FXMLLoader fxmlLoader = new * FXMLLoader(getClass().getResource("../../fxml/adminmypage/AddSearch.fxml")); * Parent root = (Parent)fxmlLoader.load(); Stage primaryStage = (Stage) * btnAddSerach.getScene().getWindow(); * * Stage primaryStage2 = new Stage(StageStyle.DECORATED); * primaryStage2.initModality(Modality.WINDOW_MODAL); * primaryStage2.initOwner(primaryStage); * * AddSearch controller = fxmlLoader.getController(); * controller.setDialog(this); * * Scene scene = new Scene(root); primaryStage2.setScene(scene); * primaryStage2.setTitle("주소 검색"); primaryStage2.show(); * * } catch (Exception e) { e.printStackTrace(); } } * * * public void inputAddr(String zipcode, String addr) { // 3번째 창한테 받은 정보 * tfAdd.setText(zipcode); tfAdd2.setText(addr); } * * * * // 이메일 전송 버튼 * * @FXML void btnEmailCon(MouseEvent event) { mail(); } private void mail() { * try { * * String host = "smtp.naver.com"; String user = "xovud925@naver.com"; // 계정 * String password = "wldms*36810"; // 패스워드 * * // SMTP 서버 정보를 설정 Properties props =new Properties(); * props.put("mail.smtp.host", host); props.put("mail.smtp.port", 587); * props.put("mail.smtp.auth", "true"); * * Session session = Session.getDefaultInstance(props, new * javax.mail.Authenticator() { protected PasswordAuthentication * getPasswordAuthentication() { return new PasswordAuthentication(user, * password); } }); * * try { MimeMessage message = new MimeMessage(session); message.setFrom(new * InternetAddress(user)); * message.addRecipient(javax.mail.Message.RecipientType.TO, new * InternetAddress(tfEmail.getText())); * * // 메일 제목 message.setSubject("안녕하세요. 경매관리시스템 AIMS 입니다."); * * // 메일 내용 * * for( int i = 0; i < 6; i++) { int a =(int)(Math.random()*10); * confirmNumber+=a+""; } * * message.setText("인증번호는" + ""+confirmNumber+""+"입니다."); * * * * * // 메일 보내기 Transport.send(message); System.out.println(message); * System.out.println("메일 전송 완료!"); * * * } catch (MessagingException e) { e.printStackTrace(); * System.out.println("전송실패"); } } catch (Exception e) { e.printStackTrace(); } * * // 메일 인증번호 * * @FXML void btnNumCon(MouseEvent event) { * if(tfInputNum.getText().equals(confirmNumber)) { //일치했을때 Stage currStage = * (Stage) btnnumCom.getScene().getWindow(); * AlertUtil.showAlert((Stage)btnnumCom.getScene().getWindow(),"입력하신 인증번호가 " * ,"확인되었습니다.","확인","취소"); }else { //일치하지 않을때 Stage currStage = (Stage) * btnnumCom.getScene().getWindow(); * AlertUtil.showAlert((Stage)btnnumCom.getScene().getWindow(),"입력하신 인증번호가 " * ,"틀렸습니다.","확인","취소"); } } // 정보 수정 버튼 * * @FXML void btnModify(ActionEvent event) { * * if(tfId.getText().isEmpty() || tfPass.getText().isEmpty() || * tfPass.getText().isEmpty() || tfRePass.getText().isEmpty() * ||tfEmail.getText().isEmpty() || tfName.getText().isEmpty() || * tfReg.getText().isEmpty() || tfTel.getText().isEmpty() || * tfAdd.getText().isEmpty() || tfAdd2.getText().isEmpty() || * tfInputNum.getText().isEmpty()) { * * Stage currentStage = (Stage) btnModify.getScene().getWindow(); * if(AlertUtil.showAlert((Stage) btnModify.getScene().getWindow(), * "빈칸을 입력해주세요")); }else { * * } * * Stage currentStage = (Stage) btnModify.getScene().getWindow(); * if(AlertUtil.showAlert((Stage) btnModify.getScene().getWindow(), * "회원정보를 수정하시겠습니까?")) { * * // 수정한 데이터 저장하는거 memInfoVO = new MemberInfoVO(); * memInfoVO.setMem_id(tfId.getText()); memInfoVO.setMem_pass(tfPass.getText()); * memInfoVO.setMem_email(tfEmail.getText()); * memInfoVO.setMem_name(tfName.getText()); * memInfoVO.setMem_regno(tfReg.getText()); * memInfoVO.setMem_tel(tfTel.getText()); memInfoVO.setMem_zip(tfAdd.getText()); * memInfoVO.setMem_addr(tfAdd2.getText()); * * * * * try { int cnt = service.updateMember(memInfoVO); } catch (RemoteException e) * { // TODO: handle exception e.printStackTrace(); } * * * * * } * * try { FXMLLoader loader = new * FXMLLoader(MemberInfoController.class.getResource( * "../../fxml/adminmypage/memberInfo.fxml")); Parent root = loader.load(); * MemberInfoController memif = loader.getController(); * memif.setMainController(this); Scene scene = new Scene(root); * currentStage.setScene(scene); currentStage.show(); * * * * } catch (Exception e) { // TODO: handle exception } * * * * * * * } * * try { * * // 수정 버튼 눌렀을 때 처음 화면으로 이동 FXMLLoader loader = new * FXMLLoader(MySchedualController.class.getResource( * "../../fxml/mypage/MySchedual.fxml")); Parent root = loader.load(); * * for (int i = 1; i < memInfoView.getChildren().size(); i++) { * memInfoView.getChildren().remove(i); } * memInfoView.getChildren().addAll(root); * * // memberList = * FXCollections.observableArrayList(service.getMyInfoList("jieun")); * * // MyInformationController memif = loader.getController(); // * memif.setMyInfoController(this); // Scene scene = new Scene(root); // * currentStage.setScene(scene); // currentStage.show(); * * * // memInfoView.setItems(memberList); * * } catch (Exception e) { * * } * * } * * // 회원 탈퇴 * * @FXML void btnOut(ActionEvent event) { Parent root = * FXMLLoader.load(MymemberController.class.getResource( * "../../fxml/mypage/Mymemtaltoe.fxml")); * * for (int i = 0; i < memInfoView.getChildren().size(); i++) { * memInfoView.getChildren().remove(i); } * * memInfoView.getChildren().addAll(root); } * * // 화면 전환해서 보여지는거 public void show(MemberInfoVO mifVO) { * * this.mifVO = mifVO; tfId.setText(mifVO.getMem_id()); * tfPass.setText(mifVO.getMem_pass()); * //textPassRe.setText(mifVO.getMem_pass()); * tfName.setText(mifVO.getMem_name()); tfReg.setText(mifVO.getMem_regno()); * tfTel.setText(mifVO.getMem_tel()); tfEmail.setText(mifVO.getMem_email()); * blacklistLabel.setText(mifVO.getMem_blacklist()); * tfAdd.setText(mifVO.getMem_zip()); tfAdd2.setText(mifVO.getMem_addr()); // * 아이디 값은 비활성화 tfId.setEditable(false); * * * * } * * * @FXML void initialize() { // service 생성 try { Registry reg = * LocateRegistry.getRegistry(8888); * * service = (ImemberInfoService) reg.lookup("ImemberInfoService"); } catch * (RemoteException e) { e.printStackTrace(); }catch (NotBoundException e) { * e.printStackTrace(); } * * * // // 입력 받는 값 저장하는거 // memInfoVO = new MemberInfoVO(); // // * memInfoVO.setMem_id(tfId.getText()); // * memInfoVO.setMem_name(tfName.getText()); // * memInfoVO.setMem_pass(tfPass.getText()); // * memInfoVO.setMem_regno(tfReg.getText()); // * memInfoVO.setMem_tel(tfTel.getText()); // * memInfoVO.setMem_email(tfEmail.getText()); // * memInfoVO.setMem_zip(tfAdd.getText()); // * memInfoVO.setMem_addr(tfAdd2.getText()); // * * // * 정규식-------------------------------------------------------------------------- * ------------------------------- * * // 패스워드 tfPass.textProperty().addListener((Observable, oldValue, newValue) -> * { if(!newValue.matches("[A-Za-z0-9_-]{5,15}")) { * if(!newValue.matches("\\d*")) { * tfPass.setText(newValue.replaceAll("[A-Za-z0-9_-]{5,15}", "")); * passLabel.setText("5-15자의 영문자, 숫자만 가능"); } } else * if(newValue.matches("[A-Za-z0-9_-]{5,15}")) { passLabel.setText(" "); } }); * * // 패스워드 일치 tfRePass.textProperty().addListener((Observable, oldValue, * newValue) -> { if(!tfPass.getText().equals(tfRePass.getText())) { * passLabel.setText("비밀번호가 일치하지 않습니다."); }else if * (newValue.equals(tfRePass.getText())) { passLabel.setText(""); * * } }); * * // 이름 tfName.textProperty().addListener((Observable, oldValue, newValue) -> { * if(!newValue.matches("^[A-Za-z가-힣]*$")) { if(!newValue.matches("\\d*")) { * tfName.setText(newValue.replaceAll("^[A-Za-z가-힣]*$", "")); * nameLabel.setText("정확한 이름을 입력해 주세요."); } }else * if(newValue.matches("^[A-Za-z가-힣]*$")) { nameLabel.setText(" "); } }); * * // 주민등록번호 tfReg.textProperty().addListener((Observable, oldValue, newValue) * -> { if(!newValue.matches("[0-9]{6}\\-[0-9]{7}$")) { * if(!newValue.matches("\\d*")) { * tfReg.setText(newValue.replaceAll("[0-9]{6}\\-[0-9]{7}$", "")); * regLabel.setText("주민번호 13자리를 입력해주세요. ex) 123456-1234567"); } }else * if(newValue.matches("[0-9]{6}\\-[0-9]{7}$")) { regLabel.setText(" "); } }); * * * // 전화번호 tfTel.textProperty().addListener((Observable, oldValue, newValue) -> * { if(!newValue.matches("[0-9]{11}")) { if(!newValue.matches("\\d*")) { * tfTel.setText(newValue.replaceAll("[0-9]{11}", "")); * telLabel.setText("숫자만 입력해주세요."); } }else if(newValue.matches("[0-9]{11}")) { * telLabel.setText(" "); } }); * * * * * } } */ package kr.or.ddit.controller.mypage; import java.net.URL; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; public class MyInfomationModifyController { @FXML private ResourceBundle resources; @FXML private URL location; @FXML private AnchorPane memberView; @FXML private TextField tfId; @FXML private TextField tfPass; @FXML private TextField tfRePass; @FXML private TextField tfName; @FXML private TextField tfReg; @FXML private TextField tfAdd; @FXML private TextField tfTel; @FXML private TextField tfEmail; @FXML private TextField tfInputNum; @FXML private Button btnnumCom; @FXML private Button btnAddSerach; @FXML private TextField tfAdd2; @FXML private Button btnemailCon; @FXML private Label passLabel; @FXML private Label idLabel; @FXML private Label nameLabel; @FXML private Label telLabel; @FXML private Label regLabel; @FXML private Button btnModify; @FXML private Button btnOut; @FXML void btnAddSearch(MouseEvent event) { } @FXML void btnEmailCon(MouseEvent event) { } @FXML void btnModify(ActionEvent event) { } @FXML void btnNumCon(MouseEvent event) { } @FXML void btnOut(ActionEvent event) { } @FXML void initialize() { assert memberView != null : "fx:id=\"memberView\" was not injected: check your FXML file 'MyInformaionMo.fxml'."; assert tfId != null : "fx:id=\"tfId\" was not injected: check your FXML file 'MyInformaionMo.fxml'."; assert tfPass != null : "fx:id=\"tfPass\" was not injected: check your FXML file 'MyInformaionMo.fxml'."; assert tfRePass != null : "fx:id=\"tfRePass\" was not injected: check your FXML file 'MyInformaionMo.fxml'."; assert tfName != null : "fx:id=\"tfName\" was not injected: check your FXML file 'MyInformaionMo.fxml'."; assert tfReg != null : "fx:id=\"tfReg\" was not injected: check your FXML file 'MyInformaionMo.fxml'."; assert tfAdd != null : "fx:id=\"tfAdd\" was not injected: check your FXML file 'MyInformaionMo.fxml'."; assert tfTel != null : "fx:id=\"tfTel\" was not injected: check your FXML file 'MyInformaionMo.fxml'."; assert tfEmail != null : "fx:id=\"tfEmail\" was not injected: check your FXML file 'MyInformaionMo.fxml'."; assert tfInputNum != null : "fx:id=\"tfInputNum\" was not injected: check your FXML file 'MyInformaionMo.fxml'."; assert btnnumCom != null : "fx:id=\"btnnumCom\" was not injected: check your FXML file 'MyInformaionMo.fxml'."; assert btnAddSerach != null : "fx:id=\"btnAddSerach\" was not injected: check your FXML file 'MyInformaionMo.fxml'."; assert tfAdd2 != null : "fx:id=\"tfAdd2\" was not injected: check your FXML file 'MyInformaionMo.fxml'."; assert btnemailCon != null : "fx:id=\"btnemailCon\" was not injected: check your FXML file 'MyInformaionMo.fxml'."; assert passLabel != null : "fx:id=\"passLabel\" was not injected: check your FXML file 'MyInformaionMo.fxml'."; assert idLabel != null : "fx:id=\"idLabel\" was not injected: check your FXML file 'MyInformaionMo.fxml'."; assert nameLabel != null : "fx:id=\"nameLabel\" was not injected: check your FXML file 'MyInformaionMo.fxml'."; assert telLabel != null : "fx:id=\"telLabel\" was not injected: check your FXML file 'MyInformaionMo.fxml'."; assert regLabel != null : "fx:id=\"regLabel\" was not injected: check your FXML file 'MyInformaionMo.fxml'."; assert btnModify != null : "fx:id=\"btnModify\" was not injected: check your FXML file 'MyInformaionMo.fxml'."; assert btnOut != null : "fx:id=\"btnOut\" was not injected: check your FXML file 'MyInformaionMo.fxml'."; } }
package com.marijannovak.littletanks; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; /** * Created by marij on 20.4.2017.. */ public class DatabaseHelper extends SQLiteOpenHelper { private static DatabaseHelper Instance = null; private DatabaseHelper(Context context) { super(context.getApplicationContext(),DatabaseScheme.DB_NAME, null, DatabaseScheme.VERSION); } public static synchronized DatabaseHelper getInstance(Context context) { if(Instance == null) { Instance = new DatabaseHelper(context); } return Instance; } private static final String SELECT_SCORES = "SELECT * FROM " + DatabaseScheme.SCORE_TABLE; @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + DatabaseScheme.SCORE_TABLE + " (" + DatabaseScheme.PLAYER_ID + " INTEGER PRIMARY KEY, " + DatabaseScheme.PLAYER + " TEXT, " + DatabaseScheme.PLAYTIME + " INT, " + DatabaseScheme.SCORE + " INT, " + DatabaseScheme.KILLED + " INT);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + DatabaseScheme.SCORE_TABLE); this.onCreate(db); } public void addScore(ScoreItem score) { ContentValues cValues = new ContentValues(); cValues.put(DatabaseScheme.PLAYER, score.getPlayerName()); cValues.put(DatabaseScheme.SCORE, score.getScore()); cValues.put(DatabaseScheme.PLAYTIME, score.getPlayTime()); cValues.put(DatabaseScheme.KILLED, score.getKilled()); SQLiteDatabase db = this.getWritableDatabase(); db.insert(DatabaseScheme.SCORE_TABLE, DatabaseScheme.PLAYER_ID, cValues); db.close(); } public ArrayList<ScoreItem> getHighScores() { SQLiteDatabase db = this.getWritableDatabase(); Cursor scoreCursor = db.rawQuery(SELECT_SCORES, null); ArrayList<ScoreItem> scoreList = new ArrayList<>(); if(scoreCursor.moveToFirst()) { do { ScoreItem score = new ScoreItem(); score.setPlayerName(scoreCursor.getString(1)); score.setPlayTime(scoreCursor.getInt(2)); score.setScore(scoreCursor.getInt(3)); score.setKilled(scoreCursor.getInt(4)); scoreList.add(score); }while (scoreCursor.moveToNext()); } scoreCursor.close(); db.close(); return scoreList; } public void clearScoreTable() { SQLiteDatabase db = this.getWritableDatabase(); db.execSQL("DELETE FROM "+ DatabaseScheme.SCORE_TABLE); } public static class DatabaseScheme { private static final int VERSION = 1; private static final String DB_NAME = "scoresDB.db"; private static final String SCORE_TABLE = "SCORES"; private static final String PLAYER_ID = "id"; private static final String PLAYER = "player"; private static final String SCORE = "score"; private static final String PLAYTIME = "playtime"; private static final String KILLED = "killed"; } }
package com.novakivska.runners.lesson6; import com.novakivska.app.classwork.lesson6.ForLoop; /** * Created by Tas_ka on 3/24/2017. */ public class ForLoopRunner { public static void main (String[] args){ //ForLoop.decade(); int j = 0; for (int i = 0; i <= 10; i++) { if ((i%2)==0 || i != 0){ j++; } } System.out.println("парных чисел " + j); } }
package pt.tooyummytogo; import java.util.List; import java.util.Random; import Observables.Subject; public class Reserva{ private List<Encomenda> listaEncomendas; private double preco; private String codigo; public Reserva(List<Encomenda> le, double p) { this.listaEncomendas = le; this.preco = p; } public double getPreco() { return preco; } public String gerarCodigo() { String[] caracteres = {"a","b","c","d","e","g","h","i","j","k","l","m","n","o","p","q", "r","s","t","u","v","w","x","y","z","1","2","3","4","5","6","7","8","9","0"}; String codigo = ""; Random r = new Random(); for(int i = 0; i < 6; i++) { int j = r.nextInt(caracteres.length); codigo = codigo + caracteres[j]; } r.nextInt(caracteres.length); return codigo; } public void subtrairProduto() { for(Encomenda e : listaEncomendas) { e.subtrai(); } } }
package com.ipincloud.iotbj.srv.domain; import java.io.Serializable; import java.math.BigDecimal; import java.sql.Time; import java.sql.Date; import java.sql.Timestamp; import com.alibaba.fastjson.annotation.JSONField; //(Visitperson) //generate by redcloud,2020-07-24 19:59:20 public class Visitperson implements Serializable { private static final long serialVersionUID = 80L; // 自增ID private Long id ; // 身份证号: private String idno ; // 姓名: private String name ; // 性别: private String gender ; // 人脸照片: private String image ; // 手机号码: private String phonenumber ; public Long getId() { return id ; } public void setId(Long id) { this.id = id; } public String getIdno() { return idno ; } public void setIdno(String idno) { this.idno = idno; } public String getName() { return name ; } public void setName(String name) { this.name = name; } public String getGender() { return gender ; } public void setGender(String gender) { this.gender = gender; } public String getImage() { return image ; } public void setImage(String image) { this.image = image; } public String getPhonenumber() { return phonenumber ; } public void setPhonenumber(String phonenumber) { this.phonenumber = phonenumber; } }
/* * 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 PPI.Vista; import PPI.Controladores.ControladorMisReservas; import PPI.Modelos.ModeloReserva; import PPI.Vistas.Interfaces.InterfazMisReservas; import java.awt.Image; import java.util.List; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JOptionPane; /** * * @author Personal */ public class VistaMisReservas extends javax.swing.JFrame implements InterfazMisReservas{ ControladorMisReservas controlador; ModeloReserva reservaModificado = new ModeloReserva(); /** * Creates new form VistaMisReservas */ public VistaMisReservas() { initComponents(); controlador = new ControladorMisReservas(this); this.setLocationRelativeTo(null); this.setIconImage(new ImageIcon(getClass().getResource("/Imagenes/grano-de-cafe.png")).getImage()); ImageIcon icon = new ImageIcon(System.getProperty("/Imagenes/grano-de-cafe.png")); Icon icono = new ImageIcon(icon.getImage().getScaledInstance(100, 100, Image.SCALE_DEFAULT)); List<ModeloReserva> reserva = controlador.VerificarReservas(); if (reserva != null) { VistaGenericaMisReservas controlGenerico = new VistaGenericaMisReservas(reserva, this); controlGenerico.crearReservas(this); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel4 = new javax.swing.JPanel(); lblLogo = new javax.swing.JLabel(); lblVolver = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jPanelMisPedidos = new javax.swing.JPanel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Mis pedidos - CoffeWine"); jPanel4.setBackground(new java.awt.Color(93, 64, 55)); lblLogo.setBackground(new java.awt.Color(255, 255, 255)); lblLogo.setFont(new java.awt.Font("Dialog", 3, 18)); // NOI18N lblLogo.setForeground(new java.awt.Color(255, 255, 255)); lblLogo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/grano-de-cafe.png"))); // NOI18N lblLogo.setText("CoffeWine"); lblVolver.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/atras.png"))); // NOI18N lblVolver.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); lblVolver.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { lblVolverMouseClicked(evt); } }); jLabel1.setBackground(new java.awt.Color(255, 255, 255)); jLabel1.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("Mis Pedidos"); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addContainerGap() .addComponent(lblVolver) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 220, Short.MAX_VALUE) .addComponent(jLabel1) .addGap(163, 163, 163) .addComponent(lblLogo) .addContainerGap()) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblLogo) .addComponent(jLabel1)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(lblVolver) .addGap(0, 0, Short.MAX_VALUE)) ); jPanelMisPedidos.setBackground(new java.awt.Color(215, 204, 200)); jPanelMisPedidos.setForeground(new java.awt.Color(215, 204, 200)); jPanelMisPedidos.setLayout(new java.awt.GridLayout(0, 1)); jScrollPane1.setViewportView(jPanelMisPedidos); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane1) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 408, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void lblVolverMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblVolverMouseClicked VistaPrincipal principal = new VistaPrincipal(); principal.setVisible(true); dispose(); }//GEN-LAST:event_lblVolverMouseClicked /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(VistaMisReservas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(VistaMisReservas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(VistaMisReservas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(VistaMisReservas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new VistaMisReservas().setVisible(true); } }); } public javax.swing.JPanel getJPanelScroll(){ return jPanelMisPedidos; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanelMisPedidos; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel lblLogo; private javax.swing.JLabel lblVolver; // End of variables declaration//GEN-END:variables @Override public void setTextLblImagenPublicar(String texto) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void setIconLblImagenPublicar(Icon icono) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void setTextLblNombreProducto(String texto) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void setTextLblCantidadDeReserva(String texto) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void setTextLblPrecio(String texto) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public int getWidthImagen() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public int getHeightImagen() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void reservaClickedModificar(int idReserva) { reservaModificado = controlador.ObtenerReservaModificar(idReserva); VistaProductosCatalogo ProductosCatalogo = new VistaProductosCatalogo(reservaModificado); ProductosCatalogo.setVisible(true); this.dispose(); } @Override public void reservaClickedEliminar(int idReserva) { int resp = JOptionPane.showConfirmDialog(null, "Esta seguro que quiere eliminar el pedido?", "ELIMINAR PEDIDO", JOptionPane.OK_CANCEL_OPTION); if (JOptionPane.OK_OPTION == resp) { ModeloReserva reservaEliminado = new ModeloReserva(); reservaEliminado.setIdReserva(idReserva); boolean eliminado = controlador.EliminarReserva(reservaEliminado.getIdReserva()); if (eliminado) { JOptionPane.showMessageDialog(null, "El pedido ha sido eliminado con éxito", "ELIMINAR PEDIDO", JOptionPane.INFORMATION_MESSAGE); VistaMisReservas vistaMisReservas = new VistaMisReservas(); vistaMisReservas.setVisible(true); this.dispose(); } } } }
package com.dbs.portal.ui.expception; public class UpdateException extends Exception{ private Object errors; public UpdateException(Object errors){ this.errors = errors; } public Object getErrorMessage(){ return this.errors; } }
package domain; import java.util.Date; /** * Class which controls the in game clock. * * The in game clock is based on the realtime clock. When a new Clock is created * without any arguments the current time and a multiplier of 1 is used. The * multiplier defines the rate at which in game time advances in comparison to * the real time. Through the use of a saved offset and the multiplier the in * game time also advances when the game is not running, forcing people run the * game often enough to get the maximum out of it. * * @author Rigès De Witte * @author Simon Peeters * @author Barny Pieters * @author Laurens Van Damme * */ public class Clock extends Savable { /** * the time at which the clock starts */ private static final long STARTTIME = 1325419200000L; // 1 jan. 2012 6:00 /** * the amount of milliseconds that add up to one day. */ public static final long MSECONDSADAY = 86400000L; /** * the speed multiplier of the clock */ private double multiplier; /** * the offset between unix epoch and the time the clock was started */ private long offset; /** * Creates a default clock. This clock is linked to the current time and * starting at January 1st 2012 at 6:00 The multiplier is set to 1 */ public Clock() { this(1); } /** * Creates a clock with a custom multiplier. This clock will start at the * current time at January 1st 2012 at 6:00, and will then further advance * {@code multiplier} times as fast as the real time. * * @param multiplier * the multiplier to use in this clock */ public Clock(double multiplier) { this(multiplier, new Date().getTime()); } /** * Creates a clock with custom multiplier and offset. This constructor * initiates a clock as if it was started at {@code offset} seconds since * unix epoch. The clock will advance at a speed of {@code multiplier} times * the real time. * * @param multiplier * the multiplier to use in this clock. * @param offset * the time this clock was started in milliseconds since unix epoch. */ public Clock(double multiplier, long offset) { this.multiplier = multiplier; this.offset = offset; } /** * * @return the offset value used by the current clock. */ public long getOffset() { return this.offset; } /** * * @return The currently used multiplier of this clock. */ public double getMultiplier() { return this.multiplier; } /** * Gets the current game time. * * @return the current game time in milliseconds since unix epoch. */ public long getTime() { long delta = new Date().getTime() - offset; return ((long) ((double) delta * multiplier)) + STARTTIME; } /** * Gets the current game time. * * @return the current game time as a Date object. */ public Date getDate() { return new Date(this.getTime()); } /** * Changes the multiplier and recalculate the offset in such a fashion that * the time does not jump. * * @param multiplier * the new multiplier to apply */ public void setMultiplier(double multiplier) { // recalculate offset this.offset = (long) (( ( new Date().getTime() * (multiplier - this.multiplier)) + this.offset * this.multiplier) / multiplier); this.multiplier = multiplier; } /** * set the current in game time to the date passed * * @param date * the new in game time as a Date object */ public void setTime(Date date) { setTime(date.getTime()); } /** * set the current in game time to the date passed * * @param date * the new in game time in milliseconds since unix epoch */ public void setTime(long time) { this.offset = new Date().getTime() - (long) ((time - STARTTIME) / multiplier); } /** * This makes the clock skip a complete day. */ public void skipDay() { this.setTime(this.getTime()+MSECONDSADAY); } }
package com.example.contactapp; import android.Manifest; import android.app.ProgressDialog; import android.content.ContentProviderClient; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Parcelable; import android.os.RemoteException; import android.provider.ContactsContract; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import MyAdapters.Myadapter; import model_list.ListItem_contacts; public class MainActivity extends AppCompatActivity { private List<ListItem_contacts> listing; private Myadapter adapter; private RecyclerView recyclerView; int count = 0; Parcelable state; EditText search; ImageView clear; private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100; private static ProgressDialog pd; @RequiresApi(api = Build.VERSION_CODES.O) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); search = findViewById(R.id.search_contact); clear = findViewById(R.id.clear_text); recyclerView = findViewById(R.id.contact_recycle_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); listing = new ArrayList<>(); fetch_contact(); clear.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { search.setText(""); } }); search.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { // filter your list from your input filter(s.toString()); //you can use runnable postDelayed like 500 ms to delay search text } }); } @Override public void onBackPressed() { Intent a = new Intent(Intent.ACTION_MAIN); a.addCategory(Intent.CATEGORY_HOME); a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(a); } @Override protected void onResume() { super.onResume(); listing = getContacts(); adapter = new Myadapter(listing, MainActivity.this); recyclerView.setAdapter(adapter); if (state != null) { recyclerView.getLayoutManager().onRestoreInstanceState(state); } search.setText(""); } @Override protected void onPause() { state = ((LinearLayoutManager) recyclerView.getLayoutManager()).onSaveInstanceState(); super.onPause(); } public void fetch_contact() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS); } else { new LoadContacts().execute(); } } public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { new LoadContacts().execute(); } else { Toast.makeText(this, "Please allow permission", Toast.LENGTH_SHORT).show(); } } } public class LoadContacts extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { listing = getContacts(); count = listing.size(); return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); if (listing != null && listing.size() > 0) { adapter = null; if (adapter == null) { adapter = new Myadapter(listing, MainActivity.this); recyclerView.setAdapter(adapter); } adapter.notifyDataSetChanged(); } else { Toast.makeText(MainActivity.this, "There are no contacts.", Toast.LENGTH_LONG).show(); } } @Override protected void onPreExecute() { super.onPreExecute(); } } public ArrayList<ListItem_contacts> getContacts() { ArrayList<ListItem_contacts> contactList = new ArrayList<ListItem_contacts>(); ContentResolver cResolver = this.getContentResolver(); ContentProviderClient mCProviderClient = cResolver.acquireContentProviderClient(ContactsContract.Contacts.CONTENT_URI); try { Cursor mCursor = mCProviderClient.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); if (mCursor != null && mCursor.getCount() > 0) { mCursor.moveToFirst(); while (!mCursor.isLast()) { Uri img_uri; String displayName = mCursor.getString(mCursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)); String id = mCursor.getString(mCursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID)); Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Integer.parseInt(id)); img_uri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY); contactList.add(new ListItem_contacts(displayName, id, img_uri)); mCursor.moveToNext(); } if (mCursor.isLast()) { Uri img_uri; String displayName = mCursor.getString(mCursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)); String id = mCursor.getString(mCursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID)); Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Integer.parseInt(id)); img_uri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY); contactList.add(new ListItem_contacts(displayName, id, img_uri)); } } mCursor.close(); } catch (RemoteException e) { e.printStackTrace(); contactList = null; } catch (Exception e) { e.printStackTrace(); contactList = null; } return contactList; } void filter(String text){ List<ListItem_contacts> temp = new ArrayList(); for(ListItem_contacts i: listing){ //or use .equal(text) with you want equal match //use .toLowerCase() for better matches if(i.getName().toLowerCase().contains(text.toLowerCase())){ temp.add(i); } } adapter = new Myadapter(temp, MainActivity.this); recyclerView.setAdapter(adapter); } }
package Recursion; import java.util.Scanner; public class Fibbonaci { static int fib(int n){ if(n==1) return 0; if(n==2) return 1; return fib(n-1)+fib(n-2); } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter the value of n "); int n = in.nextInt(); System.out.println(fib(n)); in.close(); } }
package adcar.com.network; import com.android.volley.AuthFailureError; import com.android.volley.DefaultRetryPolicy; import com.android.volley.NetworkResponse; import com.android.volley.Response; import com.android.volley.toolbox.StringRequest; import java.util.Collections; import java.util.Map; /** * Created by amitb on 02/02/16. */ public class CustomStringRequest extends StringRequest { private int mStatusCode; private Map<String, String> headerParams = null; private Map<String, String> bodyParams = null; public CustomStringRequest(int method, Map<String, String> headerParams, Map<String, String> bodyParams, String url, Response.Listener<String> listener, Response.ErrorListener errorListener) { super(method, url, listener, errorListener); this.headerParams = headerParams; this.bodyParams = bodyParams; this.setRetryPolicy(new DefaultRetryPolicy( 60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); } public CustomStringRequest(int method, String url, Response.Listener<String> listener, Response.ErrorListener errorListener) { super(method, url, listener, errorListener); this.setRetryPolicy(new DefaultRetryPolicy( 60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); } public int getStatusCode() { return mStatusCode; } @Override protected Map<String, String> getParams() throws AuthFailureError { if(bodyParams == null || bodyParams.equals(Collections.emptyMap())) { return super.getParams(); } return bodyParams; } @Override protected Response<String> parseNetworkResponse(NetworkResponse response) { mStatusCode = response.statusCode; return super.parseNetworkResponse(response); } }
package observe.weather.self.subject; import observe.weather.self.observer.Observer; /** * 主题接口 * * @author 金聖聰 * @version v1.0 * @email jinshengcong@163.com */ public interface Subject { /** * 注册观察者 * @param observer 需要注册的观察者 * @return void * @author 金聖聰 * @email jinshengcong@163.com * @version v1.0 * @date 2021/01/25 23:32 */ void registerObserver(Observer observer); /** * 移除观察者 * @param observer 需要移除的观察者 * @return void * @author 金聖聰 * @email jinshengcong@163.com * @version v1.0 * @date 2021/01/25 23:32 */ void removeObserver(Observer observer); /** * 当主题改变时,通知所有的观察者 * * @return void * @author 金聖聰 * @email jinshengcong@163.com * @version v1.0 * @date 2021/01/25 23:24 */ void notifyObservers(); }
package com.lemo.cmx.guanchazhe; /** * Created by 罗选通 on 2017/9/13. */ public class Client { public static void main(String[] args) { Subject subject=new SubjectImpl(); //创建微信用户 OBserver observer=new ObServerImpl("杨影枫"); OBserver observer2=new ObServerImpl("月眉儿"); OBserver observer3=new ObServerImpl("紫轩"); //订阅公众号 subject.registerObserver(observer); subject.registerObserver(observer2); subject.registerObserver(observer3); //公众号更新发出消息给订阅的微信用户 subject.notifyObservers(); } }
package use_collection.use_map; public class UseWeakHashMap { }
package com.bozuko.bozuko.map; import com.google.android.maps.GeoPoint; import com.google.android.maps.OverlayItem; public class MapItem extends OverlayItem{ GeoPoint mPoint; String mTitle; String mSnippet; Object mapObject; public MapItem(GeoPoint point, String title, String snippet) { super(point, title, snippet); mPoint = point; mTitle = title; mSnippet = snippet; // TODO Auto-generated constructor stub } public void update(GeoPoint p, String title, String subtitle) { // TODO Auto-generated method stub mPoint = p; mTitle = title; mSnippet = subtitle; } public void setObject(Object inObject){ mapObject = inObject; } public Object getObject(){ return mapObject; } }
package com.invillia.acme.persistence; import com.invillia.acme.persistence.entity.Order; import org.springframework.data.repository.PagingAndSortingRepository; public interface OrderRepository extends PagingAndSortingRepository<Order, Long> { }
package com.example.tarena.protop.fragment; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.chad.library.adapter.base.BaseQuickAdapter; import com.example.tarena.protop.Bean.News; import com.example.tarena.protop.R; import com.example.tarena.protop.adapter.MyBaseAdapterDecoration; import com.example.tarena.protop.adapter.MyBaseRecycleAdapter; import com.example.tarena.protop.biz.NewsBiz; import com.example.tarena.protop.listener.RefreshListener; import com.example.tarena.protop.listener.onLoadFirstAsyncFinished; import com.example.tarena.protop.util.LoadFirstAsyncTask; import com.example.tarena.protop.view.NewsInfoActivity; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * A simple {@link Fragment} subclass. */ public class WebFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener, BaseQuickAdapter.OnRecyclerViewItemClickListener { MyBaseRecycleAdapter adapter; SwipeRefreshLayout srl; RecyclerView recyclerView; int page=1;//初始数据 NewsBiz biz; List<News> list; View view; View header; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view =inflater.inflate(R.layout.fragment_web,container,false); header = inflater.inflate(R.layout.load_header,null); biz=new NewsBiz(getActivity()); initView(view); return view; } Handler handler = new Handler(Looper.getMainLooper()); //初始化View private void initView(View view) { //初始化SwipeRefreshLayout 并设置下拉刷新 srl= (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh); srl.setOnRefreshListener(this); //设置下拉刷新的条的颜色 srl.setColorSchemeColors(Color.parseColor("#00BCD4")); //初始化recycleView recyclerView= (RecyclerView) view.findViewById(R.id.web_recycler_view); // 设置固定大小 recyclerView.setHasFixedSize(true); //初始化LayoutManager recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); //初始化BaseRecycleAdapter adapter = new MyBaseRecycleAdapter(getActivity(),new ArrayList<News>()); adapter.setOnRecyclerViewItemClickListener(this); //开启动画 adapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT); //设置动画是否出现一次 // adapter.isFirstOnly(false); //设置加载更多 // adapter.setOnLoadMoreListener(this); //开启触发加载更多 // adapter.openLoadMore(10,true); //设置分割线 recyclerView.addItemDecoration(new MyBaseAdapterDecoration(getActivity(),MyBaseAdapterDecoration.VERTICAL_LIST)); //给recyclerView设置adapter recyclerView.setAdapter(adapter); } public MyBaseRecycleAdapter getNewAdapter() { MyBaseRecycleAdapter adapter = new MyBaseRecycleAdapter(getActivity(), new ArrayList<News>()); adapter.setOnRecyclerViewItemClickListener(this); //开启动画 adapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT); //设置加载更多 // adapter.setOnLoadMoreListener(this); //开启触发加载更多 // adapter.openLoadMore(10, true); //设置分割线 recyclerView.addItemDecoration(new MyBaseAdapterDecoration(getActivity(), MyBaseAdapterDecoration.VERTICAL_LIST)); //给recyclerView设置adapter recyclerView.setAdapter(adapter); return adapter; } RecyclerView.LayoutParams params=new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); @Override public void onResume() { super.onResume(); //先检查数据中有没有数据 //如果数据库中有数据 直接加载数据中的数据 不更新数据库 如果没有先更新数据库 try{ list=biz.getNewsFromDB("tb_web"); if(list.size()<=1){ Log.i("TAG", "onResume: " + "更新数据库" + list.size()); final ImageView img = (ImageView) header.findViewById(R.id.iv_load); final TextView tv_touch= (TextView) header.findViewById(R.id.tv_touch); tv_touch.setText("轻触更新数据"); final RotateAnimation loadAnim = new RotateAnimation(0,360, Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f); loadAnim.setDuration(1000); //设置重复模式 无限 loadAnim.setRepeatCount(Animation.INFINITE); //设置加速器,添加一个匀速插值器 让旋转匀速 loadAnim.setInterpolator(new LinearInterpolator()); //添加头部这句话必须要设 要不不居中 header.setLayoutParams(params); adapter=getNewAdapter(); adapter.addHeaderView(header); recyclerView.setAdapter(adapter); header.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //启动动画 tv_touch.setText("正在更新数据中,请稍后....."); img.startAnimation(loadAnim); updateDB(); } }); }else{ Log.i("TAG", "onResume: " + "没有更新数据库" + list.size()); adapter.setNewData(list); } }catch (Exception e){ updateDB(); } } /** * 更新数据库 */ public void updateDB(){ //启动异步任务更新数据到数据库 new Thread(){ @Override public void run() { LoadFirstAsyncTask task = new LoadFirstAsyncTask(getActivity(),new onLoadFirstAsyncFinished(){ @Override public void finish() { adapter=getNewAdapter(); recyclerView.setAdapter(adapter); Log.i("TAG", "web------------------"); list=biz.getNewsFromDB("tb_web"); Log.i("TAG", "finish: 现在数据库大小" + list.size()); adapter.setNewData(list); } }); task.execute("前端"); } }.start(); } /** * 下拉刷新 * 刷新完弹出通知 */ @Override public void onRefresh() { final int refreshOldNum=list.size(); if(refreshOldNum==0){srl.setRefreshing(false); return;} //标记最新日期 String listnew= String.valueOf(new SimpleDateFormat("yyyy-MM-dd").format(new Date(Long.valueOf(list.get(0).getPublishedAt())))); long listTime=Long.valueOf(list.get(0).getPublishedAt()); long currenTime =new Date().getTime(); int count = (int) ((currenTime-listTime)/86400000+1); for(int i =0;i<=count;i++){ String[] temp= String.valueOf(new SimpleDateFormat("yyyy-MM-dd").format(new Date(listTime))).split("-"); final long finalListTime = listTime; biz.getNewsFromNetNew("前端",temp[0], temp[1],temp[2], new RefreshListener() { @Override public void refreshFinish(List<News> nlist) { if(nlist!=null) { int num=0; for (News n : nlist) { if(Long.valueOf(n.getPublishedAt())> finalListTime){ list.add(0, n); num++; biz.addRefreshToDB("tb_web", n); } } // Toast.makeText(getActivity(), "发现了" + nlist.size() + "篇新文章", Toast.LENGTH_SHORT).show(); Log.i("TAG", "发现了" + num + "篇新文章"); srl.setRefreshing(false); }else{ Toast.makeText(getActivity(), "服务器链接失败,请检查网络稍后重试", Toast.LENGTH_SHORT).show(); srl.setRefreshing(false); } adapter.setNewData(list); } }); listTime+=86400000; } } /** * 点击跳转到浏览器页面 * @param view * @param i */ @Override public void onItemClick(View view, int i) { //更新数据库状态 已阅读过此篇文章 /* try{ //更新数据库的阅读状态 int num= biz.updateRead("tb_web", list.get(i).getUrl()); //更新已浏览的文章的表(判断是否曾经浏览过,不能重复添加) if(!list.get(i).isRead()){ long num2 = biz.updateReadTable("tb_read", list.get(i)); } if(num>0){ //Toast.makeText(getActivity(),"数据更新成功",Toast.LENGTH_LONG).show(); }else{ // Toast.makeText(getActivity(),"数据更新失败,没有查到这对应数据!",Toast.LENGTH_LONG).show(); } }catch (Exception e ){ Toast.makeText(getActivity(),"数据更新遇到异常!!!!",Toast.LENGTH_LONG).show(); e.printStackTrace(); } //更新list list.get(i).setRead(true); //更新界面 adapter.setNewData(list);*/ //跳转页面 Intent intent = new Intent(getActivity(), NewsInfoActivity.class); intent.putExtra("news",list.get(i)); startActivity(intent); } @Override public void onLoadMoreRequested() { } }
package Graphic.editor; import java.awt.*; import java.awt.event.*; import java.util.ArrayList; import javax.swing.*; import javax.swing.event.*; import java.awt.MouseInfo; import java.awt.Frame; import java.awt.Label; import java.awt.Panel; import java.awt.TextArea; import java.awt.TextField; public class Project2 extends JFrame { JPanel gui_panel, paint_panel; // 현 그림판 프레임은 GUI구성 패널, 그려지는 패널로 구성 JTextField txt = new JTextField() ; ArrayList<Info> nextline = new ArrayList<Info>(); ArrayList<Info> line = new ArrayList<Info>(); ArrayList<String> nextmode = new ArrayList<String>(); ArrayList<Info> next = new ArrayList<Info>(); ArrayList<Info> location = new ArrayList<Info>(); ArrayList<String> Mo = new ArrayList<String>(); JButton P; JButton N; JButton Polyline; JButton heart; JButton pencil_bt, eraser_bt; // 연필,지우개 도구를 선택하는 버튼 JButton colorSelect_bt; // 색선택 버튼 JButton rec_bt; // 사각형 버튼 JButton circle_bt; // 원 버튼 String mode= " "; boolean isFirst = true; JButton RubberBand; JButton Pointer; JButton Text; JButton plus; JButton minus; JButton fill; JLabel thicknessInfo_label, label; // 도구굵기 라벨 JTextField thicknessControl_tf; // 도구굵기가 정해질 텍스트필드 Color selectedColor; // 현 변수에 컬러가 저장되어 추후에 펜색상을 정해주는 변수의 매개변수로 사용된다. Graphics graphics; // Graphics2D 클래스의 사용을 위해 선언 Graphics2D g; // Graphics2D는 쉽게 말해 기존 graphics의 상위버전이라고 생각하시먄 됩니다. int thickness = 10; // 현 변수는 그려지는 선의 굵기를 변경할때 변경값이 저장되는 변수 int startX; // 마우스클릭시작의 X좌표값이 저장될 변수 int startY; // 마우스클릭시작의 Y좌표값이 저장될 변수 int endX; // 마우스클릭종료의 X좌표값이 저장될 변수 int endY; // 마우스클릭종료의 Y좌표값이 저장될 변수 int a,b,c,d=0; int i=0; boolean tf = false; /* 변 boolean 변수는 처음에 연필로 그리고 지우개로 지운다음 다시 연필로 그릴때 * 기본색인 검은색으로 구분시키고 만약 프로그램 시작시 색선택후 그 선택된 색이 * 지우개로 지우고 다시 연필로 그릴때 미리 정해진 색상으로 구분하는 변수인데.. * 뭐 그리 중요한 변수는 아니다.. */ class Info{ int x1, x2 ,y1, y2; Info(int x1,int y1 ,int x2, int y2){ this.x1 = x1; this.x2 = x2; this.y1 = y1; this.y2 = y2; } } public Project2() { // Paint클래스의 디폴트(Default)생성자로 기본적인 GUI구성을 해주는 역할을 한다. setLayout(null); // 기본 프레임의 레이아웃을 초기화 시켜 패널을 개발자가 직접 다룰수 있게 됨 setTitle("DrawingBoard"); // 프레임 타이틀 지정 setSize(900,750); // 프레임 사이즈 지정 setLocationRelativeTo(null); // 프로그램 실행시 화면 중앙에 출력 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 프레임 우측상단에 X버튼을 눌렀을떄의 기능 정의 gui_panel = new JPanel(); // 프레임 상단에 버튼, 텍스트필드, 라벨등이 UI가 들어갈 패널 gui_panel.setBackground(Color.GRAY); // 패널의 배경색을 회색으로 지정 gui_panel.setLayout(null); // gui_panel의 레이아웃을 null지정하여 컴포넌트들의 위치를 직접 지정해줄수 있다. fill=new JButton("fill"); fill.setFont(new Font("맑은 고딕", Font.BOLD, 20)); // 버튼 폰트및 글씨 크기 지정 fill.setBackground(Color.LIGHT_GRAY); // 연필버튼 배경색 밝은회색으로 지정 Text=new JButton("Text"); Text.setFont(new Font("맑은 고딕", Font.BOLD, 20)); // 버튼 폰트및 글씨 크기 지정 Text.setBackground(Color.LIGHT_GRAY); // 연필버튼 배경색 밝은회색으로 지정 Pointer=new JButton("Pointer"); Pointer.setFont(new Font("맑은 고딕", Font.BOLD, 13)); // 버튼 폰트및 글씨 크기 지정 Pointer.setBackground(Color.LIGHT_GRAY); // 연필버튼 배경색 밝은회색으로 지정 RubberBand=new JButton("Rubber Band"); RubberBand.setFont(new Font("맑은 고딕", Font.BOLD, 10)); // 버튼 폰트및 글씨 크기 지정 RubberBand.setBackground(Color.LIGHT_GRAY); // 연필버튼 배경색 밝은회색으로 지정 N=new JButton("👉"); N.setFont(new Font("함초롱돋움", Font.BOLD, 30)); // 버튼 폰트및 글씨 크기 지정 N.setBackground(Color.LIGHT_GRAY); // 연필버튼 배경색 밝은회색으로 지정 P=new JButton("👈"); P.setFont(new Font("함초롱돋움", Font.BOLD, 30)); // 버튼 폰트및 글씨 크기 지정 P.setBackground(Color.LIGHT_GRAY); // 연필버튼 배경색 밝은회색으로 지정 Polyline=new JButton("Polyline"); Polyline.setFont(new Font("함초롱돋움", Font.BOLD, 13)); // 버튼 폰트및 글씨 크기 지정 Polyline.setBackground(Color.LIGHT_GRAY); // 연필버튼 배경색 밝은회색으로 지정 heart=new JButton("♥"); heart.setFont(new Font("함초롱돋움", Font.BOLD, 40)); // 버튼 폰트및 글씨 크기 지정 heart.setBackground(Color.LIGHT_GRAY); // 연필버튼 배경색 밝은회색으로 지정 circle_bt=new JButton("○/⏺"); // 원 버튼 생성 circle_bt.setFont(new Font("함초롱돋움", Font.BOLD, 26)); // 버튼 폰트및 글씨 크기 지정 circle_bt.setBackground(Color.LIGHT_GRAY); // 연필버튼 배경색 밝은회색으로 지정 rec_bt=new JButton("□/⏹"); // 사각형 버튼 생성 rec_bt.setFont(new Font("함초롱돋움", Font.BOLD, 26)); // 버튼 폰트및 글씨 크기 지정 rec_bt.setBackground(Color.LIGHT_GRAY); // 연필버튼 배경색 밝은회색으로 지정 pencil_bt = new JButton("✏"); // 연필 버튼 생성 pencil_bt.setFont(new Font("함초롱돋움", Font.BOLD, 30)); // 버튼 폰트및 글씨 크기 지정 pencil_bt.setBackground(Color.LIGHT_GRAY); // 연필버튼 배경색 밝은회색으로 지정 eraser_bt = new JButton("Eraser"); // 지우개 버튼 생성 eraser_bt.setFont(new Font("함초롱돋움", Font.BOLD, 17)); // 버튼 폰트및 글씨 크기 지정 eraser_bt.setBackground(Color.LIGHT_GRAY); // 지우개 버튼 배경색 희색으로 지정 colorSelect_bt = new JButton("🎨"); // 선색상 버튼 생성 colorSelect_bt.setBackground(Color.LIGHT_GRAY); // 선색상 버튼 배경색 분홍색으로 지정 colorSelect_bt.setFont(new Font("함초롱돋움", Font.BOLD, 30)); thicknessInfo_label = new JLabel("도구굵기"); // 도구굴기 라벨 지정 / 밑에서 나올 텍스트필드의 역할을 설명 thicknessInfo_label.setFont(new Font("함초롬돋움", Font.BOLD, 12)); // 도구굵기 라벨 폰트및 글씨 크기 지정 thicknessControl_tf = new JTextField("6", 5); // 도구굵기 입력 텍스트필드 생성 thicknessControl_tf.setHorizontalAlignment(JTextField.CENTER); // 텍스트필드 라인에 띄어지는 텍스트 중앙 정렬 thicknessControl_tf.setFont(new Font("궁서체", Font.PLAIN, 25)); // 텍스트필드 X길이 및 폰트 지정 label = new JLabel("원하는 도구를 선택하세요."); label.setFont(new Font("맑은고딕", Font.BOLD, 14)); label.setForeground(Color.WHITE); fill.setBounds(525,75,80,40); Text.setBounds(610,75,80,40); Pointer.setBounds(695,75,80,40); RubberBand.setBounds(780,70,100,45); N.setBounds(650,10,65,55); P.setBounds(580,10,65,55); Polyline.setBounds(485,10,90,55); heart.setBounds(390,10,90,55); circle_bt.setBounds(295,10,90,55); rec_bt.setBounds(200,10,90,55); // 사각형 버튼 위치 지정 pencil_bt.setBounds(10,10,90,55); // 연필 버튼 위치 지정 eraser_bt.setBounds(105,10,90,55); // 지우개 버튼 위치 지정 colorSelect_bt.setBounds(785,10,90,55); // 선색상 버튼 위치 지정 thicknessInfo_label.setBounds(723,36,50,55); // 도구굵기 라벨 위치 지정 thicknessControl_tf.setBounds(723,15,50,35); // 도구굵기 텍스트필드 위치 지정 label.setBounds(20,37,900,115); gui_panel.add(fill); gui_panel.add(Text); gui_panel.add(Pointer); gui_panel.add(RubberBand); gui_panel.add(N); gui_panel.add(P); gui_panel.add(Polyline); gui_panel.add(heart); gui_panel.add(circle_bt); // gui_panel에 원 버튼 추가 gui_panel.add(rec_bt); // gui_panel에 사각형 버튼 추가 gui_panel.add(pencil_bt); // gui_panel에 연필 버튼 추가 gui_panel.add(eraser_bt); // gui_panel에 지우개 버튼 추가 gui_panel.add(colorSelect_bt); // gui_panel에 선색상 버튼 추가 gui_panel.add(thicknessInfo_label); // gui_panel에 도구굵기 라벨 추가 gui_panel.add(thicknessControl_tf); // gui_panel에 도구굵기 텍스트필드 추가 gui_panel.add(label); gui_panel.setBounds(0,0,900,120); // gui_panel이 프레임에 배치될 위치 지정 ////////////////////////////////////////////////// ↑ 패널 구분 ↓ paint_panel = new JPanel(); // 그림이 그려질 패널 생성 paint_panel.setBackground(Color.WHITE); // 패널의 배경색 하얀색 paint_panel.setLayout(null); // paint_panel의 레이아웃을 null해줘 패널 자체를 setBounds로 위치를 조정할수 있다. paint_panel.setBounds(0,120,900,620); // paint_panel의 위치 조정 add(gui_panel); // 메인프레임에 gui패널 추가 - 위치는 위에서 다 정해줌 add(paint_panel); // 메인프레임에 paint패널 추가 - 위치는 위에서 다 정해줌 setVisible(true); // 메인프레임을 보이게 한다. graphics = paint_panel.getGraphics(); // 그래픽초기화 g = (Graphics2D)graphics; // 기존의 graphics변수를 Graphics2D로 변환후 Graphics2D에 초기화 // 일반적인 Graphics가 아닌 Graphics2D를 사용한 이유는 펜의 굴기와 관련된 기능을 //수행하기 위하여 Graphics2D 클래스를 객체화함 g.setColor(selectedColor); // 그려질 선(=선도 그래픽)의 색상을 selectedColor의 값으로 설정 /////////////////////////////////////////////////// ↓ 액션 처리부분 // 그림 그리는 패널 paint_panel.addMouseListener(new MouseListener() { // paint_panel에서의 MouseListener 이벤트 처리 public void mousePressed(MouseEvent e) { // paint_panel에 마우스 눌림의 액션이 있을떄 밑 메소드 실행 if(mode.equals("Polyline")&&isFirst==true) { startX = endX = e.getX(); // 마우스가 눌렸을때 그때의 X좌표값으로 초기화 startY = endY = e.getY(); // 마우스가 눌렸을때 그때의 Y좌표값으로 초기화 isFirst = false; } else { startX = e.getX(); // 마우스가 눌렸을때 그때의 X좌표값으로 초기화 startY = e.getY(); // 마우스가 눌렸을때 그때의 Y좌표값으로 초기화 } if(mode.equals("Polyline")) paint(); } public void mouseClicked(MouseEvent e) { int a = e.getX(); int b = e.getY(); if(mode.equals("fill")) { for(int i=0;i<Mo.size();i++) { if(Mo.get(i).equals("rectangle")) { if(( a>location.get(i).x1 ) && ( b>location.get(i).y1 ) && ( a < location.get(i).x2+location.get(i).x1) && ( b<location.get(i).y2+location.get(i).y1) ) { g.setColor(selectedColor); // 그려지는 색상을 selectedColor변수의 값으로 지정 g.fillRect(location.get(i).x1, location.get(i).y1, location.get(i).x2, location.get(i).y2); } } } } } // 클릭이벤트 처리 public void mouseEntered(MouseEvent e) { } // paint_panel범위 내에 진입시 이벤트 처리 public void mouseExited(MouseEvent e) { } public void mouseReleased(MouseEvent e) { endX=e.getX(); endY=e.getY(); paint(); if (mode.equals("RubberBand")){ g.drawLine(startX, startY, endX, endY); a=startX; b=startY; c=endX; d=endY; location.add(new Info(a,b,c,d)); Mo.add("RubberBand"); } } public void mouseMoved(MouseEvent e) { } }); // 전체 지우기 class MyMouse extends MouseAdapter { public void mousePressed(MouseEvent e) { if (e.getClickCount() == 2) { g.fillRect(0,0,900,2000); isFirst = true; label.setText("모두 지우기"); } else if (e.getClickCount() == 1) { label.setText("지우개 툴을 선택하셨습니다."); } } } // 사각형 채우기 class Rec extends MouseAdapter { public void mousePressed(MouseEvent e) { if (e.getClickCount() == 2) { g.fillRect(a,b,c,d); mode="fillRect"; Mo.add("fillRect"); location.add(new Info(a,b,c,d)); nextmode.add("fillRect"); next.add(new Info(a,b,c,d)); label.setText("사각형 채우기"); } else if(e.getClickCount() == 1) { label.setText("사각형 툴을 선택하셨습니다."); } } } // 원 채우기 class Cir extends MouseAdapter { public void mousePressed(MouseEvent e) { if (e.getClickCount() == 2) { g.fillOval(a,b,c,d); mode="fillCir"; Mo.add("fillCir"); location.add(new Info(a,b,c,d)); nextmode.add("fillCir"); next.add(new Info(a,b,c,d)); label.setText("원 채우기"); } else if(e.getClickCount() == 1) { label.setText("원 툴을 선택하셨습니다."); } } } // P 버튼 class Pre extends MouseAdapter { public void mousePressed(MouseEvent e) { label.setText("이전"); if (Mo.get(Mo.size()-1).equals("rectangle")) { int x1 = location.get(location.size()-1).x1; int y1 = location.get(location.size()-1).y1; int x2= location.get(location.size()-1).x2; int y2 = location.get(location.size()-1).y2; g.setColor(Color.WHITE); g.drawRect(x1,y1,x2,y2); nextmode.add("rectangle"); next.add(new Info(x1,y1,x2,y2)); location.remove(location.size()-1); Mo.remove(Mo.size()-1); } else if (Mo.get(Mo.size()-1).equals("circle")) { int x1 = location.get(location.size()-1).x1; int y1 = location.get(location.size()-1).y1; int x2= location.get(location.size()-1).x2; int y2 = location.get(location.size()-1).y2; g.setColor(Color.WHITE); g.drawOval(x1,y1,x2,y2); nextmode.add("circle"); next.add(new Info(x1,y1,x2,y2)); location.remove(location.size()-1); Mo.remove(Mo.size()-1); } else if (Mo.get(Mo.size()-1).equals("heart")) { int x1 = location.get(location.size()-1).x1; int y1 = location.get(location.size()-1).y1; int x2= location.get(location.size()-1).x2; int y2 = location.get(location.size()-1).y2; g.setColor(Color.WHITE); g.drawString("♥", x1, y1); nextmode.add("heart"); next.add(new Info(x1,y1,x2,y2)); location.remove(location.size()-1); Mo.remove(Mo.size()-1); } else if(Mo.get(Mo.size()-1).equals("fillRect")) { int x1 = location.get(location.size()-1).x1; int y1 = location.get(location.size()-1).y1; int x2= location.get(location.size()-1).x2; int y2 = location.get(location.size()-1).y2; g.setColor(Color.WHITE); g.fillRect(x1,y1,x2,y2); nextmode.add("fillRect"); next.add(new Info(x1,y1,x2,y2)); location.remove(location.size()-1); Mo.remove(Mo.size()-1); } else if(Mo.get(Mo.size()-1).equals("fillCir")) { int x1 = location.get(location.size()-1).x1; int y1 = location.get(location.size()-1).y1; int x2= location.get(location.size()-1).x2; int y2 = location.get(location.size()-1).y2; g.setColor(Color.WHITE); g.fillOval(x1,y1,x2,y2); nextmode.add("fillCir"); next.add(new Info(x1,y1,x2,y2)); location.remove(location.size()-1); Mo.remove(Mo.size()-1); } else if(Mo.get(Mo.size()-1).equals("RubberBand")) { int x1 = location.get(location.size()-1).x1; int y1 = location.get(location.size()-1).y1; int x2= location.get(location.size()-1).x2; int y2 = location.get(location.size()-1).y2; g.setColor(Color.WHITE); g.drawLine(x1, y1, x2, y2); nextmode.add("RubberBand"); next.add(new Info(x1,y1,x2,y2)); location.remove(location.size()-1); Mo.remove(Mo.size()-1); } else if(Mo.get(Mo.size()-1).equals("Text")) { txt.setVisible(false); nextmode.add("Text"); Mo.remove(Mo.size()-1); } else if(Mo.get(Mo.size()-1).equals("pencil")) { for(i=0;i<line.size();i++) { int x1 = line.get(i).x1; int y1 = line.get(i).y1; int x2= line.get(i).x2; int y2 = line.get(i).y2; g.setColor(Color.WHITE); g.drawLine(x1, y1, x2, y2); } nextmode.add("pencil"); Mo.remove(Mo.size()-1); } } } // N 버튼 class Nex extends MouseAdapter{ public void mousePressed(MouseEvent e) { label.setText("되돌리기"); if (nextmode.get(nextmode.size()-1).equals("rectangle")) { int x = next.get(next.size()-1).x1; int y = next.get(next.size()-1).y1; int z= next.get(next.size()-1).x2; int w = next.get(next.size()-1).y2; g.setColor(Color.BLACK); g.drawRect(x,y,z,w); next.remove(next.size()-1); nextmode.remove(nextmode.size()-1); i++; Mo.add("rectangle"); a=x; b=y; c=z; d=w; location.add(new Info(a,b,c,d)); } else if(nextmode.get(nextmode.size()-1).equals("circle")) { int x = next.get(next.size()-1).x1; int y = next.get(next.size()-1).y1; int z= next.get(next.size()-1).x2; int w = next.get(next.size()-1).y2; g.setColor(Color.BLACK); g.drawOval(x,y,z,w); next.remove(next.size()-1); nextmode.remove(nextmode.size()-1); i++; Mo.add("circle"); a=x; b=y; c=z; d=w; location.add(new Info(a,b,c,d)); } else if(nextmode.get(nextmode.size()-1).equals("heart")) { int x = next.get(next.size()-1).x1; int y = next.get(next.size()-1).y1; int z= next.get(next.size()-1).x2; int w = next.get(next.size()-1).y2; g.setColor(Color.BLACK); g.drawString("♥", x, y); next.remove(next.size()-1); nextmode.remove(nextmode.size()-1); i++; Mo.add("heart"); a=x; b=y; c=z; d=w; location.add(new Info(a,b,c,d)); } else if(nextmode.get(nextmode.size()-1).equals("fillRect")) { int x = next.get(next.size()-1).x1; int y = next.get(next.size()-1).y1; int z= next.get(next.size()-1).x2; int w = next.get(next.size()-1).y2; g.setColor(Color.BLACK); g.fillRect(x,y,z,w); next.remove(next.size()-1); nextmode.remove(nextmode.size()-1); i++; Mo.add("fillRect"); a=x; b=y; c=z; d=w; location.add(new Info(a,b,c,d)); } else if(nextmode.get(nextmode.size()-1).equals("fillCir")) { int x = next.get(next.size()-1).x1; int y = next.get(next.size()-1).y1; int z= next.get(next.size()-1).x2; int w = next.get(next.size()-1).y2; g.setColor(Color.BLACK); g.fillOval(x,y,z,w); next.remove(next.size()-1); nextmode.remove(nextmode.size()-1); i++; Mo.add("fillCir"); a=x; b=y; c=z; d=w; location.add(new Info(a,b,c,d)); } else if(nextmode.get(nextmode.size()-1).equals("RubberBand")) { int x = next.get(next.size()-1).x1; int y = next.get(next.size()-1).y1; int z= next.get(next.size()-1).x2; int w = next.get(next.size()-1).y2; g.setColor(Color.BLACK); g.drawLine(x, y, z, w); next.remove(next.size()-1); nextmode.remove(nextmode.size()-1); i++; Mo.add("RubberBand"); a=x; b=y; c=z; d=w; location.add(new Info(a,b,c,d)); } else if(nextmode.get(nextmode.size()-1).equals("Text")) { txt.setVisible(true); nextmode.remove(nextmode.size()-1); i++; Mo.add("Text"); } else if(nextmode.get(nextmode.size()-1).equals("pencil")) { for(i=0;i<line.size();i++) { int x1 = line.get(i).x1; int y1 = line.get(i).y1; int x2= line.get(i).x2; int y2 = line.get(i).y2; g.setColor(Color.BLACK); g.drawLine(x1, y1, x2, y2); } nextmode.remove(nextmode.size()-1); Mo.add("pencil"); } } } fill.addActionListener(new ToolActionListener()); Text.addActionListener(new ToolActionListener()); Pointer.addActionListener(new ToolActionListener()); RubberBand.addActionListener(new ToolActionListener()); P.addMouseListener(new Pre()); P.addActionListener(new ToolActionListener()); N.addMouseListener(new Nex()); N.addActionListener(new ToolActionListener()); Polyline.addActionListener(new ToolActionListener()); heart.addActionListener(new ToolActionListener()); circle_bt.addActionListener(new ToolActionListener()); circle_bt.addMouseListener(new Cir()); rec_bt.addActionListener(new ToolActionListener()); rec_bt.addMouseListener(new Rec()); paint_panel.addMouseMotionListener(new PaintDraw()); // paint_panel에 마우스 모션리스너 추가 pencil_bt.addActionListener(new ToolActionListener()); // 연필버튼 액션처리 eraser_bt.addActionListener(new ToolActionListener()); // 지우개버튼 액션처리 eraser_bt.addMouseListener(new MyMouse()); colorSelect_bt.addActionListener(new ActionListener() { // 선색상버튼 액션처리를 익명클래스로 작성 public void actionPerformed(ActionEvent e) { // 오버라이딩 label.setText("색상변경"); tf = true; // 위에서 변수 설명을 했으므로 스킵.. JColorChooser chooser = new JColorChooser(); // JColorChooser 클래스객체화 selectedColor = chooser.showDialog(null, "Color", Color.ORANGE); // selectedColor에 선택된색으로 초기화 g.setColor(selectedColor); // 그려지는 펜의 색상을 selectedColor를 매개변수로 하여 지정 } }); } // paint 함수 public void paint() { if(mode.equals("rectangle")) { thickness = Integer.parseInt(thicknessControl_tf.getText()); g.setStroke(new BasicStroke(thickness, BasicStroke.CAP_ROUND,0)); //선굵기 if(tf == false) g.setColor(Color.BLACK); // 그려지는 색상을 검은색 지정 else { g.setColor(selectedColor); // 그려지는 색상을 selectedColor변수의 값으로 지정 } a=startX; b=startY; c=endX-startX; d=endY-startY; g.drawRect(startX, startY, endX-startX, endY-startY); Mo.add("rectangle"); location.add(new Info(a,b,c,d)); label.setText("사각형 그리는 중"); } else if(mode.equals("circle")) { thickness = Integer.parseInt(thicknessControl_tf.getText()); g.setStroke(new BasicStroke(thickness, BasicStroke.CAP_ROUND,0)); //선굵기 if(tf == false) g.setColor(Color.BLACK); // 그려지는 색상을 검은색 지정 else g.setColor(selectedColor); // 그려지는 색상을 selectedColor변수의 값으로 지정 a=startX; b=startY; c=endX-startX; d=endY-startY; g.drawOval(startX, startY, endX-startX, endY-startY); Mo.add("circle"); location.add(new Info(a,b,c,d)); label.setText("원 그리는 중"); } else if(mode.equals("heart")) { if(tf == false) g.setColor(Color.BLACK); // 그려지는 색상을 검은색 지정 else g.setColor(selectedColor); // 그려지는 색상을 selectedColor변수의 값으로 지정 g.setFont(new Font("함초롱돋움", Font.BOLD, 50)); a=startX; b=startY; c=endX; d=endY; g.drawString("♥", a, b); Mo.add("heart"); location.add(new Info(a,b,c,d)); label.setText("하트 스티커 사용 중"); } else if(mode.equals("Polyline")) { thickness = Integer.parseInt(thicknessControl_tf.getText()); g.setStroke(new BasicStroke(thickness, BasicStroke.CAP_ROUND,0)); //선굵기 if(tf == false) g.setColor(Color.BLACK); // 그려지는 색상을 검은색 지정 else g.setColor(selectedColor); // 그려지는 색상을 selectedColor변수의 값으로 지정 a=startX; b=startY; c=endX; d=endY; int xArray[]= {startX,endX}; int yArray[]= {startY,endY}; g.drawPolyline(xArray,yArray,2); label.setText("Polyline 그리는 중"); } else if(mode.equals("Text")) { Mo.add("Text"); paint_panel.add(txt); txt.setBounds(startX, startY, 100, 30); txt.setFont(new Font("굴림체", Font.BOLD, 15)); } } public class PaintDraw implements MouseMotionListener { // 위에서 paint_panel에 MouseMotionListener액션 처리가 될때 현 클래스로 넘어와서 밑 문장을 실행 @Override public void mouseDragged(MouseEvent e) { // paint_panel에서 마우스 드래그 액션이처리될떄 밑 메소드 실행 if(mode.equals("pencil")||mode.equals("e")) { thickness = Integer.parseInt(thicknessControl_tf.getText()); // 텍스트필드부분에서 값을 값고와 thickness변수에 대입 label.setText("그리는 중"); endX = e.getX(); endY = e.getY(); a=startX; b=startY; c=endX; d=endY; line.add(new Info(a,b,c,d)); g.setStroke(new BasicStroke(thickness, BasicStroke.CAP_ROUND,0)); //선굵기 g.drawLine(startX, startY, endX, endY); // 라인이 그려지게 되는부분 startX = endX; startY = endY; } else if (mode.equals("RubberBand")){ if(tf == false) g.setColor(Color.BLACK); // 그려지는 색상을 검은색 지정 else g.setColor(selectedColor); label.setText("RubberBand 그리는 중"); endX = e.getX(); endY = e.getY(); g.setStroke(new BasicStroke(thickness, BasicStroke.CAP_ROUND,0)); //선굵기 g.drawLine(startX, startY, endX, endY); // 라인이 그려지게 되는부분 repaint(); } } @Override public void mouseMoved(MouseEvent e) { if(mode.equals("Pointer")) { label.setText("Pointer"); PointerInfo a = MouseInfo.getPointerInfo(); Point b = a.getLocation(); int x = (int) b.getX(); int y = (int) b.getY(); g.drawString("●", x-330, y-190); g.setFont(new Font("맑은 고딕", Font.BOLD, 10)); if(tf == false) g.setColor(Color.RED); // 그려지는 색상을 검은색 지정 else g.setColor(selectedColor); repaint(); } } } public class ToolActionListener implements ActionListener { // 연필,지우개 버튼의 액션처리시 실행되는 클래스 public void actionPerformed(ActionEvent e) { // 오버라이딩된 actionPerformed메소드 실행 if(e.getSource() == pencil_bt) { // 연필버튼이 눌렸을떄 밑 if문장 블록범위내 문장 실행 mode="pencil"; Mo.add("pencil"); if(tf == false) g.setColor(Color.BLACK); // 그려지는 색상을 검은색 지정 else g.setColor(selectedColor); // 그려지는 색상을 selectedColor변수의 값으로 지정 label.setText("연필 툴을 선택하셨습니다."); } else if(e.getSource() == eraser_bt) { // 지우개버튼이 눌렸을떄 밑 if문장 블록범위내 문장 실행 mode="e"; g.setColor(Color.WHITE); } else if(e.getSource() == rec_bt) { mode="rectangle"; } else if(e.getSource() == circle_bt) { mode="circle"; } else if(e.getSource() == heart) { mode="heart"; label.setText("하트 스티커를 선택하셨습니다."); } else if(e.getSource() == Polyline) { mode="Polyline"; label.setText("Polyline 툴을 선택하셨습니다."); } else if(e.getSource() == RubberBand ) { mode="RubberBand"; label.setText("RubberBand 툴을 선택하셨습니다."); } else if(e.getSource() == Pointer ) { mode="Pointer"; label.setText("Pointer 툴을 선택하셨습니다."); } else if(e.getSource() == Text ) { mode="Text"; label.setText("Text 툴을 선택하셨습니다."); } else if(e.getSource() == fill ) { mode="fill"; label.setText("채우기 툴을 선택하셨습니다."); } } } public static void main(String[] args) { // 메인메소드 new Project2(); // Paint클래스의 디폴트(=Default)생성자 실행 } }
/* Ara - capture species and specimen data * * Copyright (C) 2009 INBio (Instituto Naciona de Biodiversidad) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.inbio.ara.persistence.taxonomy; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Embeddable; /** * * @author esmata */ @Embeddable public class TaxonDescriptionRecordReferencePK implements Serializable { @Basic(optional = false) @Column(name = "taxon_description_record_id") private Long taxonDescriptionRecordId; @Basic(optional = false) @Column(name = "reference_id") private Long referenceId; public TaxonDescriptionRecordReferencePK() { } public TaxonDescriptionRecordReferencePK(Long taxonDescriptionRecordId, Long referenceId) { this.taxonDescriptionRecordId = taxonDescriptionRecordId; this.referenceId = referenceId; } public Long getTaxonDescriptionRecordId() { return taxonDescriptionRecordId; } public void setTaxonDescriptionRecordId(Long taxonDescriptionRecordId) { this.taxonDescriptionRecordId = taxonDescriptionRecordId; } public Long getReferenceId() { return referenceId; } public void setReferenceId(Long referenceId) { this.referenceId = referenceId; } @Override public int hashCode() { int hash = 0; hash += (taxonDescriptionRecordId != null ? taxonDescriptionRecordId.hashCode() : 0); hash += (referenceId != null ? referenceId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof TaxonDescriptionRecordReferencePK)) { return false; } TaxonDescriptionRecordReferencePK other = (TaxonDescriptionRecordReferencePK) object; if ((this.taxonDescriptionRecordId == null && other.taxonDescriptionRecordId != null) || (this.taxonDescriptionRecordId != null && !this.taxonDescriptionRecordId.equals(other.taxonDescriptionRecordId))) { return false; } if ((this.referenceId == null && other.referenceId != null) || (this.referenceId != null && !this.referenceId.equals(other.referenceId))) { return false; } return true; } @Override public String toString() { return "org.inbio.ara.persistence.taxonomy.TaxonDescriptionRecordReferencePK[taxonDescriptionRecordId=" + taxonDescriptionRecordId + ", referenceId=" + referenceId + "]"; } }
import java.util.Scanner; public class example32_01_5 {//ПРИМЕР 5 РАЗДЕЛ 1 последовательность Фибоначчи //ДОПОЛНЕНА РЕКУРСИВНЫМ ДЕРЕВОМ private static int step=0; //поле шага - глубина рекурсии public static int f(int n) { //метод вычисления числа Фибоначчи по заданному номеру в последовательности. int result=0; space(); System.out.println(""+n+"->"); step++; if (n==0){step--; return 0;} else if (n==1){step--; return 1; } else {result=f(n-1)+f(n-2); } step--; space(); System.out.println(""+n+ "<-"); return result; } public static void space() { for (int i = 0; i < step; i++) {System.out.print("-");} } public static void main(String[] args) { try { Scanner in=new Scanner(System.in); System.out.println("Программа выводит число Фибоначчи по заданному номеру в последовательности."); System.out.println("Последовательность Фибоначчи формируется так:"+ "нулевой член последовательности равен нулю,\n"+ "первый – единице, а каждый следующий – сумме двух предыдущих."); System.out.println("Введите номер числа в последовательности:"); int n=in.nextInt(); System.out.println("Дополнительно выводится последовательность обхода дерева рекурсивных вызовов:"); System.out.printf("Число Фибоначчи под номером "+n+"="+f(n)); } catch (Exception error) { System.out.println("При обработке данных произошла ошибка! Возможно Вы некорректно ввели данные!"); } //обработка исключения } }
package com.example.nene.movie20.data; /** * Created by nene on 2018/4/16. */ public class Video { private String img; private String name; private String number; public Video(String img, String name, String number){ this.img = img; this.name = name; this.number = number; } public String getImg(){ return img; } public void setImg(){ this.img = img; } public String getName(){ return name; } public void SetName(String name){ this.name = name; } public String getNumber(){ return number; } public void setNumber(){ this.number = number; } }
package com.siciarek.fractals.test.mocks; import com.siciarek.fractals.common.Drawable; public class TestCanvas implements Drawable { @Override public void init(String style) { // TODO Auto-generated method stub } @Override public float getWidth() { // TODO Auto-generated method stub return 0; } @Override public float getHeight() { // TODO Auto-generated method stub return 0; } @Override public void updateTitle(String title) { // TODO Auto-generated method stub } @Override public void setPoint(float x, float y) { // TODO Auto-generated method stub } @Override public void moveTo(float x, float y) { // TODO Auto-generated method stub } @Override public void lineTo(float x, float y) { // TODO Auto-generated method stub } @Override public void close() { // TODO Auto-generated method stub } @Override public void reset() { // TODO Auto-generated method stub } @Override public void finalize() { // TODO Auto-generated method stub } }
package com.miyatu.tianshixiaobai.http.api; import com.miyatu.tianshixiaobai.http.service.DemandService; import com.miyatu.tianshixiaobai.http.service.MemberService; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.Api.BaseApi; import java.util.List; import java.util.Map; import okhttp3.MultipartBody; import okhttp3.RequestBody; import retrofit2.Retrofit; import rx.Observable; public class DemandApi extends BaseApi { private Map<String, Object> params; private Map<String, RequestBody> bodyMap; private List<MultipartBody.Part> parts; public static final String ADD_DEMAND = "Market.Demand/add"; //发布需求 public static final String LEVEL = "Shop.ShopLevel/index"; //小白登记 public DemandApi(String mothed) { setShowProgress(false); setMothed(mothed); setCancel(false); setCache(false); setCookieNetWorkTime(60); setCookieNoNetWorkTime(24 * 60 * 60); } public void setParams(Map<String, Object> params) { this.params = params; } public void setBodyMap(Map<String, RequestBody> bodyMap) { this.bodyMap = bodyMap; } public void setParts(List<MultipartBody.Part> parts) { this.parts = parts; } @Override public Observable getObservable(Retrofit retrofit) { DemandService service = retrofit.create(DemandService.class); if (getMothed().equals(ADD_DEMAND)) { return service.addDemand(bodyMap, parts); } if (getMothed().equals(LEVEL)) { return service.level(params); } return null; } }
/* * Copyright Verizon Media, Licensed under the terms of the Apache License, Version 2.0. See LICENSE file in project root for terms. */ package com.yahoo.cubed.model; import com.yahoo.cubed.json.filter.Filter; import com.yahoo.cubed.model.filter.PipelineFilter; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import lombok.Getter; import lombok.Setter; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; /** * Stores pipeline logic. * Projections, filters, name, etc. */ @Entity @Table(name = "pipeline") public class Pipeline implements AbstractModel { /** Pipeline ID. */ @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "pipeline_id", nullable = false) @Getter @Setter private long pipelineId; /** Product Name. */ @Column(name = "product_name") @Getter @Setter private String productName = "cubed"; /** Pipeline type. */ @Column(name = "pipeline_type") @Getter @Setter private String pipelineType = "datamart"; /** Funnel query hql. */ @Column(name = "funnel_hql") @Getter @Setter private String funnelHql; /** Funnel steps. */ @Column(name = "funnel_steps") @Getter @Setter private String funnelStepsJson; /** Funnel steps names. */ @Column(name = "funnel_step_names") @Getter @Setter private String funnelStepNames; /** Funnel query range. */ @Column(name = "funnel_query_range") @Getter @Setter private String funnelQueryRange; /** Funnel repeat interval. */ @Column(name = "funnel_repeat_interval") @Getter @Setter private String funnelRepeatInterval; /** Funnel user id field. */ @Column(name = "funnel_user_id_field") @Getter @Setter private String funnelUserIdField; /** Pipeline name. */ @Column(name = "pipeline_name", nullable = false) @Getter @Setter private String pipelineName; /** Pipeline description. */ @Column(name = "pipeline_description", nullable = false) @Getter @Setter private String pipelineDescription; /** Pipeline owner. */ @Column(name = "pipeline_owner") @Getter @Setter private String pipelineOwner; /** List of projections. */ @Fetch(value = FetchMode.SELECT) @OneToMany(mappedBy = "pipelineId", cascade = {}, fetch = FetchType.LAZY) @Getter private List<PipelineProjection> projections; /** Pipeline filter JSON string. */ @Column(name = "pipeline_filter") @Getter @Setter private String pipelineFilterJson; /** Pipeline status. */ @Column(name = "pipeline_status") @Getter @Setter private String pipelineStatus; /** Pipeline oozie job id. */ @Column(name = "pipeline_oozie_job_id") @Getter @Setter private String pipelineOozieJobId; /** Pipeline oozie job status. */ @Column(name = "pipeline_oozie_job_status") @Getter @Setter private String pipelineOozieJobStatus; /** Pipeline oozie backfill job id. */ @Column(name = "pipeline_oozie_backfill_job_id") @Getter @Setter private String pipelineOozieBackfillJobId; /** Pipeline oozie backfill status. */ @Column(name = "pipeline_oozie_backfill_job_status") @Getter @Setter private String pipelineOozieBackfillJobStatus; /** Pipeline deleted status. */ @Column(name = "pipeline_is_deleted") private boolean pipelineIsDeleted; /* * Pipeline backfill start time. * If this field value is null/empty, it means no backfill */ @Column(name = "pipeline_backfill_start_time") @Getter @Setter private String pipelineBackfillStartTime; /* * Pipeline end time. * If this field value is null/empty, then there is no end time. */ @Column(name = "pipeline_end_time") @Getter @Setter private String pipelineEndTime; /* * Pipeline create time. * If this field value is null/empty, then there is no end time. */ @Column(name = "pipeline_create_time") @Getter @Setter private String pipelineCreateTime; /* * Pipeline edit time. * If this field value is null/empty, then there is no end time. */ @Column(name = "pipeline_edit_time") @Getter @Setter private String pipelineEditTime; /** Get filters. */ @Transient public PipelineFilter pipelineFilterObject; /** Pipeline version. */ @Column(name = "pipeline_version") @Setter private Long pipelineVersion; /** Pipeline schema name. */ @Column(name = "pipeline_schema_name") @Getter @Setter private String pipelineSchemaName; /** * Id of the funnel group that this pipeline belongs to. */ @Getter @Setter @Column(name = "funnel_group_id") private long funnelGroupId; /** * Get pipeline version. */ public long getPipelineVersion() { if (pipelineVersion == null) { return 1L; } return this.pipelineVersion; } /** * Set projections. */ public void setProjections(List<PipelineProjection> projections) { for (PipelineProjection p : projections) { p.setPipelineId(this.pipelineId); } this.projections = projections; } /** * Get pipeline filter. */ public PipelineFilter getPipelineFilterObject() { if (pipelineFilterObject == null && pipelineFilterJson != null) { try { pipelineFilterObject = Filter.fromJson(pipelineFilterJson).toModel(pipelineSchemaName); } catch (Exception e) { // TODO: do some logging here return null; } } return pipelineFilterObject; } /** * Set pipeline filter. */ public void setPipelineFilterObject(PipelineFilter pipelineFilterObject) { this.pipelineFilterObject = pipelineFilterObject; } /** * Check if pipeline backfill is enabled. */ public boolean isPipelineBackfillEnabled() { return this.pipelineBackfillStartTime != null && !this.pipelineBackfillStartTime.isEmpty(); } /** * Check if pipeline backfill is enabled. */ public boolean isPipelineEndTimeEnabled() { return this.pipelineEndTime != null && !this.pipelineEndTime.isEmpty(); } /** * Set if pipeline should be marked as deleted. */ public void setPipelineIsDeleted(boolean isPipelineDeleted) { this.pipelineIsDeleted = isPipelineDeleted; } /** * Check if pipeline is marked as deleted. */ public boolean getPipelineIsDeleted() { return this.pipelineIsDeleted; } /** * Get pipeline database id. */ public long getPrimaryIdx() { return this.getPipelineId(); } /** * Simplify pipeline. */ public Pipeline simplify() { Pipeline newPipeline = new Pipeline(); newPipeline.pipelineId = this.pipelineId; newPipeline.pipelineType = this.pipelineType; newPipeline.funnelStepsJson = this.funnelStepsJson; newPipeline.funnelStepNames = this.funnelStepNames; newPipeline.funnelQueryRange = this.funnelQueryRange; newPipeline.funnelHql = this.funnelHql; newPipeline.funnelRepeatInterval = this.funnelRepeatInterval; newPipeline.funnelUserIdField = this.funnelUserIdField; newPipeline.pipelineName = this.pipelineName; newPipeline.pipelineDescription = this.pipelineDescription; newPipeline.pipelineFilterJson = this.pipelineFilterJson; newPipeline.pipelineOwner = this.pipelineOwner; newPipeline.pipelineStatus = this.pipelineStatus; newPipeline.pipelineOozieJobId = this.pipelineOozieJobId; newPipeline.pipelineOozieJobStatus = this.pipelineOozieJobStatus; newPipeline.pipelineOozieBackfillJobId = this.pipelineOozieBackfillJobId; newPipeline.pipelineOozieBackfillJobStatus = this.pipelineOozieBackfillJobStatus; newPipeline.pipelineBackfillStartTime = this.pipelineBackfillStartTime; newPipeline.pipelineIsDeleted = this.pipelineIsDeleted; newPipeline.pipelineCreateTime = this.pipelineCreateTime; newPipeline.pipelineEditTime = this.pipelineEditTime; newPipeline.pipelineVersion = this.pipelineVersion; newPipeline.pipelineSchemaName = this.pipelineSchemaName; return newPipeline; } /** * Simplify list of pipelines. */ public static List<Pipeline> simplifyPipelineList(List<Pipeline> pipelines) { if (pipelines == null) { return null; } List<Pipeline> newPipelines = new ArrayList<>(); for (Pipeline pipeline : pipelines) { newPipelines.add(pipeline.simplify()); } return newPipelines; } /** * Set funnel group ID for a list of pipelines. */ public static void setFunnelGroupId(List<Pipeline> pipelines, long funnelGroupId) { if (pipelines == null) { return; } for (Pipeline pipeline : pipelines) { pipeline.setFunnelGroupId(funnelGroupId); } } /** * Get pipeline name. */ @Override public String getPrimaryName() { return this.getPipelineName(); } }
package at.fhv.teama.easyticket.server.security; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.DelegatingPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import java.util.HashMap; @Slf4j @Configuration @RequiredArgsConstructor @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true) public class SecurityConfigurer { public final AuthoritiesPopulator authoritiesPopulator; public final SecurityConfig securityConfig; @Bean public PasswordEncoder passwordEncoder() { HashMap<String, PasswordEncoder> encoders = new HashMap<>(); BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(); encoders.put("bcrypt", bCryptPasswordEncoder); DelegatingPasswordEncoder bcrypt = new DelegatingPasswordEncoder("bcrypt", encoders); bcrypt.setDefaultPasswordEncoderForMatches(bCryptPasswordEncoder); return bcrypt; } @Autowired public void configure(AuthenticationManagerBuilder auth) throws Exception { log.info("Enable " + securityConfig.getAuthtype().toString() + " Authentication"); switch (securityConfig.getAuthtype()) { case LDAP: setupLdapAuth(auth); break; } } private void setupLdapAuth(AuthenticationManagerBuilder auth) throws Exception { LDAPConfig ldapConfig = securityConfig.getLdapConfig(); auth.ldapAuthentication() .userDnPatterns(ldapConfig.getUserDnPatterns()) .groupSearchBase(ldapConfig.getGroupSearchBase()) .userSearchBase(ldapConfig.getUserSearchBase()) .userSearchFilter(ldapConfig.getUserSearchFilter()) .ldapAuthoritiesPopulator(authoritiesPopulator) .contextSource() .managerDn(ldapConfig.getManagerDn()) .managerPassword(ldapConfig.getManagerPassword()) .url(ldapConfig.getUrl()) .port(ldapConfig.getPort()); } }
package com.eshop.service; import com.eshop.domain.*; import org.springframework.ui.Model; import java.time.LocalDate; import java.util.List; public interface AdminService { LocalDate getStartDate(LocalDate start); LocalDate getFinishDate(LocalDate finish); String getMessage(LocalDate start, LocalDate finish); void setStats(Model model, LocalDate start, LocalDate finish); void setStatsDefaultDate(Model model); List<Integer> numberOfOrdersForTenBestClients(List<Client> clientList, LocalDate start, LocalDate finish); void addNewProduct(String productName, double productPrice, String category, int amount, String colour, String brand, int weight, String operatingSystem, String image); boolean checkCategory(String categoryName); ShopAddress createShopAddress(String country, String city, int postcode, String street, int houseNumber, String phone); }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.koshish.java.hibernate.ecommerce.controller; import com.koshish.java.hibernate.ecommerce.DAO.CategoryDAO; import com.koshish.java.hibernate.ecommerce.DAO.Model.ProductInfo; import com.koshish.java.hibernate.ecommerce.DAO.Model.PurchaseDetailInfo; import com.koshish.java.hibernate.ecommerce.DAO.ProductDAO; import com.koshish.java.hibernate.ecommerce.entity.Product; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * * @author Koshish Rijal */ @Controller @RequestMapping(value = "/client") public class ClientCartController { @Autowired private ProductDAO productDAO; @Autowired private CategoryDAO categoryDAO; @Autowired private ServletContext servletContext; @RequestMapping(method = RequestMethod.GET) public String landingPage(Model model,HttpSession session) { model.addAttribute("categoryList", categoryDAO.getAll()); int hits=1; if(servletContext.getAttribute("hits")!=null){ hits=(int) servletContext.getAttribute("hits"); if(session.isNew()){ hits=(int) servletContext.getAttribute("hits")+1; } servletContext.setAttribute("hits",hits); } servletContext.setAttribute("hits",hits); return "client"; } @RequestMapping(value = "/add", method = RequestMethod.POST) public String addInCart(@ModelAttribute("productInfo") ProductInfo productInfo, HttpSession session) { //note and research that getby id of product didnt worked while created in model class productInfo //after passing product from only controller part this worked Product product = productDAO.getById(productInfo.getProductId()); productInfo.setDiscountAndProfitProductNameAndCategoryName(product); if (session.getAttribute("productInfoList") == null) { List<ProductInfo> productInfoList = new ArrayList<>(); productInfoList.add(productInfo); PurchaseDetailInfo pdi=new PurchaseDetailInfo(productInfoList); session.setAttribute("purchaseDetailInfo",pdi); session.setAttribute("productInfoList", productInfoList); return "shoppingcart"; } else { List<ProductInfo> productInfoList = (List<ProductInfo>) session.getAttribute("productInfoList"); productInfoList.add(productInfo); PurchaseDetailInfo pdi=(PurchaseDetailInfo) session.getAttribute("purchaseDetailInfo"); pdi.setProductInfoList(productInfoList); session.setAttribute("purchaseDetailInfo",pdi); session.setAttribute("productInfoList", productInfoList); return "shoppingcart"; } } @RequestMapping(value = "/continue", method = RequestMethod.GET) public String continueShopping() { return "redirect:/client"; } }
public class Pallet { private String id; private String cookie; private String delivered; private String customer; private String produced; private String blocked = "No"; public Pallet(String id, String cookie, String delivered, String customer, String produced, boolean blocked) { this.id = id; this.cookie = cookie; this.delivered = delivered; this.customer = customer; this.produced = produced; if (blocked){ this.blocked = "Yes"; } } public String getId() { return id; } public String getCookie() { return cookie; } public String getDelivered() { return delivered; } public String getCustomer() { return customer; } public String getProduced() { return produced; } public String getBlocked() { return blocked; } public String toString(){ return id + " " + cookie + " " + delivered + " " + customer + " " + produced + " " + blocked; } }
package org.silverpeas.looks.aurora; import org.silverpeas.components.questionreply.model.Question; import org.silverpeas.core.util.URLUtil; import java.util.ArrayList; import java.util.List; /** * @author Nicolas Eysseric */ public class Questions { private List<Question> list = new ArrayList<>(); private boolean canAskAQuestion = false; private String appId; public void setCanAskAQuestion(boolean canAsk) { this.canAskAQuestion = canAsk; } public boolean isCanAskAQuestion() { return canAskAQuestion; } protected void setAppId(String appId) { this.appId = appId; } public String getRequestURL() { return "/RquestionReply/"+appId+"/CreateQQuery"; } public String getAppURL() { return URLUtil.getSimpleURL(URLUtil.URL_COMPONENT, appId); } public List<Question> getList() { return list; } public void add(Question q) { list.add(q); } }
////////////////////////////////////////////////////////////////////////////////////////// //Yulun Wu //CSE 002 Sec 110 //9/13/14 // // //Program #1 //Write a program that prompts the user to enter two digits, //the first giving the number of counts on a cyclometer //and the second giving the number of seconds during which the counts occurred //and then prints out the distance traveled and average miles per hour. //Assume diameter of wheel = 27 in. import java.util.Scanner; //import statement //define a class public class Bicycle{ //main method public static void main (String[] args){ Scanner myScanner; //declare an instance for Scanner project myScanner = new Scanner (System.in); //Scanner Constructor System.out.print( "Enter the number of seconds (int) : "); int nSeconds = myScanner.nextInt(); //accept user input System.out.print( "Enter the number of counts (int): "); int nCounts = myScanner.nextInt(); //accept user input double distance; //Total distance the person biked. double time; //Total time the person took double mph; //average mph double wheelDiameter = 27.0, //define the diameter of the wheel PI=3.14159, //define pi feetPerMile = 5280, //define number of feet per mile inchesPerFoot = 12, //define number of inches per foot secondsPerMinute = 60, //define number of seconds per minute minutesPerHour = 60; //define number of minutes per hour distance = nCounts*wheelDiameter*PI/inchesPerFoot/feetPerMile; //Calculate the total distance time = nSeconds/secondsPerMinute; //Calculate the total time mph= distance/time/minutesPerHour; //Calculate the average mph System.out.println("The distance was "+ (int) (distance*100)/(100.0) + " miles and took "+ (int)(time*100)/(100.0) + " minutes."); //convert into two decimals and print. System.out.println("The average mph was "+ mph+ "."); }//end of main method }//end of class
package com.datagraph.core.engine.scheduler; import com.datagraph.core.engine.job.JobManager; import com.datagraph.core.engine.job.Manager; import java.util.List; /** * Created by Denny Joseph on 6/4/16. */ public class Scheduler implements Runnable { private Manager manager; private volatile boolean stopped = false; private int sleepDelay = 1; // in seconds private long lastCheck = System.currentTimeMillis(); public Scheduler(Manager manager, int sleepDelay) { this.manager = manager; this.stopped = false; this.sleepDelay = sleepDelay; this.lastCheck = System.currentTimeMillis(); } public void stop() { this.stopped = true; } public void restart() { this.stopped = false; this.lastCheck = System.currentTimeMillis(); } @Override public void run() { try { while (!stopped) { List<JobManager> jobManagers = manager.getJobList(); System.out.println("scheduler running "); for(JobManager jobManager : jobManagers) { if(jobManager.canStart()) jobManager.start(); } Thread.sleep(sleepDelay * 1000); } }catch(Throwable e) { System.out.println(e); } } }
package nz.co.zufang.service; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import nz.co.zufang.controller.InfoCreateRequest; import nz.co.zufang.controller.InfoUpdateRequest; import nz.co.zufang.model.Info; import nz.co.zufang.repository.InfoRepository; import nz.co.zufang.spec.InfoSpec; @Service public class InfoServiceImpl implements InfoService{ private static final int PAGE_SIZE = 5; @Autowired InfoRepository infoRepository; @Override public Info getInfoById(String id) { return infoRepository.findOne(id); } @Override public Boolean createInfo(InfoCreateRequest infoCreateRequest) { Info info = new Info(); info.setTitle(infoCreateRequest.getTitle()); info.setKeywords(infoCreateRequest.getKeywords()); info.setDescription(infoCreateRequest.getDescription()); info.setLinkMan(infoCreateRequest.getLinkMan()); info.setFee(infoCreateRequest.getFee()); info.setEmail(infoCreateRequest.getEmail()); info.setQq(infoCreateRequest.getQq()); info.setPhone(infoCreateRequest.getPhone()); info.setAddress(infoCreateRequest.getAddress()); info.setMapPoint(infoCreateRequest.getMapPoint()); info.setPostArea(infoCreateRequest.getPostArea()); info.setPostDate(new Date()); info.setEndDate(new Date()); info = infoRepository.save(info); if(info.getId()!=null){ return true; }else{ return false; } } @Override public Boolean updateInfo(InfoUpdateRequest infoUpdateRequest) { Info info = infoRepository.findOne(infoUpdateRequest.getId()); // Info info = new Info(); info.setTitle(infoUpdateRequest.getTitle()); info.setKeywords(infoUpdateRequest.getKeywords()); info.setDescription(infoUpdateRequest.getDescription()); info.setLinkMan(infoUpdateRequest.getLinkMan()); info.setFee(infoUpdateRequest.getFee()); info.setEmail(infoUpdateRequest.getEmail()); info.setQq(infoUpdateRequest.getQq()); info.setPhone(infoUpdateRequest.getPhone()); info.setAddress(infoUpdateRequest.getAddress()); info.setMapPoint(infoUpdateRequest.getMapPoint()); info.setPostArea(infoUpdateRequest.getPostArea()); info.setPostDate(new Date()); info.setEndDate(new Date()); infoRepository.save(info); return true; } @Override public Boolean deleteInfo(String id) { infoRepository.delete(id); return true; } @Override public List<Info> getAllInfo() { return (List<Info>) infoRepository.findAll(); } @Override public List<Info> getInfo(Info info, int pageNumber) { InfoSpec infoSpec = new InfoSpec(info); PageRequest request = new PageRequest(pageNumber - 1, PAGE_SIZE, Sort.Direction.DESC, "postDate"); List<Info> infos = infoRepository.findAll(infoSpec,request).getContent(); return infos; } }
//The program contains a graph for which critical path analysis has to be done. //The task is read one vertex at a time, calculated the earliest completion time and the latest completion time. //Slack time is calculated. And critical path is analysed. import java.util.*; //Author: Ashwin Ravishankar public class CriticalPathAnalysis { public static void main(String[] args) { int[][] graphWeight = new int[18][18]; //Initialize entire graph weight to 0. for(int i=0;i<18;i++) { for(int j=0;j<18;j++) { graphWeight[i][j]=0; } } //Initialize graph weight to correct vertice pairs. graphWeight[1][2] = 3; graphWeight[1][3] = 6; graphWeight[1][4] = 5; graphWeight[2][5] = 2; graphWeight[3][6] = 4; graphWeight[4][7] = 8; graphWeight[5][8] = 4; graphWeight[6][8] = 7; graphWeight[6][9] = 1; graphWeight[7][9] = 3; graphWeight[8][10] = 4; graphWeight[9][11] = 5; graphWeight[9][12] = 3; graphWeight[10][14] = 6; graphWeight[7][13] = 12; graphWeight[11][14] = 4; graphWeight[12][15] = 9; graphWeight[13][15] = 8; graphWeight[14][16] = 2; graphWeight[15][16] = 3; graphWeight[16][17] = 2; int[] earliestCompletionTime = new int[18]; int[] latestCompletionTime = new int[18]; int[] slackTime = new int[18]; //Calculate earliest completion time for each task for(int i=0;i<=17;i++) { earliestCompletionTime[i]=0; //set all the earliest completion time to 0 for(int j=1;j<i;j++) { if (graphWeight[j][i] != 0) //If there exists a path from A to B if (earliestCompletionTime[j] + graphWeight[j][i] > earliestCompletionTime[i]) //EC[2]+ WEIGHT(2)> 0 EC[5] earliestCompletionTime[i] = earliestCompletionTime[j] + graphWeight[j][i]; } } for (int i = 17; i >= 1; i--) latestCompletionTime[i] = earliestCompletionTime[17]; //Set latest completion time for all the vertices //Calculate latest completion time for each task for (int i = 17; i >= 1; i--) { for (int j = 1; j < i; j++) { if (graphWeight[j][i] != 0) if (latestCompletionTime[i] - graphWeight[j][i] < latestCompletionTime[j]) latestCompletionTime[j] = latestCompletionTime[i] - graphWeight[j][i]; } } //Calculate slack time for (int i=0; i<=17;i++) { slackTime[i]=latestCompletionTime[i] - earliestCompletionTime[i]; } //Display critical Path System.out.println("\n--------- Critical Path for the Graph ---------"); for(int i=1; i<18; i++) { if(slackTime[i]==0) { if(i!=0) { System.out.print(i); if(i!=17) { System.out.print(" ---> "); } } } } //Display earliest and latest completion time System.out.println("\n\n--------- Earliest & Latest Completion Time For Task ---------"); for(int i=1; i<18; i++) { System.out.println("For Task #" + i); System.out.println("Earliest Completion Time: " + earliestCompletionTime[i] + " weeks\t Latest Completion Time: " + latestCompletionTime[i] + " weeks\n"); } //Display earliest comepletion time of project System.out.println("\n--------- Earlist Completion Time For Entire Project---------"); System.out.println("Project's Earliest Completion Time: " + earliestCompletionTime[17] + " weeks"); //Display slack time for each task System.out.println("\n\n--------- Slack Time For Task ---------"); for (int i=1;i<18;i++) { System.out.println("Slack Time for Task "+ i + ": " + slackTime[i]+ " weeks"); } } }
package com.mhframework.gameplay.actor; import java.util.ArrayList; import java.util.Collections; import com.mhframework.core.math.MHVector; import com.mhframework.gameplay.tilemap.io.MHMapFileInfo; /****************************************************************************** * * @author Michael Henson * */ public class MHActorList //implements MHTileMapLayer { private ArrayList<MHActor> list; public MHActorList() { list = new ArrayList<MHActor>(); } public void add(MHActor actor) { list.add(actor); } public void remove(MHActor actor) { list.remove(actor); } public void update(long elapsedTime) { for (int i = 0; i < list.size(); i++) { MHActor a = list.get(i); if (a.isDestroyed()) remove(a); else a.update(elapsedTime); } } public int size() { return list.size(); } public MHActor get(int index) { if (index < 0) return list.get(0); if (index >= list.size()) return list.get(list.size()-1); return list.get(index); } // private void sortOnePass() // { // int size = list.size()-1; // for (int a = 0; a < size; a++) // { // MHActor thisOne = list.get(a); // MHActor nextOne = list.get(a+1); // // if (thisOne.compareBasePoint(nextOne) < 0) // { // list.set(a, nextOne); // list.set(a+1, thisOne); // } // } // } /**************************************************************** * Return the actor whose bounds contain the given point, if any. * If no actor contains the point, this method returns null. If * more than one actor's bounds contain the point, it returns * whichever actor is in front. * * @param point The (x, y) coordinate to be checked for the * presence of an actor. * * @return The foremost actor at the given location, or null if * there is no actor at that location. */ public MHActor getActorAt(MHVector point) { sort(); for (int a = list.size() - 1; a >= 0; a--) { if (list.get(a).getBounds().contains(point)) return list.get(a); } return null; } @SuppressWarnings("unchecked") public void sort() { Collections.sort(list); } public String toString() { String data = ""; for (MHActor actor : list) { data += actor.getImageID() + MHMapFileInfo.MAP_FILE_DELIMITER; data += actor.getX() + MHMapFileInfo.MAP_FILE_DELIMITER; data += actor.getY() + MHMapFileInfo.MAP_FILE_DELIMITER; } return data; } public void clear() { list.clear(); } public MHActorList merge(MHActorList other) { MHActorList merged = new MHActorList(); int myIndex=0, otherIndex=0; sort(); other.sort(); while (myIndex < list.size() && otherIndex < other.size()) { if (list.get(myIndex).compareTo(other.get(otherIndex)) < 0) { merged.add(list.get(myIndex)); myIndex++; } else { merged.add(other.get(otherIndex)); otherIndex++; } } if (myIndex < list.size()) { for (int i = myIndex; i < list.size(); i++) merged.add(list.get(i)); } else { for (int i = otherIndex; i < other.size(); i++) merged.add(other.get(i)); } return merged; } }
package ru.otus.sua.L13; import lombok.extern.slf4j.Slf4j; import java.util.Arrays; @Slf4j // for thread time and info print public class SorterImpl implements Sorter { @Override public int[] sort(int[] arr, int from, int to) { log.info("Sort start.["+from+","+to+"]"); Arrays.sort(arr,from,to+1); log.info("Sort end."); return arr; } }
package com.trump.auction.back.auctionProd.model; import java.math.BigDecimal; import java.util.Date; public class AuctionBidDetail { private Integer id; private String bidId; private Integer userId; private String userName; private Integer bidType; private Integer bidSubType; public Integer getBidSubType() { return bidSubType; } public void setBidSubType(Integer bidSubType) { this.bidSubType = bidSubType; } private Integer auctionProdId; private Integer auctionNo; private String userIp; private Date createTime; private Date updateTime; private BigDecimal bidPrice; private String headImg; private String nickName; private String address; public String getSubUserId() { return subUserId; } public void setSubUserId(String subUserId) { this.subUserId = subUserId; } /** * 机器人 */ private String subUserId; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getBidId() { return bidId; } public void setBidId(String bidId) { this.bidId = bidId == null ? null : bidId.trim(); } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName == null ? null : userName.trim(); } public Integer getBidType() { return bidType; } public void setBidType(Integer bidType) { this.bidType = bidType; } public Integer getAuctionProdId() { return auctionProdId; } public void setAuctionProdId(Integer auctionProdId) { this.auctionProdId = auctionProdId; } public Integer getAuctionNo() { return auctionNo; } public void setAuctionNo(Integer auctionNo) { this.auctionNo = auctionNo; } public String getUserIp() { return userIp; } public void setUserIp(String userIp) { this.userIp = userIp == null ? null : userIp.trim(); } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public BigDecimal getBidPrice() { return bidPrice; } public void setBidPrice(BigDecimal bidPrice) { this.bidPrice = bidPrice; } public String getHeadImg() { return headImg; } public void setHeadImg(String headImg) { this.headImg = headImg == null ? null : headImg.trim(); } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName == null ? null : nickName.trim(); } public String getAddress() { return address; } public void setAddress(String address) { this.address = address == null ? null : address.trim(); } }
package com.cryptocurrency.CryptoCrazy.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class XRP { @JsonProperty("USD") private double USD; public XRP() { // TODO Auto-generated constructor stub } public double getUSD() { return USD; } public void setUSD(double uSD) { USD = uSD; } @Override public String toString() { return "XRP [USD=" + USD + "]"; } }
/*import java.util.*; class Dupli { public static void removeDuplicateString2(final String input) { final Set<Character> set = new LinkedHashSet<>(); for (int i = 0; i < input.length(); i++) set.add(input.charAt(i)); final StringBuilder stringBuilder = new StringBuilder(set.size()); for (final Character character : set) stringBuilder.append(character); System.out.println(stringBuilder); } public static void main(String... harsh) { removeDuplicateString2("harshhh ggangwarr"); } } */ import java.util.*; class removeDuplicate { public String remove(String inputString) { String result = ""; Set<String> inputSet= new LinkedHashSet<String>(); //LinkedHashSet maintains the order in which elements are inserted for(int i=0;i<inputString.length();i++) { inputSet.add(String.valueOf(inputString.charAt(i))); } for(String a: inputSet) { result += a; } return result; } public static void main(String java2carrer[]) { removeDuplicate rd=new removeDuplicate(); System.out.println(rd.remove("abdacdabcd")); } }
package java_learning; class Calc { int num1; int num2; int result; public void perform() { result = num1 + num2; } } public class ObjectDemo { public static void main(String[] args) { Calc obj=new Calc(); obj.num1=2; obj.num2=3; obj.perform(); System.out.println(obj.result); } }
package com.online; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; public class TestQuery { DataSource dataSource; JdbcTemplate jdbctemplete; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; jdbctemplete=new JdbcTemplate(dataSource); } /*public void getAllStudents() { try { String sql = "select *from student"; Connection conn=dataSource.getConnection(); PreparedStatement pst = conn.prepareStatement(sql); ResultSet rs = pst.executeQuery(); while (rs.next()) { System.out.println(rs.getString(1)+"\t"+ rs.getString(2)+"\t" + rs.getString(3)+"\t" + rs.getString(4)+"\t" + rs.getString(5)); } } catch (Exception e) { e.printStackTrace(); } }*/ public int getNoStudentdentRecords(){ String sql="select count(*) from student"; int count=jdbctemplete.queryForInt(sql); return count; } public String getStudentName(int rollno){ String sql="select name from student where rollno=?"; String name=jdbctemplete.queryForObject(sql, new Object[]{rollno}, String.class); return name; } public Student getStudent(int rollno){ String sql="select *from student where rollno=?"; Student student=jdbctemplete.queryForObject(sql, new Object[]{rollno}, new StudentMapper()); return student; } public List<Student> getAllStudent() { List<Student>listofstudents= new ArrayList<Student>(); String sql="select * from student"; listofstudents=jdbctemplete.query(sql, new StudentMapper()); return listofstudents; } public int insertStudent(Student student) { String sql="insert into student values(?,?,?,?,?)"; int result=jdbctemplete.update(sql, new Object[]{student.getRollno(), student.getName(),student.getCourse(),student.getCollege(),student.getUniversity()}); return result; } public int updateStudent(Student student) { String sql="update student set name=?, course=?, college=?, university=? where rollno=?"; int result=jdbctemplete.update(sql, new Object[]{student.getName(),student.getCourse(),student.getCollege(),student.getUniversity(), student.getRollno()}); return result; } public int deleteStudent(int rollno) { String sql="delete from student where rollno=?"; int result=jdbctemplete.update(sql, new Object[]{rollno}); return result; } } class StudentMapper implements RowMapper<Student>{ @Override public Student mapRow(ResultSet rs, int rownumbers) throws SQLException { Student student=new Student(); student.setRollno(Integer.parseInt(rs.getString(1))); student.setName(rs.getString(2)); student.setCourse(rs.getString(3)); student.setCollege(rs.getString(4)); student.setUniversity(rs.getString(5)); return student; } }
package com.xys.car.service; import com.xys.car.entity.Collection; import com.baomidou.mybatisplus.extension.service.IService; import com.xys.car.entity.Color; import com.xys.car.entity.RootEntity; /** * <p> * 服务类 * </p> * * @author zxm * @since 2020-12-04 */ public interface ICollectionService extends IService<Collection> { RootEntity selectCollection(Collection collection); RootEntity insertCollection(Collection collection); RootEntity updateCollection(Collection collection); RootEntity deleteCollection(Collection collection); }
package org.engine.test; import com.google.gson.Gson; import org.apache.commons.io.FileUtils; import org.cellcore.code.engine.page.extractor.AbstractEditionsExtractor; import org.cellcore.code.engine.page.extractor.CrawlConfiguration; import org.cellcore.code.engine.page.extractor.UnsupportedCardException; import org.cellcore.code.engine.page.extractor.mcc.MCCEditionCrawler; import org.cellcore.code.engine.page.extractor.mcc.MCCEditionsExtractor; import org.cellcore.code.engine.page.extractor.mcc.MCCPageDataExtractor; import org.cellcore.code.model.Card; import org.cellcore.code.shared.GsonUtils; import org.junit.Test; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; public class MCCPageParserTest { @Test public void testGetEditions() throws URISyntaxException, IOException { Map<String,String> editionsFr=GsonUtils.getSerializer().fromJson(FileUtils.readFileToString(new File(getClass() .getClassLoader().getResource("fr_editions.json").toURI())), Map.class); AbstractEditionsExtractor editions = new MCCEditionsExtractor(editionsFr); try { CrawlConfiguration conf = editions.extractEditions("http://boutique.magiccorporation.com/cartes-magic-edition-121-innistrad.html"); for (String edition : conf.getCardSets().keySet()) { System.out.println(edition+" => "+conf.getCardSets().get(edition)); } } catch (IOException e) { e.printStackTrace(); } } @Test public void testDownloadMB() { MCCPageDataExtractor parser = new MCCPageDataExtractor(); try { Card c = parser.extractFromPage("http://boutique.magiccorporation.com/carte-magic-22140-escouflenfer-foudregueule.html"); assertEquals("Thundermaw Hellkite", c.getName()); assertEquals("thundermaw hellkite", c.getiName()); assertEquals(1, c.getSources().size()); Gson g = GsonUtils.getSerializer(); Card c2 = g.fromJson(g.toJson(c), Card.class); assertEquals(c, c2); } catch (IOException e) { e.printStackTrace(); } catch (UnsupportedCardException e) { e.printStackTrace(); } } @Test public void testDownloadUnavail() { MCCPageDataExtractor parser = new MCCPageDataExtractor(); try { Card c = parser.extractFromPage("http://boutique.magiccorporation.com/carte-magic-23026-indolent-des-egouts.html"); assertEquals("Gutter Skulk", c.getName()); assertEquals("gutter skulk", c.getiName()); assertEquals(1, c.getSources().size()); assertEquals("http://boutique.magiccorporation.com/carte-magic-23026-indolent-des-egouts.html", c.getSources().get(0).getUrl()); // assertEquals(-1,c.getSources().get(0).getLastPrice(), 0.001); // assertEquals( -1,c.getSources().get(0).getPriceSet().iterator().next().getPrice(), 0.001); } catch (IOException e) { e.printStackTrace(); } catch (UnsupportedCardException e) { e.printStackTrace(); } } @Test public void crawlPage() { MCCEditionCrawler mccEditionCrawler = new MCCEditionCrawler("http://boutique.magiccorporation.com"); try { List<String> cards = mccEditionCrawler.crawlPage("http://boutique.magiccorporation.com/cartes-magic-edition-121-innistrad.html"); assertEquals("http://boutique.magiccorporation.com/carte-magic-19801-ange-du-vol-dalbatre.html", cards.get(0)); } catch (IOException e) { e.printStackTrace(); } } }
package com.mhframework.ui; import com.mhframework.MHScreen; import com.mhframework.MHScreenManager; import com.mhframework.core.math.MHVector; import com.mhframework.core.math.geom.MHRectangle; import com.mhframework.platform.MHPlatform; import com.mhframework.platform.event.MHKeyEvent; import com.mhframework.platform.event.MHMouseTouchEvent; import com.mhframework.platform.graphics.MHBitmapImage; import com.mhframework.platform.graphics.MHColor; import com.mhframework.platform.graphics.MHFont; import com.mhframework.platform.graphics.MHGraphicsCanvas; public class MHDialogBox extends MHScreen { private static final MHColor BACKGROUND_COLOR = MHPlatform.createColor(0, 0, 0, 180); public static final MHColor SHADOW_COLOR = MHPlatform.createColor(0, 0, 0, 128); protected int boxWidth, boxHeight; protected int preferredWidth; private int lineSpacing; private MHBitmapImage backgroundImage; private boolean tileBackground = false; private String text, title; protected MHFont textFont, titleFont; private MHRectangle titleBounds; /* * Border images are assumed to be in this order: * 0 1 2 * 3 4 5 * 6 7 8 */ private MHBitmapImage[] border = null; public MHDialogBox(MHScreen parentScreen, String text) { this(parentScreen, text, MHFont.getDefaultFont()); } public MHDialogBox(MHScreen parentScreen, String text, String titleText) { this(parentScreen, text, titleText, MHFont.getDefaultFont(), MHFont.getDefaultFont()); } public MHDialogBox(MHScreen parentScreen, String text, MHFont font) { setPreviousScreen(parentScreen); this.text = text; textFont = font; load(); createBackgroundImage(); calculateBoxDimensions(); } public MHDialogBox(MHScreen parentScreen, String text, String title, MHFont font, MHFont titleFont) { setPreviousScreen(parentScreen); this.text = text; this.title = title; textFont = font; this.titleFont = titleFont; load(); createBackgroundImage(); calculateBoxDimensions(); } public void setText(String text) { this.text = text; calculateBoxDimensions(); } public void setTitle(String title) { this.title = title; calculateBoxDimensions(); } public void setFont(MHFont font) { textFont = font; calculateBoxDimensions(); } public void setTitleFont(MHFont font) { titleFont = font; calculateBoxDimensions(); } /**************************************************************** * Draw the dialog box. This method is designed to support the * Template Method design pattern. Subclasses implementing * specialized dialog boxes can override methods that are called * in the following order. Alternatively, these methods can be * called independently as well. * <ol> * <li>calculateBoxDimensions</li> * <li>drawShadow</li> * <li>drawBorder</li> * <li>drawTitle</li> * <li>drawText</li> * </ol> */ public void render(MHGraphicsCanvas g) { calculateBoxDimensions(); if (tileBackground) tileImage(g, backgroundImage, 0, 0); else getPreviousScreen().render(g); drawShadow(g); drawBorder(g); drawTitle(g); drawText(g); super.render(g); } private void drawShadow(MHGraphicsCanvas g) { final int SHADOW_DISTANCE = 20; g.setColor(SHADOW_COLOR); int x = getTitleBounds().x + SHADOW_DISTANCE; int y = getTitleBounds().y + SHADOW_DISTANCE; g.fillRect(x, y, boxWidth, boxHeight); } private void drawTitle(MHGraphicsCanvas g) { // int x = (int)getTitleBounds().getX(); // int y = (int)getTitleBounds().getY(); // int w = (int)getTitleBounds().getWidth(); // int h = (int)getTitleBounds().getHeight(); // g.setColor(Color.WHITE); // g.drawRect(x, y, w, h); if (title != null && title.trim().length() > 0) { MHVector p; if (titleFont != null) { p = titleFont.centerOn(getTitleBounds(), g, title); //(g, title, x0, y0); titleFont.drawString(g, title, (int)p.getX(), (int)p.getY()); } else { p = textFont.centerOn(getTitleBounds(), g, title); textFont.drawString(g, title, (int)p.getX(), (int)p.getY()); } } } protected void calculateBoxDimensions() { lineSpacing = (int)(textFont.getHeight() * 1.1); boxHeight = calculateBoxHeight(); boxWidth = calculateBoxWidth(); while (boxHeight > MHScreenManager.getDisplayHeight() & boxWidth < MHScreenManager.getDisplayHeight()) preferredWidth = (int)(preferredWidth * 1.1); } protected int calculateBoxHeight() { boxHeight = 5; if (border != null) boxHeight += border[1].getHeight() + border[7].getHeight(); if (title != null && title.trim().length() > 0) { if (titleFont != null) boxHeight += titleFont.getHeight() + 5; else boxHeight += textFont.getHeight() + 5; int x = getTitleBounds().x; int y = getTitleBounds().y; int w = getTitleBounds().width; int h = boxHeight; getTitleBounds().setRect(x, y, w, h); } int numLines = Math.max(1, textFont.splitLines(text, preferredWidth).length); boxHeight += numLines * lineSpacing + 5; return boxHeight; } protected MHRectangle getTitleBounds() { if (titleBounds == null) { titleBounds = new MHRectangle(); int x = MHScreenManager.getDisplayWidth()/2 - calculateBoxWidth()/2; int y = MHScreenManager.getDisplayHeight()/2 - calculateBoxHeight()/2; int w = calculateBoxWidth(); int h = this.titleFont.getHeight(); titleBounds.setRect(x, y, w, h); } return titleBounds; } protected int calculateBoxWidth() { boxWidth = 5; if (border != null) boxWidth += border[3].getWidth() + border[5].getWidth(); String[] lines = textFont.splitLines(text, preferredWidth); int longest = preferredWidth; for (int i = 0; i < lines.length; i++) longest = Math.max(longest, textFont.stringWidth(lines[i])); boxWidth += longest; int x = getTitleBounds().x; int y = getTitleBounds().y; int w = boxWidth; int h = getTitleBounds().height; getTitleBounds().setRect(x, y, w, h); return boxWidth; } public void setBackgroundImage(MHBitmapImage img, boolean tiled) { backgroundImage = img; tileBackground = tiled; } public void setBorderImages(MHBitmapImage[] images) { border = images; calculateBoxDimensions(); } @Override public void load() { preferredWidth = MHScreenManager.getDisplayWidth() / 2; } @Override public void unload() { } private void drawText(MHGraphicsCanvas g) { int x0 = (int)getTitleBounds().x; int y0 = (int)getTitleBounds().y; if (titleBounds != null) y0 += titleBounds.height; if (border == null) { x0 += 5; y0 += textFont.getHeight(); } else { x0 += border[0].getWidth() + 5; y0 += border[0].getHeight() + textFont.getHeight(); } String[] lines = textFont.splitLines(text, preferredWidth); for (int line = 0; line < lines.length; line++) { int y = y0 + (line*lineSpacing); textFont.drawString(g, lines[line], x0, y); } } private void drawBorder(MHGraphicsCanvas g) { int x0 = getTitleBounds().x; int y0 = getTitleBounds().y; if (border == null) { g.setColor(MHColor.BLACK); g.fillRect(x0, y0, boxWidth, boxHeight); g.setColor(MHColor.LIGHT_GRAY); g.drawRect(x0, y0, boxWidth, boxHeight); return; } // draw center fill for (int x = x0; x < boxWidth-border[4].getWidth(); x+=border[4].getWidth()) for (int y = y0; y < boxHeight-border[4].getHeight(); y+=border[4].getHeight()) g.drawImage(border[4], x, y); // draw top and bottom edges for (int x = x0 + border[0].getWidth(); x < boxWidth - border[2].getWidth(); x+=border[1].getWidth()) { g.drawImage(border[1], x, y0); g.drawImage(border[7], x, y0 + boxHeight-border[7].getHeight()); } // draw left and right edges for (int y = y0 + border[0].getHeight(); y < boxHeight - border[6].getHeight(); y+=border[3].getHeight()) { g.drawImage(border[3], x0, y); g.drawImage(border[5], x0 + boxWidth-border[5].getWidth(), y); } // draw corners g.drawImage(border[0], x0, y0); g.drawImage(border[2], x0 + boxWidth-border[2].getWidth(), y0); g.drawImage(border[6], x0, y0 + boxHeight-border[6].getHeight()); g.drawImage(border[8], x0 + boxWidth-border[8].getWidth(), y0 + boxHeight-border[8].getHeight()); } private void createBackgroundImage() { backgroundImage = MHPlatform.createImage(MHScreenManager.getDisplayWidth(), MHScreenManager.getDisplayHeight()); MHGraphicsCanvas bg = backgroundImage.getGraphicsCanvas(); getPreviousScreen().render(bg); bg.setColor(BACKGROUND_COLOR); bg.fillRect(0, 0, MHScreenManager.getDisplayWidth(), MHScreenManager.getDisplayHeight()); } @Override public void onKeyUp(MHKeyEvent e) { MHScreenManager.getInstance().changeScreen(getPreviousScreen()); } @Override public void onMouseUp(MHMouseTouchEvent e) { MHScreenManager.getInstance().changeScreen(getPreviousScreen()); } }
package com.lesports.airjordanplayer.ui.data; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.lesports.airjordanplayer.ui.R; import java.text.SimpleDateFormat; import java.util.List; /** * Created by tanliang on 2015/8/28. */ public class SegmentAdapter extends BaseAdapter { private List<SegmentItem> mSegmentItems; private Context mContext; private LayoutInflater mlayoutInflater; private static final int TYPE_DATE = 0; private static final int TYPE_CONTENTE = 1; private static final int TYPE_MAX_COUNT = TYPE_CONTENTE + 1; private ContentViewHolder mContentViewHolder = null; private DateViewHolder mDateViewHolder = null; public SegmentAdapter(Context context, List<SegmentItem> segmentItems) { super(); mContext = context; mlayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mSegmentItems = segmentItems; } @Override public int getItemViewType(int position) { return mSegmentItems.get(position).getDisplayType(); } @Override public int getViewTypeCount() { return TYPE_MAX_COUNT; } @Override public int getCount() { return mSegmentItems.size(); } @Override public Object getItem(int position) { return mSegmentItems.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { SegmentItem segmentItem;// = new SegmentItem(); segmentItem = mSegmentItems.get(position); SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("HH:MM"); String time = simpleDateFormat1.format(segmentItem.getDate()); SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("MM月dd日"); String date = simpleDateFormat2.format(segmentItem.getDate()); mContentViewHolder = new ContentViewHolder(); mDateViewHolder = new DateViewHolder(); int type = getItemViewType(position); switch (type) { case TYPE_CONTENTE: if (convertView == null) { convertView = mlayoutInflater.inflate(R.layout.segment_list_item_contents, null); mContentViewHolder.content = (TextView) convertView.findViewById(R.id.ctrl_segment_content); mContentViewHolder.time = (TextView) convertView.findViewById(R.id.ctrl_segment_time); mContentViewHolder.content.setText(segmentItem.getContent()); mContentViewHolder.time.setText(time); convertView.setTag(mContentViewHolder); } else { mContentViewHolder = (ContentViewHolder) convertView.getTag(); mContentViewHolder.content.setText(segmentItem.getContent()); mContentViewHolder.time.setText(time); } break; case TYPE_DATE: if (convertView == null) { convertView = mlayoutInflater.inflate(R.layout.segment_list_item_date, null); mDateViewHolder.date = (TextView) convertView.findViewById(R.id.ctrl_segment_date_item); mDateViewHolder.date.setText(date); convertView.setTag(mDateViewHolder); } else { mDateViewHolder = (DateViewHolder) convertView.getTag(); mDateViewHolder.date.setText(date); ; } break; } return convertView; } public class ContentViewHolder { public TextView content; public TextView time; } public class DateViewHolder { public TextView date; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.fastHotel.vista.disponibilidad; import FAST.com.botones.IU_Boton; import FAST.com.botones.IU_BotonCheckBox; import FAST.com.calendario.Fecha; import FAST.com.calendario.CalendarioPantallaIU; import FAST.com.clases.Apoyo; import FAST.com.clases.Hora; import FAST.com.clases.Limite; import FAST.com.etiquetas.IU_Etiqueta; import FAST.com.paneles.IU_Panel; import FAST.com.paneles.IU_PanelCampoTexto; import FAST.com.paneles.IU_PanelSpinner; import FAST.com.tablas.IU_Tabla; import FAST.com.ventanas.IUVentanaPadre; import FAST.com.ventanas.IU_VentanaSecundaria; import com.fastHotel.modeloTabla.F_Resultados; import com.fastHotel.modeloTabla.MT_ResultadosHabitacion; import com.fastHotel.modeloTabla.RenderResultado; import com.fastHotel.vista.IU_CheckIn; import java.awt.Color; import java.awt.Cursor; import java.awt.Font; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JFrame; import javax.swing.border.LineBorder; import javax.swing.table.JTableHeader; /** * * @author rudolf */ public class IU_Disponibilidad extends IUVentanaPadre{ public JFrame principal; private IU_Panel panelBusqueda; private IU_PanelCampoTexto campoFechaLlegada; private IU_Etiqueta etiquetaFechaLlegada; private IU_PanelCampoTexto campoFechaSalida; private IU_Etiqueta etiquetaFechaSalida; private IU_PanelSpinner spinnerNoches; private IU_BotonCheckBox botonCheckSimple; private IU_BotonCheckBox botonCheckMatrimonial; private IU_BotonCheckBox botonCheckDobleSimple; private IU_BotonCheckBox botonCheckTriple; private IU_BotonCheckBox botonCheckFamiliar; public IU_Etiqueta etiquetaBuscar; private IU_Panel panelResultados; private IU_Panel panelTabla; public IU_Tabla tablaResultados; public MT_ResultadosHabitacion modeloResultados; public IU_Boton botonCheckIn; public IU_Boton botonReservar; @SuppressWarnings("OverridableMethodCallInConstructor") public IU_Disponibilidad(JFrame ventana, String titulo, int ancho, int alto, int altura){ super(ventana, titulo); this.principal = ventana; moverVentana(); cerrarVentana(); } public void construirPaneles(){ int espacio = 2; int ancho = pantalla.getWidth() - 2*espacio; int alto = pantalla.getHeight() - 2*espacio; panelBusqueda = new IU_Panel(new Limite(espacio, espacio, ancho, alto/12)); pantalla.add(panelBusqueda); construirPanelBusqueda(ancho - 6, alto/12 - 4); panelResultados = new IU_Panel(new Limite(espacio, espacio + alto/12, ancho, (alto - alto/12 - espacio) - (alto - alto/12 - espacio)/6)); panelResultados.agregarColorFondo(Color.orange, Color.red, "HORIZONTAL"); pantalla.add(panelResultados); construirPanelResultados(); construirPanelBotones(); } private void construirPanelBusqueda(int ancho, int alto){ campoFechaLlegada = new IU_PanelCampoTexto("fecha de llegada", "", new Limite(2, 2 + alto/20, ancho/7, alto - alto/10), 40); campoFechaLlegada.iuTexto.setFocusable(false); campoFechaLlegada.iuTexto.deshabilitarTexto(); campoFechaLlegada.cambiarColorTituloTexto(new Color(24, 75, 152), Color.BLACK); panelBusqueda.add(campoFechaLlegada); etiquetaFechaLlegada = new IU_Etiqueta("src/imagenes/fecha.png", new Limite(4 + ancho/7, 2 + alto/20, (alto - alto/10), (alto - alto/10))); etiquetaFechaLlegada.agregarBordeContorno(null); panelBusqueda.add(etiquetaFechaLlegada); etiquetaFechaLlegada.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { CalendarioPantallaIU calendario = new CalendarioPantallaIU(principal, new Fecha().getFechaDia_literal_fechaHotel(), new Fecha(), ANCHO - ANCHO/5, ALTO/2, 50); calendario.mostrar(); if(calendario.getElemento().getObjeto() != null){ if(!((Fecha)calendario.getElemento().getObjeto()).esMenor(new Fecha())){ campoFechaLlegada.iuTexto.setText(((Fecha)calendario.getElemento().getObjeto()).getFechaMysql()); campoFechaSalida.iuTexto.setText(((Fecha)calendario.getElemento().getObjeto()).proximaDiaFecha().getFechaMysql()); spinnerNoches.iuBotonAbajo.setVisible(true); spinnerNoches.iuBotonArriba.setVisible(true); spinnerNoches.campoTexto.setText("1"); campoFechaLlegada.agregarColorFondo(Color.YELLOW, Color.YELLOW, "HORIZONTAL"); campoFechaSalida.agregarColorFondo(Color.YELLOW, Color.YELLOW, "HORIZONTAL"); } else Apoyo.mostrarMensaje(principal, "la fecha que ingreso es INCORRECTA...!"); } } }); campoFechaSalida = new IU_PanelCampoTexto("fecha de salida", "", new Limite(ancho/5, 2 + alto/20, ancho/7, alto - alto/10), 40); campoFechaSalida.iuTexto.setFocusable(false); campoFechaSalida.iuTexto.deshabilitarTexto(); campoFechaSalida.cambiarColorTituloTexto(new Color(24, 75, 152), new Color(180, 0, 0)); panelBusqueda.add(campoFechaSalida); etiquetaFechaSalida = new IU_Etiqueta("src/imagenes/fecha.png", new Limite(4 + ancho/5 + ancho/7, 2 + alto/20, (alto - alto/10), (alto - alto/10))); etiquetaFechaSalida.agregarBordeContorno(null); panelBusqueda.add(etiquetaFechaSalida); etiquetaFechaSalida.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if(!campoFechaLlegada.getDato().isEmpty()){ CalendarioPantallaIU calendario = new CalendarioPantallaIU(principal, new Fecha().getFechaDia_literal_fechaHotel(), new Fecha(), ANCHO - ANCHO/5, ALTO/2, 50); calendario.mostrar(); if(((Fecha)calendario.getElemento().getObjeto()).esMayor(new Fecha(campoFechaLlegada.getDato(), "yyyy-MM-dd"))){ campoFechaSalida.iuTexto.setText(((Fecha)calendario.getElemento().getObjeto()).getFechaMysql()); int numero = new Fecha(campoFechaLlegada.getDato(), "yyyy-MM-dd").restarDiasFecha(((Fecha)calendario.getElemento().getObjeto())); spinnerNoches.campoTexto.setText(String.valueOf(numero)); }else Apoyo.mostrarMensaje(principal, "la fecha que ingreso es INCORRECTA...!"); } } }); spinnerNoches = new IU_PanelSpinner("noches", new Limite(ancho/2 - ancho/10, 2 + alto/20, ancho/10, alto - alto/10), 40, 1, 1, 50); spinnerNoches.iuBotonAbajo.setVisible(false); spinnerNoches.iuBotonArriba.setVisible(false); spinnerNoches.setColor(new Color(24, 75, 152), Color.BLACK, Color.BLACK); spinnerNoches.campoTexto.setText(""); panelBusqueda.add(spinnerNoches); spinnerNoches.iuBotonArriba.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if(!campoFechaLlegada.getDato().isEmpty()){ int noches = (int)spinnerNoches.getDato(); Fecha fecha = new Fecha(campoFechaLlegada.getDato(), "yyyy-MM-dd"); for (int i = 0; i < noches; i++) { fecha = fecha.proximaDiaFecha(); } campoFechaSalida.iuTexto.setText(fecha.getFechaMysql()); } } }); spinnerNoches.iuBotonAbajo.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if(!campoFechaLlegada.getDato().isEmpty()){ int noches = (int)spinnerNoches.getDato(); Fecha fecha = new Fecha(campoFechaLlegada.getDato(), "yyyy-MM-dd"); for (int i = 0; i < noches; i++) { fecha = fecha.proximaDiaFecha(); } campoFechaSalida.iuTexto.setText(fecha.getFechaMysql()); } } }); botonCheckSimple = new IU_BotonCheckBox("SIMPLE", new Limite(ancho/20 + ancho/2, 2 + alto/20, ancho/10, etiquetaFechaLlegada.getAlto()/2), false); botonCheckSimple.setColorSeleccion(Color.BLACK, new Color(180, 0, 0)); panelBusqueda.add(botonCheckSimple); botonCheckMatrimonial = new IU_BotonCheckBox("MATRIMONIAL", new Limite(ancho/20 + ancho/2 + ancho/10 + 4, 2 + alto/20, ancho/6, etiquetaFechaLlegada.getAlto()/2), false); botonCheckMatrimonial.setColorSeleccion(Color.BLACK, new Color(180, 0, 0)); panelBusqueda.add(botonCheckMatrimonial); botonCheckTriple = new IU_BotonCheckBox("TRIPLE", new Limite(ancho/20 + ancho/2 + ancho/10 + 8 + ancho/6, 2 + alto/20, ancho/10, etiquetaFechaLlegada.getAlto()/2), false); botonCheckTriple.setColorSeleccion(Color.BLACK, new Color(180, 0, 0)); panelBusqueda.add(botonCheckTriple); etiquetaBuscar = new IU_Etiqueta("src/imagenes/buscar.png", new Limite(ancho - (alto - alto/10), 2 + alto/20, (alto - alto/10), (alto - alto/10))); etiquetaBuscar.agregarBordeContorno(null); panelBusqueda.add(etiquetaBuscar); botonCheckDobleSimple = new IU_BotonCheckBox("DOBLE SIMPLE", new Limite(ancho/20 + ancho/2, 2 + alto/20 + etiquetaFechaLlegada.getAlto()/2, ancho/5, etiquetaFechaLlegada.getAlto()/2), false); botonCheckDobleSimple.setColorSeleccion(Color.BLACK, new Color(180, 0, 0)); panelBusqueda.add(botonCheckDobleSimple); botonCheckFamiliar = new IU_BotonCheckBox("FAMILIAR", new Limite(ancho/20 + ancho/2 + 4 + ancho/5, 2 + alto/20 + etiquetaFechaLlegada.getAlto()/2, ancho/7, etiquetaFechaLlegada.getAlto()/2), false); botonCheckFamiliar.setColorSeleccion(Color.BLACK, new Color(180, 0, 0)); panelBusqueda.add(botonCheckFamiliar); } private void construirPanelResultados(){ int ancho = panelResultados.getAncho(); int alto = panelResultados.getAlto(); panelTabla = new IU_Panel(new Limite(0, 0, ancho, alto)); panelResultados.add(panelTabla); construirPanelTabla(); } private void construirPanelTabla(){ int espacio = 4; int ancho = panelTabla.getAncho() - 2*espacio; int alto = panelTabla.getAlto() - 2*espacio; String[] nombre_cabecera = {"N°","habitacion","tipo de habitacion","cap.","piso","camas","precio","estado","hora disponible","•"}; int[] ancho_cabecera = {4, 10, 19, 4, 10, 21, 10, 10, 10, 2}; modeloResultados = new MT_ResultadosHabitacion(nombre_cabecera); tablaResultados = new IU_Tabla(modeloResultados, espacio, espacio, ancho, alto); tablaResultados.setFuente_letra(new Font("Verdana", Font.PLAIN, 14)); JTableHeader th = tablaResultados.getTableHeader(); Font fuente = new Font("Verdana", Font.PLAIN, 14); th.setFont(fuente); tablaResultados.setCursor(new Cursor(Cursor.HAND_CURSOR)); tablaResultados.setShowHorizontalLines(false); tablaResultados.setShowVerticalLines(true); tablaResultados.setColumnSelectionAllowed(false); tablaResultados.setRowSelectionAllowed(false); tablaResultados.establecer_ancho_columnas(ancho_cabecera); panelTabla.add(tablaResultados.deslizador); modeloResultados.agregar_fila(new F_Resultados("101 S", "SIMPLE", 1, "2° piso", "1 cama de 1 1/2 plaza", 170.0, "VACANTE", new Hora().cadenaHora()+" "+new Hora().getFormato(), false, null)); modeloResultados.agregar_fila(new F_Resultados("105 S", "SIMPLE", 1, "2° piso", "1 cama de 1 1/2 plaza", 170.0, "VACANTE", new Hora().cadenaHora()+" "+new Hora().getFormato(), false, null)); for (int i = 0; i < modeloResultados.tipoColumnas.length - 1; i++) { tablaResultados.setDefaultRenderer(modeloResultados.tipoColumnas[i], new RenderResultado()); } } private void construirPanelBotones(){ int espacio = 5; int ancho = pantalla.getWidth() - 2*espacio; int alto = pantalla.getHeight() - 2*espacio; botonCheckIn = new IU_Boton("check in", new Limite(ancho - alto/7 + espacio, alto - alto/7 + espacio, alto/7, alto/7), 5); pantalla.add(botonCheckIn); botonCheckIn.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { IU_CheckIn iuCheckIn = new IU_CheckIn(principal, "CHECK-IN a la habitacion: 204 TM (TRIPLE MATRIMONIAL)", ANCHO, ALTO, 50); } }); botonReservar = new IU_Boton("reservar", new Limite(ancho - 2*alto/7, alto - alto/7 + espacio, alto/7, alto/7), 5); pantalla.add(botonReservar); } public boolean estaSeleccionadoFilaTabla(){ return tablaResultados.getSelectedRow() > -1; } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.bind; import org.springframework.core.MethodParameter; /** * {@link ServletRequestBindingException} subclass that indicates that a matrix * variable expected in the method parameters of an {@code @RequestMapping} * method is not present among the matrix variables extracted from the URL. * * @author Juergen Hoeller * @since 5.1 * @see MissingPathVariableException */ @SuppressWarnings("serial") public class MissingMatrixVariableException extends MissingRequestValueException { private final String variableName; private final MethodParameter parameter; /** * Constructor for MissingMatrixVariableException. * @param variableName the name of the missing matrix variable * @param parameter the method parameter */ public MissingMatrixVariableException(String variableName, MethodParameter parameter) { this(variableName, parameter, false); } /** * Constructor for use when a value was present but converted to {@code null}. * @param variableName the name of the missing matrix variable * @param parameter the method parameter * @param missingAfterConversion whether the value became null after conversion * @since 5.3.6 */ public MissingMatrixVariableException( String variableName, MethodParameter parameter, boolean missingAfterConversion) { super("", missingAfterConversion, null, new Object[] {variableName}); this.variableName = variableName; this.parameter = parameter; getBody().setDetail("Required path parameter '" + this.variableName + "' is not present."); } @Override public String getMessage() { return "Required matrix variable '" + this.variableName + "' for method parameter type " + this.parameter.getNestedParameterType().getSimpleName() + " is " + (isMissingAfterConversion() ? "present but converted to null" : "not present"); } /** * Return the expected name of the matrix variable. */ public final String getVariableName() { return this.variableName; } /** * Return the method parameter bound to the matrix variable. */ public final MethodParameter getParameter() { return this.parameter; } }
package TestClient; public class Threadable extends Thread { String name; SharedData theDemo; public Threadable(String name,SharedData theDemo) { this.theDemo = theDemo; this.name = name; start(); } @Override public void run() { theDemo.test(name); } }
/** * */ package com.example.demo.service; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Service; import com.example.demo.domian.User; import com.example.demo.utils.JsonUtils; /** * @author xuminzhe 2017年8月9日 上午10:46:36 * */ @Service public class DemoService { @Autowired private RedisTemplate<String, Object> redisTemplate; @Autowired private RedisTemplate<String, User> redisUserTemplate; public void setKey(Map<String, Map<?, ?>> map) { ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue(); for (Map.Entry<String, Map<?, ?>> entry : map.entrySet()) { String jsonStringFromMap = JsonUtils.getJsonStringFromMap(entry.getValue()); opsForValue.set(entry.getKey(), jsonStringFromMap); } } public void setKeyMap(Map<String, Map<?, ?>> map) { ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue(); for (Map.Entry<String, Map<?, ?>> entry : map.entrySet()) { String jsonStringFromMap = JsonUtils.getJsonStringFromMap(entry.getValue()); opsForValue.set(entry.getKey(), jsonStringFromMap); } } public void getKey(String boxUid) { ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue(); if (redisTemplate.hasKey(boxUid)) { Object object = opsForValue.get(boxUid); System.out.println(object); } } public void setUser(User user) { ValueOperations<String, User> opsForValue = redisUserTemplate.opsForValue(); opsForValue.set(user.getUsername(), user); Integer age = opsForValue.get(user.getUsername()).getAge(); String username = opsForValue.get(user.getUsername()).getUsername(); System.out.println(age + " " + username); } }
package io.papermc.hangar.controller; import org.springframework.boot.web.servlet.error.ErrorController; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; @Controller public class HangarErrorController extends HangarController implements ErrorController { @RequestMapping("/error") public ModelAndView handleError(HttpServletRequest request) { Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE); ModelAndView mav = new ModelAndView("errors/error"); // TODO show custom message with error if applicable if (status != null) { int statusCode = Integer.parseInt(status.toString()); if (statusCode == HttpStatus.NOT_FOUND.value()) { mav = new ModelAndView("errors/notFound"); } else if (statusCode == HttpStatus.GATEWAY_TIMEOUT.value() || statusCode == HttpStatus.REQUEST_TIMEOUT.value()) { mav = new ModelAndView("errors/timeout"); } } return fillModel(mav); } @Override public String getErrorPath() { return "/error"; } }
package ffm.slc.model.enums; /** * Type of environment a user account could access */ public enum EnvironmentType { PRODUCTION("Production"), SANDBOX("Sandbox"); private String prettyName; EnvironmentType(String prettyName) { this.prettyName = prettyName; } @Override public String toString() { return prettyName; } }
package com.zl.dao.front; import com.zl.pojo.client.Client; /** * 客户表实体类DAO层 * @author KINDER * */ public interface ClientDao { /** * 客户登录 */ public Client clientLogin(Client client); /** * 客户注册 */ public int clientRegister(Client client); /** * 修改绑定的手机号码 */ public int updateClientPhone(Client client); /** * 判断原手机号是否正确 */ public Client queryClientPhone(Client client); }
package com.example.hrmsEightDay.business.abstracts; import java.util.List; import com.example.hrmsEightDay.core.utilities.results.DataResult; import com.example.hrmsEightDay.core.utilities.results.Result; import com.example.hrmsEightDay.entities.abstracts.User; public interface UserService { Result add(User user); DataResult<List<User>> getAll(); DataResult<User> getUserByEmail(String email); }
package utility; import org.checkerframework.checker.units.qual.A; import java.sql.*; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class DB_Utility { private static Connection con; private static Statement stm; private static ResultSet rs; private static ResultSetMetaData rsmd; /** * Create connection method , just checking one connection successful or not */ public static void createConnection(){ String url = ConfigurationReader.getProperty("hr.database.url") ; String username = ConfigurationReader.getProperty("hr.database.username") ; String password = ConfigurationReader.getProperty("hr.database.password") ; /*try { Connection con = DriverManager.getConnection(url , username, password) ; System.out.println("CONNECTION SUCCESSFUL"); } catch (SQLException e) { System.out.println("CONNECTION HAS FAILED " + e.getMessage() ); }*/ createConnection(url,username,password); } public static void createConnection(String url, String username, String password) { try { con = DriverManager.getConnection(url, username, password); System.out.println("Connection Successful"); } catch (SQLException e) { System.out.println("Connection has Failed" + e.getMessage()); } } public static ResultSet runQuery(String query) { try { stm = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY); rs = stm.executeQuery(query); rsmd = rs.getMetaData(); } catch (SQLException e) { System.out.println("ERROR WHILE GETTING RESULTSET " + e.getMessage()); } return rs; } public static void destroy(){ try { if(rs!= null) { rs.close(); } if(stm != null){ stm.close(); } if(con != null){ con.close(); } } catch (SQLException throwables) { throwables.printStackTrace(); } } // reset cursor private static void resetCursor(){ try { rs.beforeFirst(); } catch (SQLException throwables) { throwables.printStackTrace(); } } public static int getRowCount(){ int rowCount = 0; try { rs.last(); rowCount= rs.getRow(); rs.beforeFirst(); } catch (SQLException e) { System.out.println("ERROR WHILE GETTING ROW COUNT " + e.getMessage()); }finally { resetCursor(); } return rowCount; } public static int getColumnCount(){ int columnCount = 0; try { columnCount = rsmd.getColumnCount(); } catch (SQLException e) { System.out.println("ERROR WHILE COUNTING THE COLUMN " + e.getMessage()); } return columnCount; } public static List<String> getColumnNames(){ List<String> columnNamesList = new ArrayList<>(); try { for (int colNum = 1; colNum <= rsmd.getColumnCount() ; colNum++) { String colName =rsmd.getColumnName(colNum); columnNamesList.add(colName); } } catch (SQLException e) { System.out.println("ERROR WHILE GETTING COLUMN NAMES" + e.getMessage()); } return columnNamesList; } public static List<String> getRowDataAsList(int rowNum){ List<String> rowDataList = new ArrayList<>(); try { rs.absolute(rowNum); for (int colNum = 1; colNum <= getColumnCount() ; colNum++) { String cellValue = rs.getString(colNum ); rowDataList.add(cellValue); } } catch (SQLException e) { System.out.println("ERROR WHILE getRowDataList" + e.getMessage()); }finally { resetCursor(); } return rowDataList; } public static String getCellValue(int rowNum , int columnIndex) { String cellValue = "" ; try { rs.absolute(rowNum) ; cellValue = rs.getString(columnIndex ) ; } catch (SQLException e) { System.out.println("ERROR OCCURRED WHILE getCellValue " + e.getMessage() ); }finally { resetCursor(); } return cellValue ; } public static String getCellValue(int rowNum, String columnName){ String cellValue = ""; try{ rs.absolute(rowNum); cellValue = rs.getString(columnName); }catch (SQLException e){ System.out.println("ERROR OCCURRED WHILE getCellValue" + e.getMessage()); }finally { resetCursor(); } return cellValue; } // get first cell value from First row First Column public static String getFirstRowFirstColumn(){ return getCellValue(1,1); } public static String getColumnDataAtRow(int rowNum, int columnIndex){ String result = ""; try { rs.absolute(rowNum); result = rs.getString(columnIndex); rs.beforeFirst(); } catch (SQLException throwables) { System.out.println("Error While getColumnDataAtRow"); }finally { resetCursor(); } return result; } public static String getColumnDataAtRow(int rowNum, String columnName){ String result = ""; try { rs.absolute(rowNum); result = rs.getString(columnName); rs.beforeFirst(); } catch (SQLException throwables) { System.out.println("Error While getColumnDataAtRow"); }finally { resetCursor(); } return result; } public static List<String> getColumnDataAsList(int columnIndex){ List<String> columnDataList = new ArrayList<>(); try { rs.beforeFirst(); while (rs.next()){ String celValue = rs.getString(columnIndex); columnDataList.add(celValue); } rs.beforeFirst(); }catch (SQLException e){ System.out.println("ERROR WHILE getColumnDataAsList " + e.getMessage()); }finally { resetCursor(); } return columnDataList; } public static List<String> getColumnDataAsList(String columnName){ List<String> columnDataList = new ArrayList<>(); try { rs.beforeFirst(); while (rs.next()){ String celValue = rs.getString(columnName); columnDataList.add(celValue); } rs.beforeFirst(); }catch (SQLException e){ System.out.println("ERROR WHILE getColumnDataAsList " + e.getMessage()); }finally { resetCursor(); } return columnDataList; } // display all data public static void displayAllData(){ resetCursor(); try { while (rs.next()){ //get each raw for (int colNum = 1; colNum <= getColumnCount(); colNum++) { //System.out.print( rs.getString(colIndex) + "\t" ); System.out.printf("%-25s", rs.getString(colNum)); } System.out.println(); } } catch (SQLException e) { System.out.println("ERROR WHILE GETTING ALL DATA " + e.getMessage()); }finally { resetCursor(); } } public static Map<String,String> getRowMap(int rowNum){ Map<String, String> rowMap = new LinkedHashMap<>(); try { rs.absolute(rowNum); for (int colNum = 1; colNum <= getColumnCount() ; colNum++) { String colName = rsmd.getColumnName(colNum); String cellValue = rs.getString(colNum); rowMap.put(colName,cellValue); } rs.beforeFirst(); } catch (SQLException e) { System.out.println("ERROR AT ROW MAP FUNCTION " + e.getMessage()); }finally { resetCursor(); } return rowMap; } public static List<Map<String,String>> getAllRowAsListOfMap(){ List<Map<String,String>> allRowListOfMap = new ArrayList<>(); int rowCount = getRowCount(); // move from first row till last row // get each row as map object and add it to the list for (int rowIndex = 1; rowIndex <= rowCount ; rowIndex++) { Map<String,String> rowMap = getRowMap(rowIndex); allRowListOfMap.add(rowMap); } resetCursor(); return allRowListOfMap; } }
package com.examples.io.designpatterns.strategy; public class Context { public Strategy strategy; public Context(Strategy strategy) { this.strategy = strategy; } public void doOperation(int num1,int num2) { strategy.performOperation( num1, num2); } public void changeStrategy(Strategy anotherStrategy){ strategy = anotherStrategy; } }
package com.dotech.core.db.model.dao; import com.dotech.core.db.DBHelper; import com.dotech.core.db.model.idao.IDao; import com.j256.ormlite.dao.Dao; import java.sql.SQLException; import java.util.Collection; import java.util.List; import java.util.Map; /** * Clase que implementa las funciones DAO y Operaciones CRUD * * @param <T> */ public class DaoImpl<T> implements IDao<T> { private final DBHelper dbHelper; private final Class<T> type; /** * Constructor * @param type * @param dbHelper */ public DaoImpl(Class<T> type, DBHelper dbHelper) { this.dbHelper = dbHelper; this.type = type; } /** * Obttiene todos los registros * * @return * @throws SQLException */ @Override public List<T> selectAll() throws SQLException { return dbHelper.getAll(getMyType()); } /** * Obtiene los registros de acuerdo al HashMap (Filtra la informacion como si fuera un Where) * * @param query * @return * @throws SQLException */ @Override public List<T> select(Map<String, Object> query) throws SQLException { return dbHelper.query(getMyType(), query); } /** * Crear o actualizar un registro de la tabla * * @param entity * @return * @throws SQLException */ @Override public boolean insertOrUpdate(T entity) throws SQLException { dbHelper.createOrUpdate(entity); return true; } /** * Elimina los registros de la tabla * * @param entities * @return * @throws SQLException */ @Override public boolean delete(Collection<T> entities) throws SQLException { dbHelper.deleteObjects(getMyType(), entities); return true; } /** * Regresa el Dao de la tabla correspondiente, nos ayudara cuando necesitemos realizar * inner join o consultas personalizados * * @return * @throws SQLException */ @Override public Dao<T, ?> getDao() throws SQLException { return dbHelper.getDaoImpl(getMyType()); } /** * Regresa la clase que se utilizo para la clase generic * @return */ private Class<T> getMyType() { return this.type; } }
package com.vinodborole.portal.security.auth.jwt.extractor; import org.apache.commons.lang3.StringUtils; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.stereotype.Component; /** * An implementation of {@link IPortalTokenExtractor} extracts token from * Authorization: Bearer scheme. * * @author vinod borole * * */ @Component public class PortalJwtHeaderTokenExtractor implements IPortalTokenExtractor { public static final String HEADER_PREFIX = "Bearer "; @Override public String extract(String header) { if (StringUtils.isBlank(header)) { throw new AuthenticationServiceException("Authorization header cannot be blank!"); } if (header.length() < HEADER_PREFIX.length()) { throw new AuthenticationServiceException("Invalid authorization header size."); } return header.substring(HEADER_PREFIX.length(), header.length()); } }
package com.yoga.entity; /** * TbUserRole entity */ public class TbUserRole implements java.io.Serializable { // Fields private Integer id; private TbUser tbUser; private TbRole tbRole; // Constructors /** default constructor */ public TbUserRole() { } /** full constructor */ public TbUserRole(TbUser tbUser, TbRole tbRole) { this.tbUser = tbUser; this.tbRole = tbRole; } // Property accessors public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public TbUser getTbUser() { return this.tbUser; } public void setTbUser(TbUser tbUser) { this.tbUser = tbUser; } public TbRole getTbRole() { return this.tbRole; } public void setTbRole(TbRole tbRole) { this.tbRole = tbRole; } }
package com.jd.jarvisdemonim.ui.presenter; import com.jd.jdkit.IInterface.mvp.BaseViewImpl; import java.util.List; /** * Auther: Jarvis Dong * Time: on 2017/2/21 0021 * Name: * OverView:MVP NormalTestMvpActivity设置在presenter中控制activity中的view层的控制; * Usage: 可添加额外抽象方法; * * MVP主要是通过此接口将View设置数据; * * @see NormalTestMvpActivity */ public interface NTestMvpView<T> extends BaseViewImpl { void adapterNotify(List<T> mlist); void adapterNotify(T t); }
package com.example; import java.util.ArrayList; import java.util.List; public class SortEvenOdd implements ISortEvenOdd { /* * Time Complexity: O(2n) which is similar to O(n), * because constants are ignored in Big O notations * * Space Complexity: O(n) */ @Override public List<Integer> sort(List<Integer> list) { int length = list.size(); List<Integer> resultList = new ArrayList<>(length); for (int value : list) { if (value % 2 != 0) { // if odd resultList.add(value); } } for (int value : list) { if (value % 2 == 0) { // if even resultList.add(value); } } return resultList; } }
package aeroportSpring.model; import javax.persistence.Column; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; @Entity @DiscriminatorValue("CEI") @NamedQueries({ @NamedQuery(name="ClientEI.findAllClientEI", query="select cei from ClientEI cei"), @NamedQuery(name="ClientEI.findClientEIByVille", query="select cei from ClientEI cei where lower(cei.adresse.ville) like :ville") }) public class ClientEI extends Client { @Column(name = "prenom_client",length=100) private String prenomEI; public ClientEI() { } public ClientEI(String prenomEI) { super(); this.prenomEI = prenomEI; } public String getPrenomEI() { return prenomEI; } public void setPrenomEI(String prenomEI) { this.prenomEI = prenomEI; } }