text
stringlengths
10
2.72M
package com.android.cartloading.dto; import com.google.gson.annotations.SerializedName; /** * Created by Toader on 6/6/2015. */ public class ImageDTO { @SerializedName("_id") public String _id; @SerializedName("image") public String imge_url; @SerializedName("large") public String image_url_large; @SerializedName("medium") public String image_url_medium; public String get_id() { return _id; } public String getImge_url() { return imge_url; } public String getImage_url_large() { return image_url_large; } public String getImage_url_medium() { return image_url_medium; } }
package com.sinodynamic.hkgta.service.adm; import com.sinodynamic.hkgta.dto.staff.RequestStaffDto; import com.sinodynamic.hkgta.dto.staff.StaffCoachInfoDto; import com.sinodynamic.hkgta.dto.staff.StaffListDto; import com.sinodynamic.hkgta.dto.staff.StaffMasterInfoDto; import com.sinodynamic.hkgta.dto.staff.StaffPasswordDto; import com.sinodynamic.hkgta.dto.staff.UserDto; import com.sinodynamic.hkgta.entity.crm.StaffMaster; import com.sinodynamic.hkgta.entity.crm.StaffProfile; import com.sinodynamic.hkgta.service.IServiceBase; import com.sinodynamic.hkgta.util.ResponseMsg; import com.sinodynamic.hkgta.util.constant.StaffMasterOrderByCol; import com.sinodynamic.hkgta.util.pagination.ListPage; import com.sinodynamic.hkgta.util.response.ResponseResult; /** * @author Junfeng_Yan * @since May 28 2015 */ public interface StaffMasterService extends IServiceBase<StaffMasterInfoDto>{ public ListPage<StaffMasterInfoDto> getStaffMasterList(ListPage<StaffMasterInfoDto> pListPage, StaffMasterOrderByCol orderCol,String sortType, StaffListDto dto) throws Exception; public ResponseResult getStaffMasterByUserId(String userId) throws Exception; public ResponseMsg saveStaffMaster(RequestStaffDto staffDto , String createBy) throws Exception; public ResponseMsg saveCoachDescription(StaffCoachInfoDto coachDto , String createBy) throws Exception; public ResponseMsg updateStaffMasterOld(RequestStaffDto staffDto , String updateBy) throws Exception; public ResponseMsg saveStaffMasterOld(UserDto staffDto , String createBy) throws Exception; public ResponseMsg saveStaffMaster(UserDto staffDto , String createBy) throws Exception; public ResponseMsg updateStaffMaster(UserDto staffDto , String updateBy) throws Exception; public ResponseMsg updateStaff(UserDto staffDto , String updateBy) throws Exception; public ResponseMsg updateProfilePhoto(StaffProfile p) throws Exception; public ResponseMsg changeStaffMasterStatus(RequestStaffDto staffDto , String updateBy) throws Exception; public ResponseResult staffNoIsUsed(String staffNo) throws Exception; public ResponseResult validatePassport(String loginId, String passportType, String passportNo) throws Exception; public ResponseResult emailIsUsed(String email) throws Exception; public ResponseResult changePsw(StaffPasswordDto staffPsw) throws Exception; public void changeExpiredStaffMasterStatus() throws Exception; public ResponseResult getStaffMasterOnlyByUserId(String userId); public StaffMaster getStaffMaster(String userId); public ResponseResult getCoachInfoByUserId(String userId); public String getStaffs(); public String getCoachs(); public void autoQuitExpireStaff(); public void sendEmail2Staff(String userId, UserDto staffDto) throws Exception; }
package cn.test.enumTest.EnumMap; import lombok.extern.slf4j.Slf4j; import java.util.EnumMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Created by xiaoni on 2019/4/27. */ @Slf4j public class Herb { //烹饪用的香草 public enum Type {ANNUAL, PERENNIAL, BIENNIAL} private final String name; private final Type type; Herb(String name, Type type) { this.name = name; this.type = type; } @Override public String toString() { return name; } public static void main(String[] args) { //假设一个香草的数组,表示一座花园中的植物,你想要按照类型(一年生,多年生或者两年生植物)进行组织之后将这些植物列出来。 Herb[] garden = {new Herb("a", Type.ANNUAL), new Herb("b", Type.BIENNIAL), new Herb("c", Type.PERENNIAL), new Herb("d", Type.ANNUAL)}; Map<Type, Set<Herb>> herbsByType = new EnumMap<Herb.Type, Set<Herb>>(Herb.Type.class); for (Herb.Type t : Herb.Type.values()) { herbsByType.put(t, new HashSet<Herb>()); } for (Herb h : garden) { herbsByType.get(h.type).add(h); } log.info(herbsByType.toString()); } }
package net.lantrack.framework.sysbase.service.imp; import java.util.Arrays; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.quartz.Job; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import net.lantrack.framework.core.entity.BaseEntity; import net.lantrack.framework.core.entity.PageEntity; import net.lantrack.framework.core.lcexception.ServiceException; import net.lantrack.framework.core.service.BaseService; import net.lantrack.framework.sysbase.dao.SysTaskDao; import net.lantrack.framework.sysbase.entity.SysTask; import net.lantrack.framework.sysbase.entity.SysTaskExample; import net.lantrack.framework.sysbase.entity.SysTaskExample.Criteria; import net.lantrack.framework.sysbase.service.SysTaskService; import net.lantrack.framework.sysbase.util.QuartzManager; /** * 任务管理 * @author ypn * 2018年1月30日 */ @Service public class SysTaskServiceImp extends BaseService implements SysTaskService { @Autowired protected SysTaskDao sysTaskDao; @Override public SysTask update(SysTask entity) throws ServiceException { SysTaskExample taskExample=new SysTaskExample(); Criteria cr = taskExample.createCriteria(); cr.andTaskNameEqualTo(entity.getTaskName()); List<SysTask> list=this.sysTaskDao.selectByExample(taskExample); boolean up=false; if(list!=null&&list.size()>0){ SysTask task = list.get(0); if(task.getId().equals(entity.getId())){ up = true; } }else{ up=true; } if(up){ try { int flag=this.sysTaskDao.updateByPrimaryKeySelective(entity); if(flag==1){ QuartzManager.modifyJobTime(entity.getJobName(), entity.getTriggerName(),entity.getCronExps()); } } catch (Exception e) { this.logger.error(e); throw new ServiceException(e.getMessage()); } }else{ throw new ServiceException("当前任务中已存在相同记录"); } return entity; } @Override public SysTask save(SysTask entity) throws ServiceException { try { SysTaskExample taskExample = new SysTaskExample(); SysTaskExample.Criteria cr = taskExample.createCriteria(); cr.andTaskNameEqualTo(entity.getTaskName()); List<SysTask> list = this.sysTaskDao.selectByExample(taskExample); boolean up=false; if(list==null||list.size()==0){ up = true; } if(up){ int flag=this.sysTaskDao.insertSelective(entity); //System.out.println("result flag="+flag); if(flag==1){ //开启新线程执行定时任务 Thread thread = new Thread(){ public void run(){ try { QuartzManager.addJob(entity.getJobName(),entity.getTriggerName(), (Class<? extends Job>)Class.forName(entity.getClassName()),entity.getCronExps(),null); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; thread.start(); } }else{ throw new ServiceException("当前任务已存在"); } } catch (Exception e) { e.printStackTrace(); } return entity; } @Override public SysTask queryById(Object id) { if (id==null) { this.logger.error("id can not be null or empty!"); throw new ServiceException("id can not be null or empty!"); } Integer pasId = Integer.valueOf(id.toString()); SysTask task=null; try { task=this.sysTaskDao.selectByPrimaryKey(pasId); } catch (Exception e) { e.printStackTrace(); this.logger.error(e); throw new ServiceException(e.getMessage()); } return task; } @Override public void deleteById(Object id, String update_by, boolean ifLogic) throws ServiceException { if (id==null) { throw new ServiceException("id can not be null or empty!"); } Integer pasId = Integer.valueOf(id.toString()); int flag=0; if (!ifLogic) { // 物理删除 flag=this.sysTaskDao.deleteByPrimaryKey(pasId); } else { // 逻辑删除结束 SysTask task = new SysTask(); task.setCreateDate(null); task.setUpdateBy(update_by); task.setDelFlag(BaseEntity.YES); task.setId(pasId); flag=this.sysTaskDao.updateByPrimaryKeySelective(task); } if(flag==1){ SysTask entity=this.queryById(id); //删除对应的定时任务 if(entity!=null){ QuartzManager.removeJob(entity.getJobName(), entity.getTriggerName()); } } } @Override public void deleteByIds(String ids, String update_by, boolean ifLogic) throws ServiceException { if (StringUtils.isBlank(ids)) { this.logger.error("id can not be null or empty!"); } String[] split = ids.split(","); // 添加条件 SysTaskExample taskExample = new SysTaskExample(); SysTaskExample.Criteria cr = taskExample.createCriteria(); cr.andIdIn(Arrays.asList(split)); int flag=0; if (!ifLogic) { // 物理删除 flag=this.sysTaskDao.deleteByExample(taskExample); } else { // 此处用逻辑删除 SysTask task = new SysTask(); task.setCreateDate(null); task.setUpdateBy(update_by); task.setDelFlag(BaseEntity.YES); flag=this.sysTaskDao.updateByExampleSelective(task, taskExample); } if(flag==1){ for(int i=0;i<split.length;i++){ SysTask entity=this.queryById(split[i]); //删除对应的定时任务 if(entity!=null){ QuartzManager.removeJob(entity.getJobName(), entity.getTriggerName()); } } } } @Override public void getPage(SysTask entity, PageEntity pageentity) { // TODO Auto-generated method stub } @Override public void getPageRe(SysTask entity, PageEntity pageentity) { // TODO Auto-generated method stub } @Override public void deleteByIdsRe(String ids, String update_by) throws ServiceException { // TODO Auto-generated method stub } @Override public List<SysTask> getAll(SysTask entity) { // TODO Auto-generated method stub return null; } /** * 查找已开启的任务,并加入定时任务中 * @return */ @Override public List<SysTask> startTask(String status) { SysTaskExample taskExample=new SysTaskExample(); Criteria cr = taskExample.createCriteria(); cr.andTaskStatusEqualTo(status); List<SysTask> list=this.sysTaskDao.selectByExample(taskExample); if(list!=null && list.size()>0){ for(SysTask entity:list){ //开启新线程执行定时任务 Thread thread = new Thread(){ public void run(){ try { QuartzManager.addJob(entity.getJobName(),entity.getTriggerName(), (Class<? extends Job>)Class.forName(entity.getClassName()),entity.getCronExps(),entity.getFieldJson()); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; thread.start(); } } return list; } @Override public SysTask selectByJobName(String jobName) { SysTask task=null; try { if(StringUtils.isBlank(jobName)) { task=new SysTask(); }else { task=this.sysTaskDao.selectByJobName(jobName); } if(task==null) { task=new SysTask(); } } catch (Exception e) { e.printStackTrace(); throw new ServiceException(e.getMessage()); } return task; } }
package gameassets; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.FloatControl; import java.io.File; public class PlayAudio { private final String name; public boolean isMuted; private Clip clip; private FloatControl gainControl; public PlayAudio(String name) { this.name = name; } public void play(boolean loop) { try { AudioInputStream audioStream = AudioSystem.getAudioInputStream(new File(Constants.SOUND_DIR + name).getAbsoluteFile()); clip = AudioSystem.getClip(); clip.open(audioStream); if (loop) clip.loop(Clip.LOOP_CONTINUOUSLY); clip.start(); gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN); } catch (Exception e) { System.err.println(e.getMessage()); } } public void setVolume(float volume) { float range = gainControl.getMaximum() - gainControl.getMinimum(); float gain = (range * volume) + gainControl.getMinimum(); gainControl.setValue(gain); } public void stop() { clip.stop(); isMuted = true; } public void resume() { clip.start(); isMuted = false; } public void close() { clip.close(); } }
package com.yc.education.controller.account; import com.github.pagehelper.PageInfo; import com.yc.education.controller.BaseController; import com.yc.education.model.account.AccountSaleInvoice; import com.yc.education.model.account.AccountSaleInvoiceInfo; import com.yc.education.model.account.AccountSaleInvoiceInfoProperty; import com.yc.education.service.account.IAccountSaleInvoiceInfoService; import com.yc.education.service.account.IAccountSaleInvoiceService; import com.yc.education.util.AppConst; import com.yc.education.util.StageManager; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.MouseEvent; import javafx.scene.layout.VBox; import javafx.stage.Stage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import java.net.URL; import java.text.SimpleDateFormat; import java.util.List; import java.util.ResourceBundle; /** * 销项发票小窗口 */ @Controller public class AccountSaleInvoiceMiniController extends BaseController implements Initializable { @Autowired IAccountSaleInvoiceService iAccountSaleInvoiceService; @Autowired IAccountSaleInvoiceInfoService iAccountSaleInvoiceInfoService; @FXML VBox menu_first; // 第一页 @FXML VBox menu_prev; // 上一页 @FXML VBox menu_next; // 下一页 @FXML VBox menu_last; // 最后一页 @FXML Button client_sure; @FXML CheckBox che_recently; @FXML TextField num; @FXML TextField findOrder; // 订单号 @FXML TableView tableView; @FXML TableColumn id; @FXML TableColumn order_no; @FXML TableColumn order_date; @FXML TableColumn customer_no; @FXML TableColumn customer_name; @FXML TableColumn invoice_no; @FXML TableColumn status; @FXML TableColumn cancel; // 订单id private static String orderid = ""; // 订单编号 private static String orderNo = ""; @Override public void initialize(URL location, ResourceBundle resources) { setMenuValue(1); } /** * 给翻页菜单赋值 * @param page */ private void setMenuValue(int page){ int rows = pageRows(che_recently,num); String text = findOrder.getText(); List<AccountSaleInvoice> AccountSaleInvoiceList = iAccountSaleInvoiceService.listAccountSaleInvoice(text,page, rows); if(AccountSaleInvoiceList != null && AccountSaleInvoiceList.size() >0){ PageInfo<AccountSaleInvoice> pageInfo = new PageInfo<>(AccountSaleInvoiceList); menu_first.setUserData(pageInfo.getFirstPage()); menu_prev.setUserData(pageInfo.getPrePage()); menu_next.setUserData(pageInfo.getNextPage()); menu_last.setUserData(pageInfo.getLastPage()); loadData(AccountSaleInvoiceList); }else { tableView.setItems(null); } } /** * 分页 * @param event */ public void pages(MouseEvent event){ Node node =(Node)event.getSource(); if(node.getUserData() != null){ int page =Integer.parseInt(String.valueOf(node.getUserData())); setMenuValue(page); } } /** * 根据订单号查询 */ @FXML public void likeOrder(){ setMenuValue(1); } /** * 渲染数据 * @param list */ private void generalOrder(List<AccountSaleInvoice> list){ if(list != null){ list.forEach(p->{ p.setCreateDateStr(new SimpleDateFormat("yyyy-MM-dd").format(p.getCreateDate())); if(p.getOrderCancel() != null && p.getOrderCancel()){ p.setOrderCancelStr("已作废"); }else{ p.setOrderCancelStr("正常"); } if(p.getOrderAudit() != null && p.getOrderAudit()){ p.setOrderAuditStr("已审核"); }else{ p.setOrderAuditStr("未审核"); } }); } // 查询客户集合 final ObservableList<AccountSaleInvoice> data = FXCollections.observableArrayList(list); id.setCellValueFactory(new PropertyValueFactory("id")); order_no.setCellValueFactory(new PropertyValueFactory("orderNo")); order_date.setCellValueFactory(new PropertyValueFactory("createDateStr")); customer_no.setCellValueFactory(new PropertyValueFactory("customerNo")); customer_name.setCellValueFactory(new PropertyValueFactory("customerNoStr")); invoice_no.setCellValueFactory(new PropertyValueFactory("invoiceNo")); status.setCellValueFactory(new PropertyValueFactory("orderAuditStr")); cancel.setCellValueFactory(new PropertyValueFactory("orderCancelStr")); tableView.setItems(data); // 选择行 保存数据 tableView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<AccountSaleInvoice>() { @Override public void changed(ObservableValue<? extends AccountSaleInvoice> observableValue, AccountSaleInvoice oldItem, AccountSaleInvoice newItem) { if(newItem.getId() != null && !("".equals(newItem.getId()))){ AccountSaleInvoiceMiniController.orderid = newItem.getId()+""; } if(newItem.getOrderNo() != null && !("".equals(newItem.getOrderNo()))){ AccountSaleInvoiceMiniController.orderNo = newItem.getOrderNo()+""; } } }); tableView.setOnMouseClicked((MouseEvent t) -> { if (t.getClickCount() == 2) { closeSureWin(); } }); } /** * 初始化加载数据 */ private void loadData(List<AccountSaleInvoice> list){ generalOrder(list); } //关闭当前窗体 @FXML public void closeWin(){ Stage stage=(Stage)client_sure.getScene().getWindow(); StageManager.CONTROLLER.remove("saleInvoiceControllerInvoiceMore"); stage.close(); } //确定并关闭当前窗体 @FXML public void closeSureWin(){ // 销项发票 AccountSaleInvoiceController controller = (AccountSaleInvoiceController) StageManager.CONTROLLER.get("saleInvoiceControllerInvoiceMore"); // 导入选中的产品--销货单 if(controller != null && orderid != null && !"".equals(orderid)){ AccountSaleInvoice order = iAccountSaleInvoiceService.selectByKey(Long.valueOf(orderid)); if(order != null){ controller.setBasicValue(order); List<AccountSaleInvoiceInfo> productList = iAccountSaleInvoiceInfoService.listAccountSaleInvoiceInfo(order.getId().toString()); ObservableList<AccountSaleInvoiceInfoProperty> importPurchaseData = FXCollections.observableArrayList(); int rows = 1; for (AccountSaleInvoiceInfo k : productList) { importPurchaseData.add(new AccountSaleInvoiceInfoProperty(k.getId(),k.getOrderSoruce(), k.getOrderNo(), (rows++)+"", k.getCustomerNo(), k.getCustomerStr(), k.getProductNo(), k.getProductName(), k.getInvoceName(),k.getUnit(),k.getNum(),k.getPrice(),k.getMoney(),k.getRate(),k.getRateMoney(),k.getTax(),k.getRateNot(),k.getRemark())); } if(importPurchaseData != null){ controller.generalProductTab(importPurchaseData); } controller.setControllerUse(); } } closeWin(); } }
package libraryproject.repositories; import libraryproject.domain.book.Book; import libraryproject.domain.book.BorrowedBook; import libraryproject.domain.book.EBook; import libraryproject.domain.book.PaperBook; import libraryproject.domain.user.UserProfile; import java.util.HashSet; import java.util.Set; public class BookRepository { private static Set<Book> books; public BookRepository() { this.books = new HashSet<>(); } public static void addBook(Book book) { if (book == null) { throw new IllegalArgumentException("Book can not be null!"); } if (books.contains(book)) { addExistingBook(book); } else { books.add(book); if (book instanceof PaperBook) { QueueRepository.addQueue((PaperBook)book); } } } public static void addExistingBook(Book book) { if (book == null) { throw new IllegalArgumentException("Book can not be null!"); } if (book instanceof PaperBook) { for (Book booksIterator : books) { if (booksIterator == book) { ((PaperBook) booksIterator).addBook(); } } } else if (book instanceof EBook) { System.out.println("This EBook is already available!"); } } public static void removeBook(Book book) { if (book == null) { throw new IllegalArgumentException("Book can not be null!"); } if (books.contains(book)) { books.remove(book); } else { throw new IllegalArgumentException("Book is not valid!"); } } public static Book getBook(Book book) { if (book == null) { throw new IllegalArgumentException("Book can not be null!"); } for(Book iterator : books) { if (iterator.equals(book)) { return iterator; } } return null; } public static Set<Book> getAllBooks() { return new HashSet<>(books); } public static Set<Book> getCurrentlyBorrowedBooks() { Set<Book> allBorrowedBooks = new HashSet<>(); for(UserProfile userProfiles : UserRepository.getAllUsers()) { for(BorrowedBook booksBorrowed : userProfiles.getBorrowedBooks()) { allBorrowedBooks.add(booksBorrowed.getBook()); } } return allBorrowedBooks; } }
/** * Created by friday on 16/9/2. */ import sun.security.provider.SHA; import java.util.Hashtable; public class ShapeCache { private static Hashtable<String,Shape> shapeTable = new Hashtable<String,Shape>(); public static Shape getShape(String shapeId) { Shape cloneShape = shapeTable.get(shapeId); return (Shape)cloneShape.clone(); } public static void loadCache() { Circle circle = new Circle(); circle.setId("1");; shapeTable.put(circle.getId(),circle); Rectangle rect = new Rectangle(); rect.setId("2"); shapeTable.put(rect.getId(),rect); Line line = new Line(); line.setId("3"); shapeTable.put(line.getId(),line); } }
package com.arthur.leetcode; /** * @program: leetcode * @description: 将一维数组转变成二维数组 * @title: No2022 * @Author hengmingji * @Date: 2022/1/1 18:28 * @Version 1.0 */ public class No2022 { public int[][] construct2DArray(int[] original, int m, int n) { if(original.length != m * n) { return new int[][]{}; } int[][] num = new int[m][n]; int k = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { num[i][j] = original[k++]; } } return num; } }
/* * Copyright 2002-2018 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.servlet.tags.form; import jakarta.servlet.jsp.JspException; import org.springframework.lang.Nullable; /** * Abstract base class to provide common methods for * implementing databinding-aware JSP tags for rendering an HTML '{@code input}' * element with a '{@code type}' of '{@code checkbox}' or '{@code radio}'. * * @author Thomas Risberg * @author Juergen Hoeller * @author Rossen Stoyanchev * @since 2.5 */ @SuppressWarnings("serial") public abstract class AbstractCheckedElementTag extends AbstractHtmlInputElementTag { /** * Render the '{@code input(checkbox)}' with the supplied value, marking the * '{@code input}' element as 'checked' if the supplied value matches the * bound value. */ protected void renderFromValue(@Nullable Object value, TagWriter tagWriter) throws JspException { renderFromValue(value, value, tagWriter); } /** * Render the '{@code input(checkbox)}' with the supplied value, marking the * '{@code input}' element as 'checked' if the supplied value matches the * bound value. */ protected void renderFromValue(@Nullable Object item, @Nullable Object value, TagWriter tagWriter) throws JspException { String displayValue = convertToDisplayString(value); tagWriter.writeAttribute("value", processFieldValue(getName(), displayValue, getInputType())); if (isOptionSelected(value) || (value != item && isOptionSelected(item))) { tagWriter.writeAttribute("checked", "checked"); } } /** * Determines whether the supplied value matched the selected value * through delegating to {@link SelectedValueComparator#isSelected}. */ private boolean isOptionSelected(@Nullable Object value) throws JspException { return SelectedValueComparator.isSelected(getBindStatus(), value); } /** * Render the '{@code input(checkbox)}' with the supplied value, marking * the '{@code input}' element as 'checked' if the supplied Boolean is * {@code true}. */ protected void renderFromBoolean(Boolean boundValue, TagWriter tagWriter) throws JspException { tagWriter.writeAttribute("value", processFieldValue(getName(), "true", getInputType())); if (boundValue) { tagWriter.writeAttribute("checked", "checked"); } } /** * Return a unique ID for the bound name within the current PageContext. */ @Override @Nullable protected String autogenerateId() throws JspException { String id = super.autogenerateId(); return (id != null ? TagIdGenerator.nextId(id, this.pageContext) : null); } /** * Writes the '{@code input}' element to the supplied * {@link TagWriter}, * marking it as 'checked' if appropriate. */ @Override protected abstract int writeTagContent(TagWriter tagWriter) throws JspException; /** * Flags "type" as an illegal dynamic attribute. */ @Override protected boolean isValidDynamicAttribute(String localName, Object value) { return !"type".equals(localName); } /** * Return the type of the HTML input element to generate: * "checkbox" or "radio". */ protected abstract String getInputType(); }
package learn.sprsec.ssia0502context.controllers; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Async; import org.springframework.security.concurrent.DelegatingSecurityContextCallable; import org.springframework.security.concurrent.DelegatingSecurityContextExecutorService; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @Slf4j @RestController public class HelloController { @GetMapping("/hello") public String hello(Authentication authentication) { // SecurityContext context = SecurityContextHolder.getContext(); // Authentication authentication = context.getAuthentication(); String username = authentication.getName(); log.trace("Hello, {}!", username); return "Hello, " + username + "!"; } @GetMapping("/bye") @Async public void goodbye() { SecurityContext context = SecurityContextHolder.getContext(); String username = context.getAuthentication().getName(); log.trace("Goodbye, {}!", username); } @GetMapping("/ciao") public String ciao() throws ExecutionException, InterruptedException { Callable<String> task = () -> { SecurityContext context = SecurityContextHolder.getContext(); String username = context.getAuthentication().getName(); log.trace("Ciao, {}!", username); return username; }; ExecutorService executor = Executors.newSingleThreadExecutor(); try { var contextTask = new DelegatingSecurityContextCallable<>(task); return "Ciao, " + executor.submit(contextTask).get() + "!"; } finally { executor.shutdown(); } } @GetMapping("/hola") public String hola() throws ExecutionException, InterruptedException { Callable<String> task = () -> { SecurityContext context = SecurityContextHolder.getContext(); String username = context.getAuthentication().getName(); log.trace("Hola, {}!", username); return username; }; ExecutorService executor = Executors.newSingleThreadExecutor(); executor = new DelegatingSecurityContextExecutorService(executor); try { return "Hola, " + executor.submit(task).get() + "!"; } finally { executor.shutdown(); } } }
package com.git.cloud.common.interceptor; import java.util.ArrayList; import java.util.List; import org.jdom.Element; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.git.cloud.common.support.XmlParser; public class SysOperLogResolve { private static Logger logger = LoggerFactory.getLogger(SysOperLogResolve.class); @SuppressWarnings("unchecked") public static void initSysOperLogMap() { XmlParser xml = null; try { String url= SysOperLogResolve.class.getResource("/").getPath()+"/config/sysOperLogCfg.xml"; logger.info("sysOperLogCfg.xml 加载址地:"+url); xml = new XmlParser(url); logger.info("sysOperLogCfg.xml 加载成功"); } catch (Exception e) { logger.error("sysOperLogCfg.xml加载异常",e); } if(xml != null) { // 首先清除所有模块配置信息 SysOperLogMap.getSysOperLogMap().clearModuleMap(); try { List<Element> elementList = xml.getElement("module"); Element element; ModuleModel module; List<Element> subElementList; Element subElement; List<OperateModel> operateList; OperateModel operate; String clazz; int len = elementList == null ? 0 : elementList.size(); for(int i=0 ; i<len ; i++) { element = elementList.get(i); module = new ModuleModel(); clazz = element.getAttributeValue("class"); if(clazz == null) { continue; } // 封装模块对象 module.setClazz(clazz); module.setModuleCode(getCheckStr(element.getAttributeValue("moduleCode"))); module.setModuleName(getCheckStr(element.getAttributeValue("moduleName"))); // 封装模块包含的操作对象 operateList = new ArrayList<OperateModel> (); subElementList = element.getChildren("operate"); int subLen = subElementList == null ? 0 : subElementList.size(); for(int j=0 ; j<subLen ; j++) { subElement = subElementList.get(j); operate = new OperateModel(); operate.setOperateType(getCheckStr(subElement.getAttributeValue("operateType"))); operate.setOperateName(getCheckStr(subElement.getAttributeValue("operateName"))); operate.setStartsWith(getCheckStr(subElement.getAttributeValue("startsWith"))); operate.setInterceptMethod(getCheckStr(subElement.getAttributeValue("interceptMethod"))); operate.setLogMethod(getCheckStr(subElement.getAttributeValue("logMethod"))); operate.setParamOrder(getCheckStr(subElement.getAttributeValue("paramOrder"))); operate.setPkId(getCheckStr(subElement.getAttributeValue("pkId"))); operate.setGetBeanMethod(getCheckStr(subElement.getAttributeValue("getBeanMethod"))); operate.setBusinessName(getCheckStr(subElement.getAttributeValue("businessName"))); operateList.add(operate); } module.setOperateList(operateList); // 添加到内存中 SysOperLogMap.getSysOperLogMap().put(clazz, module); } } catch (Exception e) { logger.error("sysOperLogCfg.xml读取异常",e); } } } private static String getCheckStr(String str) { if(str == null) { str = ""; } return str; } public static void main(String[] args) { SysOperLogResolve.initSysOperLogMap(); } }
package com.mahang.weather.model.entity; import com.litesuits.orm.db.annotation.Table; import android.os.Parcel; import android.os.Parcelable; @Table("AirInfo") public class AirInfo extends BaseInfo implements Parcelable { private String quality; private String aqi; private String pm25; private String pm10; private String so2; private String no2; private String co; private String o3; public AirInfo() { // TODO Auto-generated constructor stub } public AirInfo(String aqi, String quality) { this.setAqi(aqi); this.setQuality(quality); } protected AirInfo(Parcel in) { quality = in.readString(); aqi = in.readString(); pm25 = in.readString(); pm10 = in.readString(); so2 = in.readString(); no2 = in.readString(); co = in.readString(); o3 = in.readString(); } public static final Creator<AirInfo> CREATOR = new Creator<AirInfo>() { @Override public AirInfo createFromParcel(Parcel in) { return new AirInfo(in); } @Override public AirInfo[] newArray(int size) { return new AirInfo[size]; } }; public void setBasiceInfo(String aqi, String quality) { this.setAqi(aqi); this.setQuality(quality); } @Override public int describeContents() { // TODO Auto-generated method stub return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(quality); dest.writeString(aqi); dest.writeString(pm25); dest.writeString(pm10); dest.writeString(so2); dest.writeString(no2); dest.writeString(co); dest.writeString(o3); } public String getQuality() { return quality; } public void setQuality(String quality) { this.quality = quality; } public String getAqi() { return aqi; } public void setAqi(String aqi) { this.aqi = aqi; } public String getPm25() { return pm25; } public void setPm25(String pm25) { this.pm25 = pm25; } public String getPm10() { return pm10; } public void setPm10(String pm10) { this.pm10 = pm10; } public String getSo2() { return so2; } public void setSo2(String so2) { this.so2 = so2; } public String getNo2() { return no2; } public void setNo2(String no2) { this.no2 = no2; } public String getCo() { return co; } public void setCo(String co) { this.co = co; } public String getO3() { return o3; } public void setO3(String o3) { this.o3 = o3; } }
package com.meehoo.biz.core.basic.dao.security; import com.meehoo.biz.core.basic.domain.security.UserLoginRecord; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; /** * Created by qx on 2019/4/1. */ public interface IUserLoginRecordDao extends JpaRepository<UserLoginRecord, String> { @Query("FROM UserLoginRecord WHERE userId = ?1") UserLoginRecord queryByUserId(String userId); @Modifying @Query("update UserLoginRecord set status = ?2 where userId = ?1") void updateStatus(String userId, Integer status); }
package machine_learning; public interface LinearCalculator { public double calc(double[] data, double[] theta); }
package br.com.AMGiv.bo; import java.sql.Connection; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import br.com.AMGiv.beans.Hospedagem; import br.com.AMGiv.dao.HospedagemDAO; import br.com.AMGiv.excecoes.Excecoes; /** * Class HospedagemBO. */ public abstract class HospedagemBO { /** dao. */ static HospedagemDAO dao = new HospedagemDAO(); /** * Cadastrar hospedagem. * * @author Givs * @version 1.0 * @param h de Hospedagem da classe Hospedagem.java * @param conn de Connection (parametro de conexão com o banco de dados) * @throws Sql Exception * @since 1.0 * @throws Exception */ public static void cadastrarHospedagem(Hospedagem h, Connection conn) throws Exception{ if(h.getReservaQuarto().getStatus() != 1){ throw new Excecoes("Reserva Cancelada"); } Calendar calendar = Calendar.getInstance(); Calendar cal= Calendar.getInstance(); DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); System.out.println("Data inicio: "+h.getReservaQuarto().getDataInicio() ); String data = h.getReservaQuarto().getDataInicio(); cal.setTime(dateFormat.parse(data)); if(cal.getTime().before(calendar.getTime())){ h.getReservaQuarto().setStatus(3); ReservaQuartoBO.AlterarStatusReserva(h.getReservaQuarto().getStatus(),h.getReservaQuarto().getCodReserva(), conn); throw new Excecoes("Data de Check-In excedida!"); } new HospedagemDAO().registrarHospedagem(h, conn); } /** * Consultar hospedagem. * @author Rafael Paulo da Silva Queiros * @version 1.0 * @since 1.0 * @param codHospedagem de cod hospedagem da classe Hospedagem * @param conn de Connection (parametro de conexão com o banco de dados) * @return objeto do tipo hospedagem * @throws Exception * @throws sql Exception */ public static Hospedagem consultarHospedagem(int codHospedagem,Connection conn) throws Exception{ return new HospedagemDAO().getPesquisarHospedagem(codHospedagem, conn); } }
package com.test.base; import static org.junit.Assert.assertArrayEquals; import java.util.Arrays; import com.test.SolutionA; import junit.framework.TestCase; public class Example extends TestCase { private SolutionA solution; @Override protected void setUp() throws Exception { super.setUp(); } public void testSolutionA() { solution = new SolutionA(); assertSolution(new int[] {0}, new int[] {0}, new int[] {0}); assertSolution(new int[] {1, 1, 1, 1, 1}, new int[] {1, 0, 1}, new int[] {1, 0, 0, 0, 0}); assertSolution(new int[] {1}, new int[] {1, 0, 1}, new int[] {1, 1, 0, 1, 0}); } private void assertSolution(int[] arr1, int[] arr2, int[] expect) { int[] actual = solution.addNegabinary(arr1, arr2); System.out.println("actual = " + Arrays.toString(actual)); assertArrayEquals(expect, actual); } @Override protected void tearDown() throws Exception { solution = null; super.tearDown(); } }
import java.awt.Graphics; import java.awt.Image; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.imageio.ImageIO; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import javax.swing.Timer; /** * Level is the class that holds all level detail data * and game objects within level */ public class Level { private LevelManager levelManager; //reference to level manager which controls the level private UserPlane userPlane; //user plane object private List<TargetPlane> targetPlanes; //list of target planes in game private List<Target> targets; //list of targets in game private List<Target> createdTargets; //list of targets read from file private List<Obstacle> obstacles; //list of obstacles in game private List<Obstacle> createdObstacles; //list of obstacles read from file private List<TargetPlane> createdTargetPlanes; //list of target planes read from file private List<Weapon> userWeapons; //list of weapons sent by user plane private List<BonusPackage> bonusPackages; //list of bonus packages in game private List<BonusPackage> createdBonusPackages; //list of bonus packages read from file private int points; //total points user has collected in level private int levelTimePeriod; //total time allocated for user plane private int levelPointThreshold; //point threshold for the level to be vieweved as successful private int coinCoefficient; //coin coefficient which represents points per coin private int levelId; //id of the level private List<Integer> weapons; //list of weapons user has private Image backGroundImage; //background image of the level //Constructor of level - it takes reference to its creator level manager and level id public Level(LevelManager levelManager, int levelId){ targetPlanes = new ArrayList<TargetPlane>(); targets = new ArrayList<Target>(); obstacles = new ArrayList<Obstacle>(); createdTargetPlanes = new ArrayList<TargetPlane>(); createdTargets = new ArrayList<Target>(); createdObstacles = new ArrayList<Obstacle>(); userWeapons = new ArrayList<Weapon>(); bonusPackages = new ArrayList<BonusPackage>(); createdBonusPackages = new ArrayList<BonusPackage>(); this.levelId = levelId; this.levelManager = levelManager; levelManager.setCurrentLevelId(levelId); createUserPlane(); initializeWeapons(); } private void createUserPlane() { if( levelManager.getGameManager().getCollectionManager().getPilotSelection() == 0){ if( levelManager.getGameManager().getCollectionManager().getUserPlaneSelection() == 0){ this.userPlane = new UserPlane(ImageConstants.user11, UserPlaneEnum.ALDERAAN_CRUISER.health(), 100, UserPlaneEnum.ALDERAAN_CRUISER.shootDamage(), UserPlaneEnum.ALDERAAN_CRUISER.shootType(), UserPlaneEnum.ALDERAAN_CRUISER.speed()); } else if( levelManager.getGameManager().getCollectionManager().getUserPlaneSelection() == 1){ this.userPlane = new UserPlane(ImageConstants.user12, UserPlaneEnum.TOMCAT.health(), 100, UserPlaneEnum.TOMCAT.shootDamage(), UserPlaneEnum.TOMCAT.shootType(), UserPlaneEnum.TOMCAT.speed()); } else if( levelManager.getGameManager().getCollectionManager().getUserPlaneSelection() == 2){ this.userPlane = new UserPlane(ImageConstants.user13, UserPlaneEnum.F22_RAPTOR.health(), 100, UserPlaneEnum.F22_RAPTOR.shootDamage(), UserPlaneEnum.F22_RAPTOR.shootType(), UserPlaneEnum.F22_RAPTOR.speed()); } else if( levelManager.getGameManager().getCollectionManager().getUserPlaneSelection() == 3){ this.userPlane = new UserPlane(ImageConstants.user14, UserPlaneEnum.SAAB_GRIPEN.health(), 100, UserPlaneEnum.SAAB_GRIPEN.shootDamage(), UserPlaneEnum.SAAB_GRIPEN.shootType(), UserPlaneEnum.SAAB_GRIPEN.speed()); } else if( levelManager.getGameManager().getCollectionManager().getUserPlaneSelection() == 4){ this.userPlane = new UserPlane(ImageConstants.user15, UserPlaneEnum.WUNDERWAFFE.health(), 100, UserPlaneEnum.WUNDERWAFFE.shootDamage(), UserPlaneEnum.WUNDERWAFFE.shootType(), UserPlaneEnum.WUNDERWAFFE.speed()); } this.userPlane.setPilot(new Pilot( PilotEnum.NICK.speed())); } else if( levelManager.getGameManager().getCollectionManager().getPilotSelection() == 1){ if( levelManager.getGameManager().getCollectionManager().getUserPlaneSelection() == 0){ this.userPlane = new UserPlane(ImageConstants.user21, UserPlaneEnum.ALDERAAN_CRUISER.health(), 100, UserPlaneEnum.ALDERAAN_CRUISER.shootDamage(), UserPlaneEnum.ALDERAAN_CRUISER.shootType(), UserPlaneEnum.ALDERAAN_CRUISER.speed()); } else if( levelManager.getGameManager().getCollectionManager().getUserPlaneSelection() == 1){ this.userPlane = new UserPlane(ImageConstants.user22, UserPlaneEnum.TOMCAT.health(), 100, UserPlaneEnum.TOMCAT.shootDamage(), UserPlaneEnum.TOMCAT.shootType(), UserPlaneEnum.TOMCAT.speed()); } else if( levelManager.getGameManager().getCollectionManager().getUserPlaneSelection() == 2){ this.userPlane = new UserPlane(ImageConstants.user23, UserPlaneEnum.F22_RAPTOR.health(), 100, UserPlaneEnum.F22_RAPTOR.shootDamage(), UserPlaneEnum.F22_RAPTOR.shootType(), UserPlaneEnum.F22_RAPTOR.speed()); } else if( levelManager.getGameManager().getCollectionManager().getUserPlaneSelection() == 3){ this.userPlane = new UserPlane(ImageConstants.user24, UserPlaneEnum.SAAB_GRIPEN.health(), 100, UserPlaneEnum.SAAB_GRIPEN.shootDamage(), UserPlaneEnum.SAAB_GRIPEN.shootType(), UserPlaneEnum.SAAB_GRIPEN.speed()); } else if( levelManager.getGameManager().getCollectionManager().getUserPlaneSelection() == 4){ this.userPlane = new UserPlane(ImageConstants.user25, UserPlaneEnum.WUNDERWAFFE.health(), 100, UserPlaneEnum.WUNDERWAFFE.shootDamage(), UserPlaneEnum.WUNDERWAFFE.shootType(), UserPlaneEnum.WUNDERWAFFE.speed()); } this.userPlane.setPilot(new Pilot( PilotEnum.PENNY.speed())); } else if( levelManager.getGameManager().getCollectionManager().getPilotSelection() == 2){ if( levelManager.getGameManager().getCollectionManager().getUserPlaneSelection() == 0){ this.userPlane = new UserPlane(ImageConstants.user31, UserPlaneEnum.ALDERAAN_CRUISER.health(), 100, UserPlaneEnum.ALDERAAN_CRUISER.shootDamage(), UserPlaneEnum.ALDERAAN_CRUISER.shootType(), UserPlaneEnum.ALDERAAN_CRUISER.speed()); } else if( levelManager.getGameManager().getCollectionManager().getUserPlaneSelection() == 1){ this.userPlane = new UserPlane(ImageConstants.user32, UserPlaneEnum.TOMCAT.health(), 100, UserPlaneEnum.TOMCAT.shootDamage(), UserPlaneEnum.TOMCAT.shootType(), UserPlaneEnum.TOMCAT.speed()); } else if( levelManager.getGameManager().getCollectionManager().getUserPlaneSelection() == 2){ this.userPlane = new UserPlane(ImageConstants.user33, UserPlaneEnum.F22_RAPTOR.health(), 100, UserPlaneEnum.F22_RAPTOR.shootDamage(), UserPlaneEnum.F22_RAPTOR.shootType(), UserPlaneEnum.F22_RAPTOR.speed()); } else if( levelManager.getGameManager().getCollectionManager().getUserPlaneSelection() == 3){ this.userPlane = new UserPlane(ImageConstants.user34, UserPlaneEnum.SAAB_GRIPEN.health(), 100, UserPlaneEnum.SAAB_GRIPEN.shootDamage(), UserPlaneEnum.SAAB_GRIPEN.shootType(), UserPlaneEnum.SAAB_GRIPEN.speed()); } else if( levelManager.getGameManager().getCollectionManager().getUserPlaneSelection() == 4){ this.userPlane = new UserPlane(ImageConstants.user35, UserPlaneEnum.WUNDERWAFFE.health(), 100, UserPlaneEnum.WUNDERWAFFE.shootDamage(), UserPlaneEnum.WUNDERWAFFE.shootType(), UserPlaneEnum.WUNDERWAFFE.speed()); } this.userPlane.setPilot(new Pilot( PilotEnum.MIKE.speed())); } else if( levelManager.getGameManager().getCollectionManager().getPilotSelection() == 3){ if( levelManager.getGameManager().getCollectionManager().getUserPlaneSelection() == 0){ this.userPlane = new UserPlane(ImageConstants.user41, UserPlaneEnum.ALDERAAN_CRUISER.health(), 100, UserPlaneEnum.ALDERAAN_CRUISER.shootDamage(), UserPlaneEnum.ALDERAAN_CRUISER.shootType(), UserPlaneEnum.ALDERAAN_CRUISER.speed()); } else if( levelManager.getGameManager().getCollectionManager().getUserPlaneSelection() == 1){ this.userPlane = new UserPlane(ImageConstants.user42, UserPlaneEnum.TOMCAT.health(), 100, UserPlaneEnum.TOMCAT.shootDamage(), UserPlaneEnum.TOMCAT.shootType(), UserPlaneEnum.TOMCAT.speed()); } else if( levelManager.getGameManager().getCollectionManager().getUserPlaneSelection() == 2){ this.userPlane = new UserPlane(ImageConstants.user43, UserPlaneEnum.F22_RAPTOR.health(), 100, UserPlaneEnum.F22_RAPTOR.shootDamage(), UserPlaneEnum.F22_RAPTOR.shootType(), UserPlaneEnum.F22_RAPTOR.speed()); } else if( levelManager.getGameManager().getCollectionManager().getUserPlaneSelection() == 3){ this.userPlane = new UserPlane(ImageConstants.user44, UserPlaneEnum.SAAB_GRIPEN.health(), 100, UserPlaneEnum.SAAB_GRIPEN.shootDamage(), UserPlaneEnum.SAAB_GRIPEN.shootType(), UserPlaneEnum.SAAB_GRIPEN.speed()); } else if( levelManager.getGameManager().getCollectionManager().getUserPlaneSelection() == 4){ this.userPlane = new UserPlane(ImageConstants.user45, UserPlaneEnum.WUNDERWAFFE.health(), 100, UserPlaneEnum.WUNDERWAFFE.shootDamage(), UserPlaneEnum.WUNDERWAFFE.shootType(), UserPlaneEnum.WUNDERWAFFE.speed()); } this.userPlane.setPilot(new Pilot( PilotEnum.EVA.speed())); } else if( levelManager.getGameManager().getCollectionManager().getPilotSelection() == 4){ if( levelManager.getGameManager().getCollectionManager().getUserPlaneSelection() == 0){ this.userPlane = new UserPlane(ImageConstants.user51, UserPlaneEnum.ALDERAAN_CRUISER.health(), 100, UserPlaneEnum.ALDERAAN_CRUISER.shootDamage(), UserPlaneEnum.ALDERAAN_CRUISER.shootType(), UserPlaneEnum.ALDERAAN_CRUISER.speed()); } else if( levelManager.getGameManager().getCollectionManager().getUserPlaneSelection() == 1){ this.userPlane = new UserPlane(ImageConstants.user52, UserPlaneEnum.TOMCAT.health(), 100, UserPlaneEnum.TOMCAT.shootDamage(), UserPlaneEnum.TOMCAT.shootType(), UserPlaneEnum.TOMCAT.speed()); } else if( levelManager.getGameManager().getCollectionManager().getUserPlaneSelection() == 2){ this.userPlane = new UserPlane(ImageConstants.user53, UserPlaneEnum.F22_RAPTOR.health(), 100, UserPlaneEnum.F22_RAPTOR.shootDamage(), UserPlaneEnum.F22_RAPTOR.shootType(), UserPlaneEnum.F22_RAPTOR.speed()); } else if( levelManager.getGameManager().getCollectionManager().getUserPlaneSelection() == 3){ this.userPlane = new UserPlane(ImageConstants.user54, UserPlaneEnum.SAAB_GRIPEN.health(), 100, UserPlaneEnum.SAAB_GRIPEN.shootDamage(), UserPlaneEnum.SAAB_GRIPEN.shootType(), UserPlaneEnum.SAAB_GRIPEN.speed()); } else if( levelManager.getGameManager().getCollectionManager().getUserPlaneSelection() == 4){ this.userPlane = new UserPlane(ImageConstants.user55, UserPlaneEnum.WUNDERWAFFE.health(), 100, UserPlaneEnum.WUNDERWAFFE.shootDamage(), UserPlaneEnum.WUNDERWAFFE.shootType(), UserPlaneEnum.WUNDERWAFFE.speed()); } this.userPlane.setPilot(new Pilot( PilotEnum.NEO.speed())); } } //private call-initializes weapons from collection private void initializeWeapons() { weapons = new ArrayList<Integer>(); for( int i = 0; i < levelManager.getPurchasedWeapons().size(); i++ ){ weapons.add(i, levelManager.getPurchasedWeapons().get(i)); } } //Returns list of user weapons public List<Weapon> getUserWeapons() { return userWeapons; } //Returns level point threshold public int getLevelPointThreshold() { return levelPointThreshold; } //Changes level point threshold public void setLevelPointThreshold(int levelPointThreshold) { this.levelPointThreshold = levelPointThreshold; } //Returns time period allocated for level public int getLevelTimePeriod() { return levelTimePeriod; } //Changes time period allocated for level public void setLevelTimePeriod(int levelTimePeriod) { this.levelTimePeriod = levelTimePeriod; } //Return points public int getPoints() { return points; } //Updates points by specified amount public void updatePoints( int amount){ points += amount; if( points <= 0) points = 0; } //Returns user plane public UserPlane getUserPlane() { return userPlane; } //Create objects according to time of level and appearance time of objects public void createObjects(int timeInSeconds, int frameWidth) { for( int i = 0; i < createdTargetPlanes.size(); i++ ){ if( createdTargetPlanes.get(i).getAppearTime() == timeInSeconds ){ targetPlanes.add(createdTargetPlanes.get(i)); createdTargetPlanes.remove(i); levelManager.updateTargetPlanes(targetPlanes); } } for( int i = 0; i < createdTargets.size(); i++ ){ if( createdTargets.get(i).getAppearTime() == timeInSeconds ){ targets.add(createdTargets.get(i)); createdTargets.remove(i); levelManager.updateTargets(targets); } } for( int i = 0; i < createdObstacles.size(); i++ ){ if( createdObstacles.get(i).getAppearTime() == timeInSeconds ){ obstacles.add(createdObstacles.get(i)); createdObstacles.remove(i); levelManager.updateObstacles(obstacles); } } for( int i = 0; i < createdBonusPackages.size(); i++ ){ if( createdBonusPackages.get(i).getAppearTime() == timeInSeconds ){ bonusPackages.add(createdBonusPackages.get(i)); createdBonusPackages.remove(i); levelManager.updateBonusPackages(bonusPackages); } } } //Returns end of level status text public String levelPassedText() { if( userPlane.getHealth() <= 0 ){ return "LEVEL FAILED - HEALTH DEPLETED"; } else{ if( points >= levelPointThreshold ) return "LEVEL PASSED"; else return "LEVEL FAILED - YOU DID NOT COLLECT " + levelPointThreshold + " POINTS"; } } //Returns coin coefficient public int getCoinCoefficient() { return coinCoefficient; } //Changes coin coefficient public void setCoinCoefficient(int coinCoefficient) { this.coinCoefficient = coinCoefficient; } //Returns level id public int getLevelId() { return levelId; } //Given points turns points to coins according to coin coefficient and returns public int turnPointsIntoCoins(int points) { levelManager.addCoins(points / coinCoefficient); return points / coinCoefficient; } //Changes created target planes public void setCreatedTargetPlanes(List<TargetPlane> targetPlanes) { this.createdTargetPlanes = targetPlanes; } //Returns whether level is passed or not public boolean levelPassed() { if( userPlane.getHealth() <= 0 ){ return false; } else{ if( points >= levelPointThreshold ) return true; else return false; } } //Returns list of target planes in level public List<TargetPlane> getTargetPlanes() { return targetPlanes; } //Updates list of target planes in level public void setTargetPlanes(List<TargetPlane> tps) { this.targetPlanes = tps; } //Returns list of weapons in level public List<Integer> getWeapons() { return weapons; } //Updates set of weapons in level public void setWeapons(List<Integer> weapons) { this.weapons = weapons; } //Updates user plane public void updateUserPlane(UserPlane userPlane) { this.userPlane = userPlane; } //Sets created targets public void setCreatedTargets(List<Target> targets) { this.createdTargets = targets; } //Returns list of targets public List<Target> getTargets() { return targets; } //Returns list of obstacles in game public List<Obstacle> getObstacles() { return obstacles; } public void setCreatedObstacles(List<Obstacle> obstacles) { this.createdObstacles = obstacles; } public void setCreatedBonusPackages(List<BonusPackage> bonusPackages) { this.createdBonusPackages = bonusPackages; } public List<BonusPackage> getBonusPackages() { return bonusPackages; } }
package realtime.service.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.alibaba.fastjson.JSON; import analysis.util.AnalysisUtil; import berkeley.service.BerkeleyService; import berkeley.service.impl.BerkeleyServiceImpl; import elasticsearch.util.ClientUtil; import quartz.job.BaiduJob; import quartz.job.JuHeJob; import quartz.job.SinaJob; import quartz.util.JobUtil; import realtime.bean.BaiduStock; import realtime.bean.JuHeStock; import realtime.bean.SinaStock; import realtime.jsonstruts.BaiduStruts; import realtime.jsonstruts.JuHeStruts; import realtime.service.RealTimeStockService; import realtime.util.HttpUtil; import realtime.util.ThreadUtil; import realtime.util.thread.impl.BaiduRealDataServiceImpl; import realtime.util.thread.impl.JuHeRealDataServiceImpl; import realtime.util.thread.impl.SinaRealDataServiceImpl; import realtime.vo.BaiduStockVO; import realtime.vo.JuHeStockVO; import util.ConstantUtil; import util.RefUtil; public class RealTimeStockServiceImpl implements RealTimeStockService { private static RealTimeStockServiceImpl INSTANCE; public static synchronized RealTimeStockServiceImpl getInstance() { if (null == INSTANCE) { INSTANCE = new RealTimeStockServiceImpl(); } return INSTANCE; } private static Map<String, String> compMap; private RealTimeStockServiceImpl() { ClientUtil.getNewClient(); // 获取编码信息 BerkeleyService berkeleyService = BerkeleyServiceImpl.getInstance(); compMap = berkeleyService.queryDatabaseByKey(ConstantUtil.STOCK_DB, ConstantUtil.STOCK_KEY); if (null != compMap && !compMap.isEmpty()) { for (String key : compMap.keySet()) { ThreadUtil.arrayBlockingQueue.add(key); } } } /** * 启动新浪获取实时数据api */ @Override public void startSinaRealTimeStock() { try { // 启动新浪线程 ThreadUtil.startThread(new SinaRealDataServiceImpl()); } catch (Exception e) { e.printStackTrace(); } } /** * 启动百度获取实时数据api */ @Override public void startBaiduRealTimeStock() { try { // 启动百度线程 ThreadUtil.startThread(new BaiduRealDataServiceImpl()); } catch (Exception e) { e.printStackTrace(); } } /** * 启动聚合获取实时数据api */ @Override public void startJuHeRealTimeStock() { try { // 启动聚合线程 ThreadUtil.startThread(new JuHeRealDataServiceImpl()); } catch (Exception e) { e.printStackTrace(); } } /** * 一次查询新浪api * * @param type * @param codeList */ @Override public List<SinaStock> querySinaAPIOnce(List<String> codeList) { String[] datas = null; SinaStock sinaStock = null; List<SinaStock> ssList = new ArrayList<>(); String httpUrl = ConstantUtil.SINA_API; StringBuilder sBuilder = new StringBuilder(""); try { // 判断查询代码是否为空 if (null != codeList && !codeList.isEmpty()) { for (String code : codeList) { sBuilder.append(code).append(","); } // 不为空则将其变成字符串,并用逗号隔开 String codeChain = sBuilder.substring(0, sBuilder.length() - 1); // 替换模板中codes变量,开始查询 httpUrl = httpUrl.replaceAll("\\{codes\\}", codeChain); String dataStr = HttpUtil.stockRealTimeRequest(httpUrl, null, "GBK"); // 查询后通过正则表达式进行数据过滤 Pattern pattern = Pattern.compile("\"[^\"]*\""); Matcher matcher = pattern.matcher(dataStr); while (matcher.find()) { // 将返回数据切割并转化成实体 datas = matcher.group().replaceAll("\"", "").split(","); sinaStock = RefUtil.refArray2SinaStock(datas); // 分析工具 AnalysisUtil.anyDimensionsAnalysis(sinaStock); ssList.add(sinaStock); } } } catch (Exception e) { e.printStackTrace(); } return ssList; } /** * 一次查询百度api * * @param codeList * @return */ @Override public List<BaiduStock> queryBaiduAPIOnce(List<String> codeList) { String httpUrl = ConstantUtil.BAIDU_API; StringBuilder sBuilder = new StringBuilder(""); Map<String, String> paramMap = new HashMap<>(); paramMap.put("apikey", ConstantUtil.BAIDU_API_KEY); BaiduStock baiduStock = null; BaiduStockVO baiduStockVO; List<BaiduStock> bsList = new ArrayList<>(); if (null != codeList && !codeList.isEmpty()) { for (String code : codeList) { sBuilder.append(code).append(","); } // 不为空则将其变成字符串,并用逗号隔开 String codeChain = sBuilder.substring(0, sBuilder.length() - 1); // 替换模板中codes变量,开始查询 httpUrl = httpUrl.replaceAll("\\{codes\\}", codeChain); String jsonStr = HttpUtil.stockRealTimeRequest(httpUrl, paramMap, "UTF-8"); // 获取到Json数据并解析 BaiduStruts baiduStruts = JSON.parseObject(jsonStr, BaiduStruts.class); // 按照baidu提供的api进行数据解析工作 Map<String, List<String>> reMap = baiduStruts.getRetData(); if (null != reMap && !reMap.isEmpty()) { List<String> inList = reMap.get("stockinfo"); if (null != inList && !inList.isEmpty()) { for (String json : inList) { baiduStockVO = (BaiduStockVO) JSON.parse(json); baiduStock = (BaiduStock) RefUtil.stockVO2Entity( baiduStockVO, new BaiduStock(), RefUtil.baiduFieldMapping); // 分析工具 AnalysisUtil.anyDimensionsAnalysis(baiduStock); bsList.add(baiduStock); } } } } // 最后得到实体 return bsList; } /** * 一次查询聚合api * * @param code */ @Override public JuHeStock queryJuHeAPIOnce(String code) { JuHeStock jhStock = null; JuHeStockVO juHeStockVO; // 整理url发送信息 String httpUrl = ConstantUtil.JUHE_API; httpUrl = httpUrl.replaceAll("\\{code\\}", code); String jsonStr = HttpUtil.stockRealTimeRequest(httpUrl, null, "UTF-8"); // 获取到Json数据并解析 JuHeStruts juHeStruts = JSON.parseObject(jsonStr, JuHeStruts.class); List<Map<String, String>> reList = juHeStruts.getResult(); if (null != reList && !reList.isEmpty()) { Map<String, String> reMap = reList.get(0); String dataStr = reMap.get("data"); juHeStockVO = JSON.parseObject(dataStr, JuHeStockVO.class); jhStock = (JuHeStock) RefUtil.stockVO2Entity(juHeStockVO, new JuHeStock(), RefUtil.juHeFieldMapping); // 分析工具 AnalysisUtil.anyDimensionsAnalysis(jhStock); } // 最后得到实体 return jhStock; } /** * 启动 sina job下载 */ @Override public void startSinaJobThread() { Map<String, String> paramMap = new HashMap<>(); paramMap.put("type", "cron"); paramMap.put("cron", "*/8 30 9-11 * * ? | */8 00 13-15 * * ?"); try { JobUtil.initJob(SinaJob.class, "Sina", paramMap); } catch (Exception e) { e.printStackTrace(); } } /** * 启动 baidu job下载 */ @Override public void startBaiduJobThread() { Map<String, String> paramMap = new HashMap<>(); paramMap.put("type", "cron"); paramMap.put("cron", "*/5 30 9-11 * * ? | */5 00 13-15 * * ?"); try { JobUtil.initJob(BaiduJob.class, "Baidu", paramMap); } catch (Exception e) { e.printStackTrace(); } } /** * 启动 juhe job下载 */ @Override public void startJuHeJobThread() { Map<String, String> paramMap = new HashMap<>(); paramMap.put("type", "cron"); paramMap.put("cron", "*/3 30 9-11 * * ? | */3 00 13-15 * * ?"); try { JobUtil.initJob(JuHeJob.class, "JuHe", paramMap); } catch (Exception e) { e.printStackTrace(); } } }
package ua.com.owu.relations.dao; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import ua.com.owu.relations.models.User; @EnableJpaRepositories public interface UserDAO extends JpaRepository<User,Integer> { }
/* $Id$ */ package djudge.acmcontester.server.interfaces; import djudge.acmcontester.structures.MonitorData; public interface TeamMonitorNativeInterface { public MonitorData getTeamMonitor(String username, String password); }
import enums.BlackJackMove; import enums.WinState; import java.util.ArrayList; import java.util.List; public class Player { private List<Card> cards; private Boolean hasStuck; private String name; private WinState winState; public Player(String name) { this.name = name; this.hasStuck = false; this.cards = new ArrayList<Card>(); this.winState = null; } public WinState getWinState() { return winState; } public void setWinState(WinState winState) { this.winState = winState; } public String getName() { return name; } public Boolean getHasStuck() { return hasStuck; } public void setHasStuck(Boolean hasStuck) { this.hasStuck = hasStuck; } public List<Card> getCards() { return cards; } public void addCard(Card card){ this.cards.add(card); } public void addCards(List<Card> cards){ for (Card card : cards){ this.addCard(card); } } }
package com.krish.array; public class MissingOneFromMtoN { public static void main(String[] args) { int[] arr = { -2, -1, 0, 1, 2, 3, 4, 6, 7 }; System.out.println(find(arr, 0, arr.length - 1)); } private static int find(int[] arr, int start, int end) { if (arr == null || arr.length == 0 || start == end || arr[end] - arr[start] == end) return Integer.MIN_VALUE; int mid = start + (end - start) / 2; if (arr[mid] + 1 != arr[mid + 1]) return arr[mid] + 1; // 1,2,4,5 if (arr[mid] - 1 != arr[mid - 1]) return arr[mid] -1; // 1,3,4,5 if (arr[mid] > arr[start] + (mid - start)) { return find(arr, start, mid); // 1,3,4,5,6,7 } else if (arr[end] > arr[mid] + (end - mid)) { return find(arr, mid, end); // 1,2,3,4,6,7 } else { return arr[end] - 1; } } }
package modelo.fases; import java.util.HashMap; import modelo.Equipo; import modelo.StatsJuego; import modelo.excepciones.TransformacionInvalida; public class FasePicolo2 extends Fase { public HashMap<String, Integer> obtenerStats() { return StatsJuego.statsEstado2.get("Picolo"); } public Fase transformar(int ki) { throw new TransformacionInvalida(); } public Fase transformarPicolo(int ki,Equipo equipo){ throw new TransformacionInvalida(); } }
package elitesportsoop; public class Main { public static void main(String[] args) { Candidate candidate = new Candidate(null, null, 0, 0, 0); } }
package pl.rafaltruszewski.stringcalculator; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; class NumbersParser { private static final String DEFAULT_DELIMITER = "[," + "\n" + "]"; private static final Pattern NUMBERS_WITH_MULTI_DELIMITER = Pattern.compile("^//(\\[.+\\])\n(.+)$"); private static final Pattern NUMBERS_WITH_SINGLE_DELIMITER = Pattern.compile("^//(.)\n?(.+)$"); private static final Pattern SINGLE_DELIMITERS = Pattern.compile("(\\[.+?\\])"); public NumbersParser() { } public List<Integer> parse(String numbers) { if (hasDelimiters(numbers)) { SplitArguments splitArguments = findDelimiters(numbers); return mapToInt(split(splitArguments)); } else { return mapToInt(Arrays.asList(numbers.split(DEFAULT_DELIMITER))); } } private List<Integer> mapToInt(List<String> numbersAsString) { return numbersAsString.stream() .map(Integer::valueOf) .collect(Collectors.toList()); } private List<String> split(SplitArguments splitArguments){ String delimitersForSplit = splitArguments.delimitersAsRegex(); String numbersWithoutDelimiters = splitArguments.getNumbers(); return Arrays.asList(numbersWithoutDelimiters.split(delimitersForSplit)); } private SplitArguments findDelimiters(String numbersWithDelimiters){ Matcher multiDelimiterMatcher = NUMBERS_WITH_MULTI_DELIMITER.matcher(numbersWithDelimiters); if (multiDelimiterMatcher.find()) { String manyDelimiters = multiDelimiterMatcher.group(1); Matcher singleDelimitersMatcher = SINGLE_DELIMITERS.matcher(manyDelimiters); List<String> delimiters = new LinkedList<>(); while (singleDelimitersMatcher.find()){ String group = singleDelimitersMatcher.group(); delimiters.add(group.substring(1, group.length()-1)); } return new SplitArguments(delimiters, multiDelimiterMatcher.group(2)); } Matcher singleDelimiterMatcher = NUMBERS_WITH_SINGLE_DELIMITER.matcher(numbersWithDelimiters); if (singleDelimiterMatcher.find()) { String delimiter = singleDelimiterMatcher.group(1); String numbersWithoutDelimiter = singleDelimiterMatcher.group(2); return new SplitArguments(Collections.singletonList(delimiter), numbersWithoutDelimiter); } throw new RuntimeException("Numbers " + numbersWithDelimiters + " have invalid delimiter"); } private boolean hasDelimiters(String numbers) { return numbers.startsWith("//"); } private static class SplitArguments { private final List<String> delimiters; private final String numbers; private SplitArguments(List<String> delimiters, String numbers) { this.delimiters = delimiters; this.numbers = numbers; } String getNumbers() { return numbers; } String delimitersAsRegex() { return String.join("|", delimiters); } } }
package cartas; public class AncientBrain extends CartaMonstruo { public AncientBrain() { super(); this.puntosDeAtaque = new Puntos(1000); this.puntosDeDefensa = new Puntos(700); this.nivel = 3; this.nombre = "Ancient Brain"; this.colocarImagenEnCartaDesdeArchivoDeRuta("resources/images/carta_AncientBrain.png"); } }
package com.bruce.singleton.type6_doublecheckvvv; public class SingletonTest06 { public static void main(String[] args) { // todo more logics //todo more logics System.out.println("使用静态内部类完成单例模式"); Singleton s1=Singleton.getInstance(); Singleton s2=Singleton.getInstance(); System.out.println(s1==s2); System.out.println(s1.hashCode()+".."+s2.hashCode()); } } class Singleton { //加关键字 volatile 轻量及synchronized 立即刷新 变值到内存上 private static volatile Singleton instance; private Singleton() { } //写一个静态内部类,该类有一个静态属性Singleton private static class SingletonInstance{ private static final Singleton INSTANTCE_SINGLETON=new Singleton(); } //加入双重检查代码,解决线程案例问题,同时解决懒加载问题 //同时保证〦〧〨效率 public static synchronized Singleton getInstance() { return SingletonInstance.INSTANTCE_SINGLETON; } }
package com.mydiaryapplication.userdiary.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import javax.sql.DataSource; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { private AuthenticationSuccessHandler authenticationSuccessHandler; //A DataSource is a factory for connections to any physical data source. @Autowired private DataSource dataSource; @Autowired public SecurityConfig(AuthenticationSuccessHandler authenticationSuccessHandler) { this.authenticationSuccessHandler = authenticationSuccessHandler; } @Bean @Override public UserDetailsService userDetailsService() { return new CustomUserDetailsService(); } @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } /* Spring's Security DaoAuthenticationProvider is a simple authentication provider that uses a Data Access Object (DAO) to retrieve user information from a relational database. It leverages a UserDetailsService (as a DAO) in order to lookup the username, password and GrantedAuthoritys. */ @Bean public DaoAuthenticationProvider authenticationProvider() { DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); authProvider.setUserDetailsService(userDetailsService()); authProvider.setPasswordEncoder(passwordEncoder()); return authProvider; } //authentication failure handler @Autowired public void configureBothAuthentication(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("Admin@1") .password(passwordEncoder().encode("admin")) .roles("ADMIN"); auth.authenticationProvider(authenticationProvider()); } @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/").permitAll() .antMatchers("/admin/**").hasAnyRole("ADMIN") .antMatchers("/user").authenticated() .antMatchers("/api/**").authenticated() .antMatchers("/diarypage/**").authenticated() .and() .formLogin().loginPage("/login") .successHandler(authenticationSuccessHandler) .permitAll() .and() .logout() .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) .logoutSuccessUrl("/") .deleteCookies("JSESSIONID") .invalidateHttpSession(true); } }
package com.maliang.core.model; import java.util.List; public class ObjectField extends MongodbModel { private String name; private String uniqueMark; private Integer type; private String linkedObject; private String label; private String relationship; private Integer elementType;//鐢ㄤ簬type=array鏃� //private Dict dict;//鐢ㄤ簬type=dict鏃� @Mapped(type=ObjectField.class) private List<ObjectField> fields;//鐢ㄤ簬type=inner /** * 存储类型 * 用于第一层的arry[inner]类型: * 1:独立存储: 可以单独操作一条子记录 * 2:整存整取:整个数组统一操作 * **/ private Integer storeType = 1; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUniqueMark() { return uniqueMark; } public void setUniqueMark(String uniqueMark) { this.uniqueMark = uniqueMark; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public String getLinkedObject() { return linkedObject; } public void setLinkedObject(String linkedObject) { this.linkedObject = linkedObject; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public String getRelationship() { return relationship; } public void setRelationship(String relationship) { this.relationship = relationship; } public Integer getElementType() { return elementType; } public void setElementType(Integer elementType) { this.elementType = elementType; } public List<ObjectField> getFields() { return fields; } public void setFields(List<ObjectField> fields) { this.fields = fields; } public boolean isInnerCollection() { return FieldType.INNER_COLLECTION.is(this.getType()); } public boolean isArray() { return FieldType.ARRAY.is(this.getType()); } public boolean isLinkCollection() { return FieldType.LINK_COLLECTION.is(this.getType()); } public boolean isVariableLink() { return FieldType.VARIABLE_LINK.is(this.getType()); } public boolean isRelativeInner() { return FieldType.RELATIVE_INNER.is(this.getType()); } public boolean isInner() { return this.isInnerCollection() || this.isRelativeInner(); } } /* class Type { int code; String linkedObject; Type next; Type pre; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getLinkedObject() { return linkedObject; } public void setLinkedObject(String linkedObject) { this.linkedObject = linkedObject; } public Type getNext() { return next; } public void setNext(Type next) { this.next = next; } public Type getPre() { return pre; } public void setPre(Type pre) { this.pre = pre; } }*/
package org.corfudb.runtime.exceptions; /** * This exception is thrown when a client tries to read an address * that has been trimmed. */ public class TrimmedException extends LogUnitException { public TrimmedException() { } public TrimmedException(String message) { super(message); } }
package info.fandroid.mindmap.util; import java.util.Random; import info.fandroid.mindmap.R; /** * Created by Vitaly on 29.12.2015. */ public class ColorManager { public static final int[] color = { R.color.planet_color_1_1, R.color.planet_color_2_1, R.color.planet_color_3_1, R.color.planet_color_4_1, R.color.planet_color_5_1, R.color.planet_color_1_2, R.color.planet_color_2_2, R.color.planet_color_3_2, R.color.planet_color_4_2, R.color.planet_color_5_2, R.color.planet_color_1_3, R.color.planet_color_2_3, R.color.planet_color_3_3, R.color.planet_color_4_3, R.color.planet_color_5_3}; public static int getRandomColor() { Random rand = new Random(); return color[rand.nextInt(color.length - 1)]; } }
package express.product.pt.cn.fishepress; import android.support.v4.app.Fragment; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager; import com.ashokvarma.bottomnavigation.BottomNavigationBar; import com.ashokvarma.bottomnavigation.BottomNavigationItem; import java.util.ArrayList; import express.product.pt.cn.fishepress.base.BaseActivity; import express.product.pt.cn.fishepress.base.ClientApp; import express.product.pt.cn.fishepress.ui.buy.BuyFragment; import express.product.pt.cn.fishepress.ui.cook.CookFragment; import express.product.pt.cn.fishepress.ui.index.IndexFragment; import express.product.pt.cn.fishepress.ui.personal.PersonalFragment; import express.product.pt.cn.fishepress.utils.ToastUtils; public class MainActivity extends BaseActivity implements BottomNavigationBar.OnTabSelectedListener { private BottomNavigationBar bottomNavigationBar; @Override public int getLayoutID() { return R.layout.activity_main; } @Override public void initViews() { bottomNavigationBar=findView(R.id.b_n_b); bottomNavigationBar.setMode(BottomNavigationBar.MODE_FIXED); bottomNavigationBar.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC); bottomNavigationBar.addItem(new BottomNavigationItem(R.drawable.index,"首页")) .addItem(new BottomNavigationItem(R.drawable.cook,"食材搭配")) .addItem(new BottomNavigationItem(R.drawable.buy,"购物车")) .addItem(new BottomNavigationItem(R.drawable.personal,"首页")) .setInActiveColor(R.color.textColorGray) .setActiveColor(R.color.colorTheme) .initialise(); switchFragment(new IndexFragment()); bottomNavigationBar.setForegroundGravity(Gravity.BOTTOM); getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } @Override public void initListener() { bottomNavigationBar.setTabSelectedListener(this); } @Override public void initData() { } @Override public void processClick(View v) { } public void switchFragment(Fragment frag){ getSupportFragmentManager().beginTransaction().replace(R.id.main_fragment_container,frag).commit(); } public ArrayList<Fragment> getFragments(){ ArrayList<Fragment> fragments=new ArrayList<>(); fragments.add(new IndexFragment()); fragments.add(new CookFragment()); fragments.add(new BuyFragment()); fragments.add(new PersonalFragment()); return fragments; } @Override public void onTabSelected(int position) { switchFragment(getFragments().get(position)); } @Override public void onTabUnselected(int position) { // getSupportFragmentManager().beginTransaction().remove(fragment).commit(); } @Override public void onTabReselected(int position) { } long firstTime=0; @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if(keyCode==KeyEvent.KEYCODE_BACK){ long secondTime=System.currentTimeMillis(); if(secondTime-firstTime>2000){ firstTime=secondTime; ToastUtils.showShortToast(ClientApp.getContext(),"再按一次退出程序"); return true; }else { System.exit(0); } } return super.onKeyUp(keyCode, event); } }
package managers; import DBApi.Chat; import DBApi.ChatMessage; import DBApi.HibernateUtil; import DBApi.PrivateMessage; import org.hibernate.Criteria; import org.hibernate.Session; import DBApi.Location; import org.hibernate.impl.CriteriaImpl; import tools.LocationInfo; import tools.MessagePool; import java.util.*; public class MessageManager { public static final int CHAT_CLEAR_TIME=1000*60*1; public static final int LOT=10; public static final int chatKesh=20; Session session=HibernateUtil.getSession(); public MessageManager(){ } public MessagePool privatemessagePool=new MessagePool(); public HashMap<Integer,Chat> chats =new HashMap<Integer,Chat>(); public void addChat(Chat chat){ Location l=chat.getLocation(); if(l==null)return; int i=(int)Math.floor(l.getLongitude()); int j=(int)Math.floor(l.getLatitude()); chats.put(chat.getId(),chat); } public Chat removeChat(int id){ return chats.remove(id); } public boolean sendPrivateMessage(PrivateMessage m){ session.beginTransaction(); session.save(m); session.getTransaction().commit(); return privatemessagePool.addMessage(m); } public boolean sendMessageToChat(ChatMessage m){ Chat c= chats.get(m.getChatId()); Session s=HibernateUtil.getSession(); if(c!=null) { c.addMessage(m); s.beginTransaction(); s.save(m); s.getTransaction().commit(); if(c.getMessages().size()>chatKesh) c.getMessages().remove(c.getMessages().size()-1); return true; } else return false; } public List<PrivateMessage>getNewPrivateMessages(int userId){ return privatemessagePool.getMessages(userId); } public List<PrivateMessage>getDialogMessages(int user1Id,int user2Id,long dateOffset){ org.hibernate.Query q=session.createQuery("from PrivateMessage where (userToId= :userToId or userToId= :userFromId) and (userFromId= :userToId or userFromId= :userFromId) and date< :date order by date asc"); q.setLong("userToId", 2); q.setLong("userFromId", 1); q.setLong("date", dateOffset); q.setMaxResults(10); return q.list(); } public List<ChatMessage>getLastChatMessages(int chatId,long date){ List<ChatMessage> messages=new ArrayList<ChatMessage>(); Chat c= chats.get(chatId); if(c==null)return null; int n=0; try { for (ChatMessage m : c.getMessages()) { if (m.getDate() < date || n > 20) break; messages.add(m); n++; } } catch (Exception e){} return messages; } public List<ChatMessage>getChatMessages(int chatId,long date){ org.hibernate.Query q = session.createQuery("from ChatMessage where chatId =:chatId and date< :date order by date asc"); q.setLong("chatId",chatId); q.setLong("date",date); q.setMaxResults(20); return q.list(); } public List<Chat> getChats(Location l){ org.hibernate.Query q = session.createQuery("from Chat where locationGroup =:group"); q.setInteger("group",LocationManager.locationGroup(l)); return q.list(); } }
package com.allmsi.test.controller; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition; import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition; import org.springframework.web.servlet.mvc.method.RequestMappingInfo; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; import com.allmsi.sys.model.protocol.SuccessProtocol; import com.allmsi.sys.model.protocol.WarnProtocol; import com.allmsi.sys.util.StrUtil; import com.allmsi.test.model.MethodVo; import com.allmsi.test.model.UrlTree; @Controller @RequestMapping("/test") public class TestController { @Resource private RequestMappingHandlerMapping requestMappingHandlerMapping; private final List<String> EXCLUDE_LIST = Arrays.asList("/login", "/logout"); @RequestMapping(value = "/controller/url", method = RequestMethod.GET) @ResponseBody public Object url(String url) { List<UrlTree> urlList = new ArrayList<>(); Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods(); for (Map.Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) { UrlTree urlTree = new UrlTree(); RequestMappingInfo info = m.getKey(); PatternsRequestCondition p = info.getPatternsCondition(); for (String tempUrl : p.getPatterns()) { if ((StrUtil.isEmpty(url) || tempUrl.indexOf(url) > -1) && !EXCLUDE_LIST.contains(tempUrl)) { urlTree.setLabel(tempUrl); urlList.add(urlTree); } } } return new SuccessProtocol(urlList); } @RequestMapping(value = "/controller/method", method = RequestMethod.GET) @ResponseBody public Object method(String url) { if (StrUtil.isEmpty(url)) { return new WarnProtocol(); } MethodVo methodResult = new MethodVo(); Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods(); for (Map.Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) { RequestMappingInfo info = m.getKey(); HandlerMethod method = m.getValue(); PatternsRequestCondition p = info.getPatternsCondition(); for (String tempUrl : p.getPatterns()) { if (url.equals(tempUrl)) { methodResult.setUrl(url); break; } } if (StrUtil.notEmpty(methodResult.getUrl())) { methodResult.setClassName(method.getMethod().getDeclaringClass().getName()); // 类名 methodResult.setMethod(method.getMethod().getName()); // 方法名 Parameter[] parameters = method.getMethod().getParameters(); List<String> parameterList = new ArrayList<>(); for (Parameter parameter : parameters) { String typeName = parameter.getType().getSimpleName(); if ("String".equals(typeName) || "Integer".equals(typeName)) { parameterList.add(parameter.getName()); } else { Method[] methods = parameter.getType().getMethods(); for (Method tempMethod : methods) { String methodsName = tempMethod.getName(); if (methodsName.startsWith("set")) { for (Parameter tempParameter : tempMethod.getParameters()) { parameterList.add(tempParameter.getName()); } } } } } methodResult.setParameters(parameterList); RequestMethodsRequestCondition methodsCondition = info.getMethodsCondition(); String type = methodsCondition.toString(); if (type != null && type.startsWith("[") && type.endsWith("]")) { type = type.substring(1, type.length() - 1); methodResult.setType(type); // 方法名 } break; } } return new SuccessProtocol(methodResult); } }
package com.bofsoft.laio.customerservice.DataClass.Order; import com.bofsoft.laio.data.BaseData; /** * 教练获取来噢教练车档案信息 * * @author yedong */ public class CarDocInfoData extends BaseData { public String CarLicense; // 车牌号 public String CarInfo; // 准教证、驾驶证等信息,以<br>分隔(注:学员请求时,不会返回此信息) }
package com.imooc.ioc.demo2; /** * @Author: Asher Huang * @Date: 2019-10-15 * @Description: com.imooc.ioc.demo2 * @Version:1.0 */ public class Bean3Factory { public Bean3 createBean3() { System.out.println("Bean3的工厂方法被执行了"); return new Bean3(); } }
package df.repository.api; import df.repository.entry.id.EntityId; import df.repository.entry.value.EntryValue; import java.util.Map; public interface ICache extends IRepository<EntityId, EntryValue> { <V> V get(K theKey); <V> Iterable<V> getAll(Iterable<K> theKey); <K> K put(K theKey, V theValue); void putAll(Map<K, V> theMap); }
package com.kemp.qrcode; import android.graphics.Bitmap; import android.os.Bundle; import android.util.Log; import android.view.SurfaceView; import android.widget.ImageView; import com.google.zxing.client.android.CaptureActivity; import com.google.zxing.client.android.ViewfinderView; public class MainActivity extends CaptureActivity { @Override public void onCreate(Bundle savedInstanceState) { setOrientationPortrait(true); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view); ViewfinderView viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view); setMainView(surfaceView, viewfinderView); } @Override public void handleDecodeText(String result) { Log.d("MainActivity", result); finish(); } @Override public void handleDecodeBitmap(Bitmap result) { ImageView iv = (ImageView) findViewById(R.id.iv); iv.setImageBitmap(result); } }
package com.bofsoft.laio.laiovehiclegps.Widget; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.bofsoft.laio.laiovehiclegps.R; /** * 自定义工具栏 * Created by Bofsoft on 2017/5/15. */ public class MyToolBar extends RelativeLayout implements View.OnClickListener { private ImageView leftImg, rightImg;//工具栏的左右图片 private TextView txt_title, txt_line;//工具栏中间的主题,工具栏和下面布局的分隔线 private MyToolBar myToolBar;//自定义工具栏 public MyToolBar(Context context, AttributeSet attrs) { super(context, attrs); if (context instanceof MyToolBarClickListener) { myToolBarClickListener = (MyToolBarClickListener) context; } LayoutInflater.from(context).inflate(R.layout.widget_mytoolbar, this); init(); } public void init() { findView(); } private void findView() { leftImg = (ImageView) findViewById(R.id.toorBar_leftImageView); txt_title = (TextView) findViewById(R.id.toorBar_title); rightImg = (ImageView) findViewById(R.id.toorBar_rightImageView); txt_line = (TextView) findViewById(R.id.toorBar_line); rightImg.setOnClickListener(this); leftImg.setOnClickListener(this); } //设置左图片 public void setLeftImg(int resId) { leftImg.setImageResource(resId); } //设置右图片 public void setRightImg(int resId) { rightImg.setImageResource(resId); } //设置主题 public void setTitle(String title) { txt_title.setText(title); } //设置是否显示分隔线,默认不显示 public void setLine(boolean flag) { if (flag == true) { txt_line.setVisibility(View.VISIBLE); } }//设置是否显示左图片,默认显示 public void setLeftImgVisibility(boolean flag) { if (flag == false) { txt_line.setVisibility(View.GONE); } }//设置是否显示右图片,默认显示 public void setRightImgVisibility(boolean flag) { if (flag == false) { txt_line.setVisibility(View.GONE); } } public interface MyToolBarClickListener{ void onLeftClick(); void onRightClick(); } MyToolBarClickListener myToolBarClickListener = null; //工具栏左侧和右侧图片点击事件 @Override public void onClick(View v) { if (v.getId()==R.id.toorBar_leftImageView){ myToolBarClickListener.onLeftClick(); }else if (v.getId()==R.id.toorBar_rightImageView){ myToolBarClickListener.onRightClick(); } } }
/** * */ package square; /** * @author NikitaNB * */ public class Figure { public static final int SQUARE = 1; public static final int LINE = 2; public static final int ZIGZAG1 = 3; public static final int ZIGZAG2 = 4; public static final int CORNER1 = 5; public static final int CORNER2 = 6; public static final int TOBJECT = 7; public static final int COUNTTYPE = 7; //public static final int protected int x=-1; protected int y=-1; private Square figure[]=null; public Figure(int x, int y, int figureConst){ this.x=x; this.y=y; figure = new Square[4]; switch(figureConst){ case SQUARE: figure[0]=new Square(1,1); figure[1]=new Square(2,1); figure[2]=new Square(1,2); figure[3]=new Square(2,2); break; case LINE: figure[0]=new Square(0,1); figure[1]=new Square(1,1); figure[2]=new Square(2,1); figure[3]=new Square(3,1); break; case ZIGZAG1: figure[0]=new Square(1,1); figure[1]=new Square(1,2); figure[2]=new Square(2,2); figure[3]=new Square(2,3); break; case ZIGZAG2: figure[0]=new Square(2,1); figure[1]=new Square(1,2); figure[2]=new Square(2,2); figure[3]=new Square(1,3); break; case CORNER1: figure[0]=new Square(1,1); figure[1]=new Square(2,1); figure[2]=new Square(1,2); figure[3]=new Square(1,3); break; case CORNER2: figure[0]=new Square(1,1); figure[1]=new Square(2,1); figure[2]=new Square(2,2); figure[3]=new Square(2,3); break; case TOBJECT: figure[0]=new Square(2,1); figure[1]=new Square(1,2); figure[2]=new Square(2,2); figure[3]=new Square(3,2); break; default: throw new IllegalArgumentException("Unknown figure; figureConst = "+figureConst); } } public int getX(){ return x; } public int getY(){ return y; } public void down(){ y++; } public void right(){ x++; } public void left(){ x--; } public void rotateR(){ for(int i =0;i<figure.length;i++) //figure[i].transpon(); figure[i].rotateOnClock(); } public void rotateL(){ for(int i =0;i<figure.length;i++) //figure[i].transpon(); figure[i].rotateConClock(); } public Square[] getSquares(){ return figure; } public Member[][] getBitField(){ Member[][] bits = new Member[figure.length][figure.length]; for(int i=0;i<figure.length;i++){ for(int j=0;j<figure.length;j++) bits[j][i] = null; for(int j=0;j<figure.length;j++) bits[figure[j].x][figure[j].y]=figure[j]; } return bits; } }
package cn.com.onlinetool.fastpay.pay.wxpay.request; import cn.com.onlinetool.fastpay.annotations.validation.Validation; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * @author choice * @description: 微信 退款查询 请求对象 * 应用场景: * 提交退款申请后,通过调用该接口查询退款状态。退款有一定延时,用零钱支付的退款20分钟内到账,银行卡支付的退款3个工作日后重新查询退款状态。 * 注意: * 如果单个支付订单部分退款次数超过20次请使用退款单号查询 * 分页查询: * 当一个订单部分退款超过10笔后,商户用微信订单号或商户订单号调退款查询API查询退款时,默认返回前10笔和total_refund_count(订单总退款次数)。 * 商户需要查询同一订单下超过10笔的退款单时,可传入订单号及offset来查询,微信支付会返回offset及后面的10笔,以此类推。 * 当商户传入的offset超过total_refund_count,则系统会返回报错PARAM_ERROR。 * 举例: * 一笔订单下的退款单有36笔,当商户想查询第25笔时,可传入订单号及offset=24,微信支付平台会返回第25笔到第35笔的退款单信息,或商户可直接传入退款单号查询退款 * 是否需要证书: * 不需要。 * @date 2019-06-10 20:30 * */ @NoArgsConstructor @AllArgsConstructor @Data @Validation public class WXPayRefundQueryRequest extends WXPayBaseRequest { /** * 微信订单号 微信订单号/商户订单号/商户退款单号/微信退款单号 四选一 * 微信生成的订单号,在支付通知中有返回 */ private String transactionId; /** * 商户订单号 微信订单号/商户订单号/商户退款单号/微信退款单号 四选一 * 商户系统内部订单号,要求32个字符内,只能是数字、大小写字母_-|*@ ,且在同一个商户号下唯一。 */ private String outTradeNo; /** * 商户退款单号 微信订单号/商户订单号/商户退款单号/微信退款单号 四选一 * 商户系统内部的退款单号,商户系统内部唯一,只能是数字、大小写字母_-|*@ ,同一退款单号多次请求只退一笔。 */ private String outRefundNo; /** * 微信退款单号 微信订单号/商户订单号/商户退款单号/微信退款单号 四选一 * 微信生成的退款单号,在申请退款接口有返回 */ private String refundId; /** * 偏移量 非必填 * 偏移量,当部分退款次数超过10次时可使用,表示返回的查询结果从这个偏移量开始取记录 */ private Integer offset; }
package com.tech.interview.siply.redbus.service.implementation; import com.tech.interview.siply.redbus.configuration.RedbusUserDetails; import com.tech.interview.siply.redbus.entity.dao.users.Owner; import com.tech.interview.siply.redbus.entity.dto.OwnerDTO; import com.tech.interview.siply.redbus.entity.dto.UserDTO; import com.tech.interview.siply.redbus.repository.contract.users.OwnerRepository; import com.tech.interview.siply.redbus.service.contract.OwnerService; import lombok.AllArgsConstructor; import org.modelmapper.ModelMapper; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.stream.Collectors; @Service @AllArgsConstructor public class OwnerServiceImpl implements OwnerService, UserDetailsService { final ModelMapper modelMapper = new ModelMapper(); OwnerRepository ownerRepository; @Override public String addOwner(OwnerDTO ownerDTO) { UserDTO userDTO = modelMapper.map(ownerDTO, UserDTO.class); Owner owner = new Owner(userDTO, ownerDTO); ownerRepository.save(owner); return "Saved Owner"; } @Override public List<OwnerDTO> getAllOwnerUsers() { Pageable pageable = PageRequest.of(0,10); return ownerRepository.findAll(pageable).stream().map(owner -> modelMapper.map(owner, OwnerDTO.class) ).collect(Collectors.toList()); } @Override public void deleteOwnerUser(UUID id) { ownerRepository.deleteById(id); } @Override public OwnerDTO getOwnerById(UUID id) { return modelMapper.map(ownerRepository.findById(id).get(), OwnerDTO.class); } @Override public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException { Optional<Owner> ownerUser = ownerRepository.findByUserName(userName); return new RedbusUserDetails(ownerUser.orElseThrow(() -> new UsernameNotFoundException("Owner not found"))); } }
package student.pl.edu.pb.geodeticapp.views; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; import android.view.View; import student.pl.edu.pb.geodeticapp.R; public class CompassView extends View { private Context context; private Paint needleNPaint; private Paint needleEWPaint; private Paint needleSPaint; private int compassBackgroundColor; private boolean transparent; private double rotationAngle; private double needleAxisX; private double needleAxisY; private double needleLength; private double needleWidth; private double[] needlePointsBuffer; private Path needlePath; private Matrix pathTransformMatrix; public CompassView(Context context) { super(context); init(context); } public CompassView(Context context, AttributeSet attributeSet) { super(context, attributeSet); init(context); } public CompassView(Context context, AttributeSet attributeSet, int defStyle) { super(context, attributeSet, defStyle); init(context); } @Override public void onDraw(Canvas canvas) { super.onDraw(canvas); drawBackground(canvas); drawNeedle(canvas, 0.0 + rotationAngle, needleNPaint); drawNeedle(canvas, 90 + rotationAngle, needleEWPaint); drawNeedle(canvas, 180 + rotationAngle, needleSPaint); drawNeedle(canvas, 270 + rotationAngle, needleEWPaint); drawDetails(canvas); } @Override public void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); needleAxisX = w / 2.0; needleAxisY = 0.9 * h; needleLength = h * 0.8; needleWidth = needleLength / 3.0; } public void update(double rotationAngle) { this.rotationAngle = rotationAngle; invalidate(); } private void init(Context context) { this.context = context; transparent = false; needleNPaint = new Paint(); needleEWPaint = new Paint(); needleSPaint = new Paint(); needleNPaint.setColor(ContextCompat.getColor(context, R.color.compassNeedleN)); needleNPaint.setStyle(Paint.Style.FILL); needleEWPaint.setColor(ContextCompat.getColor(context, R.color.compassNeedleEW)); needleEWPaint.setStyle(Paint.Style.FILL); needleSPaint.setColor(ContextCompat.getColor(context, R.color.compassNeedleS)); needleSPaint.setStyle(Paint.Style.FILL); compassBackgroundColor = ContextCompat.getColor(context, R.color.compassBackground); needlePointsBuffer = new double[6]; rotationAngle = 0.0; needlePath = new Path(); pathTransformMatrix = new Matrix(); } private void drawNeedle(Canvas canvas, double rotationOffset, Paint paint) { needlePointsBuffer[0] = needleAxisX; needlePointsBuffer[1] = needleAxisY - needleLength; needlePointsBuffer[2] = needleAxisX - needleWidth / 2.0; needlePointsBuffer[3] = needleAxisY; needlePointsBuffer[4] = needleAxisX + needleWidth / 2.0; needlePointsBuffer[5] = needleAxisY; needlePath.moveTo((float) needlePointsBuffer[0], (float) needlePointsBuffer[1]); needlePath.lineTo((float) needlePointsBuffer[2], (float) needlePointsBuffer[3]); needlePath.lineTo((float) needlePointsBuffer[4], (float) needlePointsBuffer[5]); needlePath.lineTo((float) needlePointsBuffer[0], (float) needlePointsBuffer[1]); needlePath.close(); pathTransformMatrix.setRotate((float) (-rotationOffset), (float) needleAxisX, (float) needleAxisY); needlePath.transform(pathTransformMatrix); canvas.drawPath(needlePath, paint); needlePath.reset(); pathTransformMatrix.reset(); } private void drawBackground(Canvas canvas) { if (transparent) { canvas.drawColor(Color.TRANSPARENT); } else { canvas.drawColor(compassBackgroundColor); } } private void drawDetails(Canvas canvas) { canvas.drawCircle((float) needleAxisX, (float) needleAxisY, (float) (needleWidth * 0.6), needleEWPaint); } public int getNeedleNColor() { return needleNPaint.getColor(); } public void setNeedleNColor(int needleNColor) { this.needleNPaint.setColor(needleNColor); } public Paint getNeedleEWPaint() { return needleEWPaint; } public void setNeedleEWPaint(Paint needleEWPaint) { this.needleEWPaint = needleEWPaint; } public Paint getNeedleSPaint() { return needleSPaint; } public void setNeedleSPaint(Paint needleSPaint) { this.needleSPaint = needleSPaint; } public int getCompassBackgroundColor() { return compassBackgroundColor; } public void setCompassBackgroundColor(int compassBackgroundColor) { this.compassBackgroundColor = compassBackgroundColor; } public boolean isTransparent() { return transparent; } public void setTransparent(boolean transparent) { this.transparent = transparent; } }
package gayares; public class comprogActivityComputation { public static void main(String[] args) { double grossPay,deduction,netPay; grossPay = 25_000.00; deduction = grossPay * .1; netPay = grossPay - deduction; System.out.println("==Deduction & Netpay==\n"); System.out.println("Grosspay: " + grossPay); System.out.println("Deduction: " + deduction); System.out.println("Net Pay: " + netPay); } }
package factoring.fermat; import factoring.math.PrimeMath; import java.util.Collection; /** * n = (xArray+y)^2 - (xArray-y)^2 = xArray^2 - y^2 , 0 <= y <= sqrt(n) * n + y^2 = xArray^2 * Created by Thilo Harich on 02.03.2017. */ public class FermatDec extends FermatFact { @Override public long findFactors(long n, Collection<Long> factors) { long sqrtN = (long) Math.floor(Math.sqrt(n)); for (long y = sqrtN; y >= 0; y--) { long right = n + y*y; // long sqrtR = PrimeMath.sqrt(right); // long error = n + sqrtR*sqrtR; // right = n + (y-error)*(y-error); if(PrimeMath.isSquare(right)) { long x = (long) Math.sqrt(right); factors.add((x+y)); return n/(x+y); } } return n; } }
package edu.colostate.cs.cs414.soggyZebras.rollerball.Game; import edu.colostate.cs.cs414.soggyZebras.rollerball.Server.User; import edu.colostate.cs.cs414.soggyZebras.rollerball.Transport.TCPConnection; import javax.swing.*; import java.util.*; public class Game implements java.io.Serializable { private static final long serialVersionUID = 652968509827690L; protected Map<Location,Piece> board; private User player1; private User player2; private boolean inProgress; private User winner; private User loser; private int gameID; // set to 'w' or 'b' depending on who's turn it is private User whosTurn; /** * create a new game with the initial game board */ public Game(int id,User p1, User p2) { this.board = new HashMap<>(); this.gameID = id; this.player1 = p1; this.player2 = p2; this.inProgress = true; this.whosTurn = p1; this.winner = this.loser = null; // add white pieces addPiece(new Pawn(new Location(5, 2), 'w', "pawn")); addPiece(new Pawn(new Location(6, 2), 'w', "pawn")); addPiece(new King(new Location(5, 3), 'w', "king")); addPiece(new Bishop(new Location(6, 3), 'w', "bishop")); addPiece(new Rook(new Location(5, 4), 'w', "rook")); addPiece(new Rook(new Location(6, 4), 'w', "rook")); // add black pieces addPiece(new Pawn(new Location(0, 4), 'b', "pawn")); addPiece(new Pawn(new Location(1, 4), 'b', "pawn")); addPiece(new King(new Location(1, 3), 'b', "king")); addPiece(new Bishop(new Location(0, 3), 'b', "bishop")); addPiece(new Rook(new Location(0, 2), 'b', "rook")); addPiece(new Rook(new Location(1, 2), 'b', "rook")); } public Game(){} public Game(Map<Location,Piece> m) { this.board = m; } public void addPiece(Piece p) { board.put(p.loc, p); } public ArrayList<Location> validMoves(User p, Location l){ return board.get(l).validMoves(board); } public ArrayList<Location> validMoves(Location loc, Map <Location,Piece> boardPassed){ return boardPassed.get(loc).validMoves(boardPassed); } // TODO can we maybe remove this/do we need the check for which user has the turn (in other method) public ArrayList<Location> validMoves(Location l){ return board.get(l).validMoves(board); } /** * Function to move a piece from starting location to new location * @param to - new location to move to * @param from - old location to move from * @return - returns board state */ public Map<Location, Piece> makeMove(User p, Location to, Location from){ if(whosTurn == p) { board.put((to), board.get(from)); board.get(to).setLoc(to); board.remove(from); if (whosTurn.equals(player1)) { whosTurn = player2; } else { whosTurn = player1; } } return board; } /** * Function to calculate if the white pieces have won by checkmating the black king * @return - returns true if white piece has won */ public boolean wonGameW(){ System.err.println(!teamHasKing('b')); if (!teamHasKing('b')) return true; //TODO: need a check for if the piece can capture and it is not your turn so you cannot get away in time but the king might have a move - check on clicked? user has chosen the wrong piece and cannot get away Set<Location> allWLocs = new HashSet<Location>(); ArrayList<Location> KingMoves = new ArrayList<Location>(); ArrayList<Location> compare = new ArrayList<Location>(); Location kingLoc = null; for(Location I :board.keySet()){ if(board.get(I).getColor()=='w'){ for(Location X : validMoves(I)) { allWLocs.add(X); } } if(board.get(I).getColor()=='b'&& board.get(I).getType()=="king"){ KingMoves = validMoves(I); kingLoc = I; } } //Now all valid black moves and white king moves are populated. if(KingMoves.isEmpty()&&allWLocs.contains(kingLoc)){ //case for if King has no valid moves and will be captured return true; } else if(KingMoves.isEmpty()&&!allWLocs.contains(kingLoc)) return false; //King is in initial position or surrounded by friendly pieces else { compare.addAll(KingMoves); for (Location I : KingMoves) { if (allWLocs.contains(I)) { compare.remove(I); } } } return compare.isEmpty(); } /** * Function to calculate if the black pieces have won by checkmating the white king * @return - returns true if black piece has won */ public boolean wonGameB(){ if (!teamHasKing('w')) return true; //TODO: need a check for if the piece can capture and it is not your turn so you cannot get away in time but the king might have a move - check on clicked? user has chosen the wrong piece and cannot get away Set<Location> allBLocs = new HashSet<Location>(); ArrayList<Location> KingMoves = new ArrayList<Location>(); ArrayList<Location> compare = new ArrayList<Location>(); Location kingLoc = null; for(Location I :board.keySet()){ if(board.get(I).getColor()=='b'){ for(Location X : validMoves(I)) { allBLocs.add(X); } } if(board.get(I).getColor()=='w'&& board.get(I).getType()=="king"){ KingMoves = validMoves(I); kingLoc = I; } } //Now all valid black moves and white king moves are populated. if(KingMoves.isEmpty()&&allBLocs.contains(kingLoc)){ //case for if King has no valid moves and will be captured return true; } else if(KingMoves.isEmpty()&&!allBLocs.contains(kingLoc)){ //TODO: call JoptionPane with message that King is in Check //JOptionPane.showMessageDialog(this, "White King in Check!"); return false; //King is in initial position or surrounded by friendly pieces } else { compare.addAll(KingMoves); for (Location I : KingMoves) { if (allBLocs.contains(I)) { compare.remove(I); } } } return compare.isEmpty(); } /** * check to see if a team has their king * @param whichTeam 'w' for white, 'b' for black * @return true if the team has their king */ private boolean teamHasKing(char whichTeam) { ArrayList<Location> allLocs = new ArrayList<>(); for(Location l : board.keySet()) { if (board.get(l).getColor() == whichTeam && board.get(l) instanceof King) { return true; } } return false; } /** * Function to determine a stalemate condition in the game where neither player has any moves * @return - returns true of both sets of moves are empty */ public boolean stalemate(){ Set<Location> allWLocs = new HashSet<Location>(); Set<Location> allBLocs = new HashSet<Location>(); for(Location I :board.keySet()){ if(board.get(I).getColor()=='b'){ for(Location X : validMoves(I)) { allBLocs.add(X); } } else{ for(Location X : validMoves(I)) { allWLocs.add(X); } } } return(allWLocs.isEmpty()&&allBLocs.isEmpty()); //Case for neither player having a valid move } /** * Function to get current board state of game * @return - returns game Board */ public Map<Location, Piece> getBoard() { return board; } public User getPlayer1(){ return player1; } public User getPlayer2(){ return player2; } public int getGameID(){ return gameID; } public void setGameID(int gID){ gameID = gID; } public User getWhosTurn(){ return whosTurn; } public boolean isInProgress() { return inProgress; } public User getWinner() { return winner; } public User getLoser() { return loser; } public void setWinner(User w){this.winner = w;} public void setLoser(User l){this.loser = l;} public void setInProgress(boolean b){inProgress = b;} }
package com.froi.graficador.entidades; public class Rectangulo extends Figura { private int alto; private int ancho; public Rectangulo(int pox, int poy, int alto, int ancho, String color) { super(pox, poy, color); this.alto = alto; this.ancho = ancho; setDescripcion("RECTANGULO"); } public int getAlto() { return alto; } public int getAncho() { return ancho; } @Override public String toString() { return "\nRectangulo\npox: " + getPox() + "\npoy: " + getPoy() + "\nalto: " + getAlto() + "\nancho: " + getAncho() + "\ncolor: " + getColor(); } }
package com.siscom.controller.dto; import com.siscom.service.model.FormaPgto; import com.siscom.service.model.ItemVenda; import lombok.Getter; import lombok.Setter; import java.util.ArrayList; @Getter @Setter public class VendaDto { private Integer codigoCliente; private Integer codigoVendedor; private FormaPgto formaPagamento; private ArrayList<ItemVenda> itensVenda; }
package de.amr.games.pacman.controller.event; import de.amr.games.pacman.model.common.PacManGameModel; public class ScatterPhaseStartedEvent extends PacManGameEvent { public final int scatterPhase; public ScatterPhaseStartedEvent(PacManGameModel gameModel, int scatterPhase) { super(gameModel, Info.OTHER, null, null); this.scatterPhase = scatterPhase; } @Override public String toString() { return String.format("ScatterPhaseStartedEvent: scatterPhase=%d", scatterPhase); } }
package cn.test.future; import com.google.common.util.concurrent.ThreadFactoryBuilder; import lombok.extern.slf4j.Slf4j; import java.util.UUID; import java.util.concurrent.*; import java.util.concurrent.locks.ReentrantLock; /** * @author Created by xiaoni on 2019/7/12. */ @Slf4j public class TestFuture { ReentrantLock reentrantLock = new ReentrantLock(); ReentrantLock mainObjectLock = new ReentrantLock(); ExecutorService executorService = new ThreadPoolExecutor(5, 30, 5000L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(1024), new ThreadFactoryBuilder().setNameFormat("sendHttpMessage-Pool-%d").build(), new ThreadPoolExecutor.AbortPolicy()); public void test(String threadName) throws Exception { //单台机器在50秒内,向云端请求最多25次(间隔2s/次),所以线程池容量200理论最大可以支持8台同时网络不好的最极端情况,超过该能力后可能后台仍然卡死 Future<String> future = executorService.submit(new CallableAjaxResult(threadName)); int i = 0; while (!future.isDone()) { try { log.info(threadName + "future is done count:" + i++); Thread.sleep(1000); } catch (InterruptedException e) { } } try { log.info(threadName + "test response: {}", future.get()); } catch (InterruptedException e) { log.error(threadName + e.getMessage(), e); } catch (ExecutionException e) { log.error(threadName + e.getMessage(), e); } } /** * 模拟主线程掉用数据库锁 */ public void test2MainLock(String threadName) { try { if (mainObjectLock.tryLock()) { log.info(threadName + "拿到了mainObject锁"); } else { log.info(threadName + "没拿到mainObject锁"); } } catch (Exception e) { log.error(threadName + e.getMessage(), e); } finally { try { if (mainObjectLock != null && mainObjectLock.isLocked()) { log.info(threadName + "最终释放mainObject锁"); mainObjectLock.unlock(); } } catch (IllegalMonitorStateException e) { log.info(threadName + "当前线程没有占用mainObject锁" + e.getMessage(), e); } } } class CallableAjaxResult implements Callable<String> { private String threadName; CallableAjaxResult(String threadName) { this.threadName = threadName; } @Override public String call() throws Exception { log.info("开始写入test,threadName=" + threadName); try { String uuid = UUID.randomUUID().toString(); try { test2MainLock(threadName); if (!reentrantLock.tryLock()) { log.debug(threadName + "未获取到锁,下次再试"); return threadName + "未获取到锁,下次再试"; } log.info(threadName + "开始等待消息{}回执:{}", uuid, System.currentTimeMillis()); for (int i = 0; i < 10; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { log.error(e.getMessage(), e); } if (i == 8) { throw new Exception(threadName + "test error"); } } log.info(threadName + "收到消息{}机器人回执:{}", uuid, System.currentTimeMillis()); return threadName + "success 1"; } catch (Exception e) { log.error(threadName + e.getMessage(), e); return threadName + e.getMessage(); } finally { try { if (reentrantLock != null && reentrantLock.isLocked()) { log.info(threadName + "最终释放锁"); reentrantLock.unlock(); } } catch (IllegalMonitorStateException e) { log.info(threadName + "当前线程没有占用锁" + e.getMessage(), e); } } } catch (Exception e) { log.error(threadName + e.getMessage(), e); return threadName + e.getMessage(); } } } public static void main(String[] args) { TestFuture testFuture = new TestFuture(); try { for (int i = 0; i < 10; i++) { final int j = i; new Thread(new Runnable() { @Override public void run() { try { testFuture.test("thread-" + j + "|||||"); } catch (Exception e) { e.printStackTrace(); } } }).start(); } for (int i = 10; i < 20; i++) { final int j = i; new Thread(new Runnable() { @Override public void run() { try { testFuture.test("thread-" + j + "|||||"); } catch (Exception e) { e.printStackTrace(); } } }).start(); } } catch (Exception e) { e.printStackTrace(); } } }
package com.bslp_lab1.changeorg.service; import com.bslp_lab1.changeorg.DTO.PetitionDTO; import com.bslp_lab1.changeorg.DTO.ResponseMessageDTO; import com.bslp_lab1.changeorg.beans.Petition; import com.bslp_lab1.changeorg.beans.User; import com.bslp_lab1.changeorg.exceptions.PetitionNotFoundException; import com.bslp_lab1.changeorg.exceptions.UserNotFoundException; import com.bslp_lab1.changeorg.repository.PetitionRepository; import org.hibernate.exception.ConstraintViolationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; @Service public class PetitionRepositoryService{ @Autowired private PetitionRepository petitionRepository; @Autowired private UserRepositoryService userRepositoryService; @Autowired private DTOConverter dtoConverter; public List<Petition> findAll(){ return this.petitionRepository.findAll(); } public Petition findById(Long id) throws PetitionNotFoundException{ Petition petition = this.petitionRepository.findByID(id); if(petition == null){ throw new PetitionNotFoundException("Петиция не найдена", HttpStatus.BAD_REQUEST); } return petition; } public PetitionDTO findByIdToResponse(Long id) throws PetitionNotFoundException{ Petition petition = this.findById(id); PetitionDTO petitionDTO = dtoConverter.convertPetitionToDTO(petition); return petitionDTO; } public ArrayList<PetitionDTO> getAllPetitions(){ ArrayList<PetitionDTO> petitionDTOS = new ArrayList<>(); ArrayList<Petition> petitions = new ArrayList<>(this.findAll()); for (Petition petition : petitions){ petitionDTOS.add(dtoConverter.convertPetitionToDTO(petition)); } return petitionDTOS; } public ResponseEntity<ResponseMessageDTO> saveFromDTO(PetitionDTO petitionDTO, HttpServletRequest request){ ResponseMessageDTO message = new ResponseMessageDTO(); try { User owner = this.userRepositoryService.getUserFromRequest(request); Petition petition = dtoConverter.convertPetitionFromDTO(petitionDTO, owner); this.petitionRepository.save(petition); message.setAnswer("Petition was added"); return new ResponseEntity<>(message, HttpStatus.CREATED); } catch (UserNotFoundException e) { message.setAnswer("Petition without owner. Please, try later"); return new ResponseEntity<>(message, HttpStatus.NETWORK_AUTHENTICATION_REQUIRED); } catch (DataIntegrityViolationException e) { String answerText = ""; if(e.getCause().getClass() == ConstraintViolationException.class){ answerText = "Петиция с таким топиком уже существует!"; }else{ answerText = "УПС! Произошла ошибка, пожалуйста, попробуйте позднее"; } message.setAnswer(answerText); return new ResponseEntity<>(message, HttpStatus.BAD_REQUEST); } } public void save(Petition petition){ this.petitionRepository.save(petition); } public void incrementCountSign(Petition petition){ petition.incrementCountSign(); this.save(petition); } public PetitionRepository getPetitionRepository() { return petitionRepository; } }
import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; // TODO: Auto-generated Javadoc /** * The Class Manager. */ public class Manager { /** The commands. */ private CopyOnWriteArrayList<Command> commands; /** The accounts. */ private List<Account> accounts; /** The conversion rate. */ private float conversionRate; /** * Instantiates a new manager. */ public Manager() { commands = new CopyOnWriteArrayList<Command>(); accounts = Collections.synchronizedList(new ArrayList<Account>()); commands.add(new Open(this)); commands.add(new State(this)); commands.add(new Rate(this)); commands.add(new Convert(this)); commands.add(new Transfer(this)); conversionRate = 1.0f; } /** * Process. * * @param command the command * @param input the input * @param out the out */ public void process(String command, String[] input, PrintWriter out) { for (Command cmd : commands) { if (cmd.isCommand(command)) { int inputLength = 0; if (input != null) { inputLength = input.length; } if (cmd.isValid(inputLength)) { try { cmd.process(input, out); } catch (Exception e) { e.printStackTrace(); out.println( "An error occured trying to process that command, please check that you used the right syntax"); out.println("Syntax: " + cmd.help()); } } else { out.println("Invalid syntax! Not enough parameters supplied"); out.println("Syntax: " + cmd.help()); } return; } } out.println("There was no command found matching '" + command + "'"); } /** * Sets the conversion rate. * * @param rate the new conversion rate */ public synchronized void setConversionRate(float rate) { this.conversionRate = rate; } /** * Creates the account. * * @param id the id * @return true, if successful */ public boolean createAccount(int id) { if (getAccountById(id) == null) { accounts.add(new Account(id, 0, 0)); return true; } return false; } /** * Transfer. * * @param accountFrom the account from * @param accountTo the account to * @param arian the arian * @param pres the pres */ public void transfer(int accountFrom, int accountTo, float arian, float pres) { Account from = getAccountById(accountFrom); Account to = getAccountById(accountTo); if(from == null || to == null) { return; } from.setArian(from.getArian() - arian); from.setPres(from.getPres() - pres); to.setArian(to.getArian() + arian); to.setPres(to.getPres() + pres); } /** * Convert. * * @param accountId the account id * @param arian the arian * @param pres the pres */ public void convert(int accountId, float arian, float pres) { // (A−a+p/r, P−p+a·r) Account acc = getAccountById(accountId); if(acc == null) { return; } float newArian = acc.getArian() - arian + pres / conversionRate; float newPres = acc.getPres() - pres + arian / conversionRate; acc.setArian(newArian); acc.setPres(newPres); } /** * Gets the state. * * @return the state */ public String getState() { String state = ""; synchronized(accounts){ for (Account acc : accounts) { state += acc.getId() + ": Arian " + acc.getArian() + ", Pres " + acc.getPres() + "\n"; } } return state; } /** * Gets the account by id. * * @param id the id * @return the account by id */ public Account getAccountById(int id) { synchronized(accounts){ for(Account acc : accounts) { if(acc.getId() == id) { return acc; } } } return null; } }
package orm.integ.test; import java.util.Random; import orm.integ.eao.EntityAccessObject; import orm.integ.test.entity.SchoolClass; import orm.integ.test.entity.SchoolClassService; import orm.integ.test.entity.Student; import orm.integ.test.entity.StudentService; import orm.integ.utils.IdGenerator; public class DataMaker { public static void main(String[] args) { } static void createStudents(int classCount, int studentCountPerClass) { createSchoolClasses(classCount); EntityAccessObject<Student> eao = new StudentService().getEao(); String sql = "delete from tb_student"; eao.getDAO().executeSql(sql); TimeMonitor tm = new TimeMonitor("createStudents"); Student stu; String name; Random rand = new Random(); int count = studentCountPerClass*classCount; for (int i=0; i<count; i++) { stu = new Student(); name = IdGenerator.createRandomStr(12, false); stu.setName(name); stu.setSex(rand.nextInt(2)); stu.setSchoolClassId(rand.nextInt(classCount)+1); eao.insert(stu); } tm.finish("create "+count+" students"); } static void createSchoolClasses(int count) { EntityAccessObject<SchoolClass> eao = new SchoolClassService().getEao(); String sql = "delete from tb_school_class"; eao.getDAO().executeSql(sql); SchoolClass sc; double classNumPerGrade = count/6.0; int grade; for (int i=1; i<=count; i++) { sc = new SchoolClass(); sc.setId(i); sc.setName("class "+i); grade = new Double((i-1)/classNumPerGrade).intValue()+1; System.out.println("i="+i+", grade="+grade); sc.setGrade(grade); eao.insert(sc); } } }
package com.nextLevel.hero.mngSalary.model.dto; import java.sql.Date; public class MngAccountDTO { private int companyNo; private int memberNo; private String memberName; private String searchDate; private String searchCondition; private String searchValue; private String departmentName; private String rank; private int bankCode; private String bankName; private String accountNo; private java.sql.Date enrollDate; private String accountFileUrl; public MngAccountDTO() {} public MngAccountDTO(int companyNo, int memberNo, String memberName, String searchDate, String searchCondition, String searchValue, String departmentName, String rank, int bankCode, String bankName, String accountNo, Date enrollDate, String accountFileUrl) { super(); this.companyNo = companyNo; this.memberNo = memberNo; this.memberName = memberName; this.searchDate = searchDate; this.searchCondition = searchCondition; this.searchValue = searchValue; this.departmentName = departmentName; this.rank = rank; this.bankCode = bankCode; this.bankName = bankName; this.accountNo = accountNo; this.enrollDate = enrollDate; this.accountFileUrl = accountFileUrl; } public int getCompanyNo() { return companyNo; } public void setCompanyNo(int companyNo) { this.companyNo = companyNo; } public int getMemberNo() { return memberNo; } public void setMemberNo(int memberNo) { this.memberNo = memberNo; } public String getMemberName() { return memberName; } public void setMemberName(String memberName) { this.memberName = memberName; } public String getSearchDate() { return searchDate; } public void setSearchDate(String searchDate) { this.searchDate = searchDate; } public String getSearchCondition() { return searchCondition; } public void setSearchCondition(String searchCondition) { this.searchCondition = searchCondition; } public String getSearchValue() { return searchValue; } public void setSearchValue(String searchValue) { this.searchValue = searchValue; } public String getDepartmentName() { return departmentName; } public void setDepartmentName(String departmentName) { this.departmentName = departmentName; } public String getRank() { return rank; } public void setRank(String rank) { this.rank = rank; } public int getBankCode() { return bankCode; } public void setBankCode(int bankCode) { this.bankCode = bankCode; } public String getBankName() { return bankName; } public void setBankName(String bankName) { this.bankName = bankName; } public String getAccountNo() { return accountNo; } public void setAccountNo(String accountNo) { this.accountNo = accountNo; } public java.sql.Date getEnrollDate() { return enrollDate; } public void setEnrollDate(java.sql.Date enrollDate) { this.enrollDate = enrollDate; } public String getAccountFileUrl() { return accountFileUrl; } public void setAccountFileUrl(String accountFileUrl) { this.accountFileUrl = accountFileUrl; } @Override public String toString() { return "MngAccountDTO [companyNo=" + companyNo + ", memberNo=" + memberNo + ", memberName=" + memberName + ", searchDate=" + searchDate + ", searchCondition=" + searchCondition + ", searchValue=" + searchValue + ", departmentName=" + departmentName + ", rank=" + rank + ", bankCode=" + bankCode + ", bankName=" + bankName + ", accountNo=" + accountNo + ", enrollDate=" + enrollDate + ", accountFileUrl=" + accountFileUrl + "]"; } }
package za.ac.cput.chapter5assignment.abstractfactory; /** * Created by student on 2015/03/11. */ public class SecondYearSubjectFactory implements Subjectfactory { private static SecondYearSubjectFactory secondYearSubjectFactory = null; private SecondYearSubjectFactory() { } public static SecondYearSubjectFactory getSecondYearSubjectFactoryInstance() { if (secondYearSubjectFactory == null) return new SecondYearSubjectFactory(); return secondYearSubjectFactory; } @Override public Subject getSubjectName(String subjectCode) { if ("SecondYearDS".equalsIgnoreCase(subjectCode)) { return new SecondYearDS(); } else { return new SecondYearTP(); } } }
package CloudComputing; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; import urn.ebay.api.PayPalAPI.CreateRecurringPaymentsProfileReq; import urn.ebay.api.PayPalAPI.CreateRecurringPaymentsProfileRequestType; import urn.ebay.api.PayPalAPI.CreateRecurringPaymentsProfileResponseType; import urn.ebay.api.PayPalAPI.PayPalAPIInterfaceServiceService; import urn.ebay.api.PayPalAPI.SetExpressCheckoutReq; import urn.ebay.api.PayPalAPI.SetExpressCheckoutRequestType; import urn.ebay.api.PayPalAPI.SetExpressCheckoutResponseType; import urn.ebay.apis.CoreComponentTypes.BasicAmountType; import urn.ebay.apis.eBLBaseComponents.BillingAgreementDetailsType; import urn.ebay.apis.eBLBaseComponents.BillingCodeType; import urn.ebay.apis.eBLBaseComponents.BillingPeriodDetailsType; import urn.ebay.apis.eBLBaseComponents.BillingPeriodType; import urn.ebay.apis.eBLBaseComponents.CreateRecurringPaymentsProfileRequestDetailsType; import urn.ebay.apis.eBLBaseComponents.CurrencyCodeType; import urn.ebay.apis.eBLBaseComponents.PaymentActionCodeType; import urn.ebay.apis.eBLBaseComponents.PaymentDetailsType; import urn.ebay.apis.eBLBaseComponents.RecurringPaymentsProfileDetailsType; import urn.ebay.apis.eBLBaseComponents.ScheduleDetailsType; import urn.ebay.apis.eBLBaseComponents.SetExpressCheckoutRequestDetailsType; import com.paypal.exception.ClientActionRequiredException; import com.paypal.exception.HttpErrorException; import com.paypal.exception.InvalidCredentialException; import com.paypal.exception.InvalidResponseDataException; import com.paypal.exception.MissingCredentialException; import com.paypal.exception.SSLConfigurationException; import com.paypal.sdk.exceptions.OAuthException; @WebServlet("/abc") public class smupaypalsuccess extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String token = request.getParameter("token"); System.out.println(token); RecurringPaymentsProfileDetailsType profileDetails = new RecurringPaymentsProfileDetailsType("2015-03-03T00:00:00:000Z"); BasicAmountType paymentAmount = new BasicAmountType(CurrencyCodeType.USD, "1.0"); BillingPeriodType period = BillingPeriodType.fromValue("Day"); int frequency = 10; BillingPeriodDetailsType paymentPeriod = new BillingPeriodDetailsType(period, frequency, paymentAmount); ScheduleDetailsType scheduleDetails = new ScheduleDetailsType(); scheduleDetails.setDescription("recurringbilling"); scheduleDetails.setPaymentPeriod(paymentPeriod); CreateRecurringPaymentsProfileRequestDetailsType createRPProfileRequestDetails = new CreateRecurringPaymentsProfileRequestDetailsType(profileDetails, scheduleDetails); createRPProfileRequestDetails.setToken(token); CreateRecurringPaymentsProfileRequestType createRPProfileRequest = new CreateRecurringPaymentsProfileRequestType(); createRPProfileRequest.setCreateRecurringPaymentsProfileRequestDetails(createRPProfileRequestDetails); CreateRecurringPaymentsProfileReq createRPPProfileReq = new CreateRecurringPaymentsProfileReq(); createRPPProfileReq.setCreateRecurringPaymentsProfileRequest(createRPProfileRequest); Map<String, String> sdkConfig = new HashMap<String, String>(); sdkConfig.put("mode", "sandbox"); sdkConfig.put("acct1.UserName", "jerrold.wee.2011-facilitator_api1.smu.edu.sg"); sdkConfig.put("acct1.Password", "SQ684XV7A2T2HVPT"); sdkConfig.put("acct1.Signature","AYdV1cYGJpnGYw2.DNLPPgAasAMIAZQjjtvqHDp9I8DnDM2USjAUINuv"); PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(sdkConfig); try { CreateRecurringPaymentsProfileResponseType createRPProfileResponse = service.createRecurringPaymentsProfile(createRPPProfileReq); response.sendRedirect("PaypalSuccess.jsp"); } catch (SSLConfigurationException | InvalidCredentialException | HttpErrorException | InvalidResponseDataException | ClientActionRequiredException | MissingCredentialException | OAuthException | InterruptedException | ParserConfigurationException | SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package Util.Email.Logging; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.Formatter; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import java.util.logging.Handler; import java.util.logging.MemoryHandler; import java.util.logging.SimpleFormatter; import java.util.logging.StreamHandler; import java.util.logging.ConsoleHandler; import java.util.logging.FileHandler ; import java.util.logging.SocketHandler; import Util.Email.PathManager; import Util.Email.Logging.EmailMessageFormatter;; /** * @author ddk * @created 14.12.18 * * 使用JDK内置Logger可以分成三个步骤来完成: * 1. 创建Logger * 2. 创建Handler,为handler指定Formmater, * 然后将Handler添加到logger中去。 * 3. 设定Level级别 * * problem: * 1 禁止向控制台输出, 因为自定义的方式没有在控制台里面出现 * 2 不管是SimpleFormatter, 还是自定义, 控制台只输出SimpleFormatter的形式(不懂!!!) * 3 同时使用System.out */ public class EmailLogger { private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd-hh.mm.ss"); // get log folder private static final String LOG_FOLDER_NAME = PathManager.getLogsResourcePath(); // define the extension private static final String LOG_FILE_RREFIX = "mail.log."; private static final String LOG_FILE_SUFFIX = ".log"; // private static String LoggerName = "Util.Email.Logging.EmailLogger"; private static Level LevelName = Level.ALL; // default private static Logger logger = null; // private static Logger logger2 = null; /** * Instance */ private static EmailLogger el; private EmailLogger() { } public static EmailLogger getEmailLoggerInstance() { if(el == null) { el = new EmailLogger(); } return el; } // public static void setLoggerName(final String loggerName) { LoggerName = loggerName; } public static String getLoggerName() { return LoggerName; } // public static void setLevelName(final Level levelName) { LevelName = levelName; } public static Level getLevelName() { return LevelName; } // private synchronized static String getLogFilePath() { StringBuffer logFilePath = new StringBuffer(); logFilePath.append(LOG_FOLDER_NAME); final String logFileDir = logFilePath.toString(); System.out.println(); System.out.println("log - logFileDir: " + logFileDir); System.out.println(); File file = new File(logFileDir); if (!file.exists()) { // make folder file.mkdir(); } // logFilePath.append(File.separatorChar); final String fileName = LOG_FILE_RREFIX + sdf.format(new Date()); logFilePath.append(fileName); logFilePath.append(LOG_FILE_SUFFIX); final String logFileName = logFilePath.toString(); System.out.println(); System.out.println("log - logFileName: " + logFileName); System.out.println(); return logFileName; } // public synchronized static Logger setLoggerHanlder(Logger logger) { return setLoggerHanlder(logger, LevelName); } public synchronized static Logger setLoggerHanlder(Logger logger, Level level) { FileHandler fileHandler = null; try { // 文件日志内容标记为可追加 fileHandler = new FileHandler(getLogFilePath(), true); //以文本的形式输出 fileHandler.setFormatter(new EmailMessageFormatter()); // simple // fileHandler.setFormatter(new SimpleFormatter()); // 为记录器添加记录处理器 logger.addHandler(fileHandler); // 设置level logger.setLevel(level); // 禁止消息处理将日志消息上传给父级处理器 logger.setUseParentHandlers(false); } catch (SecurityException e) { logger.severe(populateExceptionStackTrace(e)); } catch (IOException e) { logger.severe(populateExceptionStackTrace(e)); } return logger; } // default public synchronized static Logger getDefaultLoggerHanlder() { if(logger == null) { logger = setLoggerHanlder(Logger.getLogger(LoggerName)); } return logger; } // default public synchronized static Logger getLoggerHanlder(String LoggerName) { if(logger2 == null) { logger2 = setLoggerHanlder(Logger.getLogger(LoggerName)); } return logger2; } // ************************************************************************** private synchronized static String populateExceptionStackTrace(Exception e) { StringBuilder sb = new StringBuilder(); sb.append(e.toString()).append("\n"); for (StackTraceElement elem : e.getStackTrace()) { sb.append("\tat ").append(elem).append("\n"); } return sb.toString(); } /** * * @param msg */ public synchronized static void severe(String msg) { msg = "\n" + msg; System.out.println(msg); EmailLogger.getDefaultLoggerHanlder().severe(msg); } public synchronized static void warning(String msg) { msg = "\n" + msg; System.out.println(msg); EmailLogger.getDefaultLoggerHanlder().warning(msg); } public synchronized static void info(String msg) { msg = "\n" + msg; System.out.println(msg); EmailLogger.getDefaultLoggerHanlder().info(msg); } public synchronized static void config(String msg) { msg = "\n" + msg; System.out.println(msg); EmailLogger.getDefaultLoggerHanlder().config(msg); } public synchronized static void fine(String msg) { msg = "\n" + msg; System.out.println(msg); EmailLogger.getDefaultLoggerHanlder().fine(msg); } public synchronized static void finer(String msg) { msg = "\n" + msg; System.out.println(msg); EmailLogger.getDefaultLoggerHanlder().finer(msg); } public synchronized static void fineset(String msg) { msg = "\n" + msg; System.out.println(msg); EmailLogger.getDefaultLoggerHanlder().finest(msg); } }
package model; public class Model { public static String name = null; public String getName() { return name; } public void setName(String name) { Model.name = name; } }
package br.com.wasys.gfin.cheqfast.cliente.background; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.IBinder; import android.os.Looper; import android.os.Message; import android.os.Process; import android.support.annotation.Nullable; import android.util.Log; import android.webkit.MimeTypeMap; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import java.io.File; import java.util.ArrayList; import java.util.Date; import java.util.List; import br.com.wasys.gfin.cheqfast.cliente.R; import br.com.wasys.gfin.cheqfast.cliente.endpoint.DigitalizacaoEndpoint; import br.com.wasys.gfin.cheqfast.cliente.endpoint.Endpoint; import br.com.wasys.gfin.cheqfast.cliente.model.ArquivoModel; import br.com.wasys.gfin.cheqfast.cliente.model.DigitalizacaoModel; import br.com.wasys.gfin.cheqfast.cliente.model.ResultModel; import br.com.wasys.gfin.cheqfast.cliente.realm.Arquivo; import br.com.wasys.gfin.cheqfast.cliente.realm.Digitalizacao; import br.com.wasys.library.exception.AppException; import br.com.wasys.library.utils.TypeUtils; import io.realm.Realm; import io.realm.RealmList; import io.realm.RealmQuery; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import retrofit2.Call; /** * Created by pascke on 28/06/17. */ public class DigitalizacaoService extends Service { private Looper mLooper; private ServiceHandler mHandler; private static final String TAG = "Digitalizacao"; private static final String KEY_TIPO = DigitalizacaoService.class.getName() + ".tipo"; private static final String KEY_REFERENCIA = DigitalizacaoService.class.getName() + ".reference"; // HANDLER PARA EXECUCAO DO SERVICO private final class ServiceHandler extends Handler { public ServiceHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { try { Bundle data = msg.getData(); String name = data.getString(KEY_TIPO); String referencia = data.getString(KEY_REFERENCIA); DigitalizacaoModel.Tipo tipo = TypeUtils.parse(DigitalizacaoModel.Tipo.class, name); if (tipo != null && StringUtils.isNotBlank(referencia)) { digitalizar(tipo, referencia); } } finally { stopSelf(msg.arg1); } } } @Override public void onCreate() { HandlerThread thread = new HandlerThread(TAG, Process.THREAD_PRIORITY_BACKGROUND); thread.start(); mLooper = thread.getLooper(); mHandler = new ServiceHandler(mLooper); } // METODO PARA INICIAR O PROCESSO public static void startDigitalizacaoService(Context context, DigitalizacaoModel.Tipo tipo, String referencia) { Intent intent = new Intent(context, DigitalizacaoService.class); intent.putExtra(DigitalizacaoService.KEY_TIPO, tipo.name()); intent.putExtra(DigitalizacaoService.KEY_REFERENCIA, referencia); context.startService(intent); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } // INICIA O SERVICO EM SEGUNDO PLANO @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent != null) { String tipo = intent.getStringExtra(KEY_TIPO); String referencia = intent.getStringExtra(KEY_REFERENCIA); // OBTEM A MENSAGEM Message message = mHandler.obtainMessage(); message.arg1 = startId; // BUNDLE DE PARAMETROS Bundle data = new Bundle(); data.putString(KEY_TIPO, tipo); data.putString(KEY_REFERENCIA, referencia); message.setData(data); // ENVIA A MENSAGEM PARA SER PROCESSADA mHandler.sendMessage(message); // REINICIA CASO MORTO return START_STICKY; } return super.onStartCommand(intent, flags, startId); } private void digitalizar(DigitalizacaoModel.Tipo tipo, String referencia) { Log.d(TAG, "Iniciando digitalizacao " + referencia + "..."); DigitalizacaoModel model = find(tipo, referencia, DigitalizacaoModel.Status.ERRO, DigitalizacaoModel.Status.AGUARDANDO); if (model != null) { try { update(model.id, DigitalizacaoModel.Status.ENVIANDO); upload(tipo, referencia, model.arquivos); delete(model.id); update(model.id, DigitalizacaoModel.Status.ENVIADO); Log.d(TAG, "Sucesso na digitalizacao " + referencia + "."); } catch (Throwable throwable) { Log.e(TAG, "Erro na digitalizacao " + referencia + ".", throwable); String message = throwable.getMessage(); if (!(throwable instanceof AppException)) { Throwable rootCause = ExceptionUtils.getRootCause(throwable); if (rootCause != null) { String rootCauseMessage = rootCause.getMessage(); if (StringUtils.isNotBlank(rootCauseMessage)) { message = rootCauseMessage; } } if (StringUtils.isBlank(message)) { message = getString(R.string.msg_erro_digitalizacao); } } update(model.id, DigitalizacaoModel.Status.ERRO, message); } } Log.d(TAG, "Digitalizacao " + referencia + " finalizado."); } private void delete(Long id) { Realm realm = Realm.getDefaultInstance(); try { Log.d(TAG, "Listando registros de arquivos da digitalizacao para excluir..."); realm.beginTransaction(); Digitalizacao digitalizacao = realm.where(Digitalizacao.class) .equalTo("id", id) .findFirst(); RealmList<Arquivo> arquivos = digitalizacao.arquivos; if (CollectionUtils.isNotEmpty(arquivos)) { List<String> caminhos = new ArrayList<>(arquivos.size()); for (Arquivo arquivo : arquivos) { caminhos.add(arquivo.caminho); } Log.d(TAG, "Excluindo registros de arquivos..."); arquivos.deleteAllFromRealm(); realm.commitTransaction(); Log.d(TAG, "Sucesso na exclusao dos registros de arquivos."); Log.d(TAG, "Iniciando exclusao dos arquivos fisicos"); for (String caminho : caminhos) { File file = new File(caminho); if (file.exists()) { file.delete(); Log.d(TAG, "Arquivo '"+ caminho +"' excluido com sucesso."); } } Log.d(TAG, "Sucesso na exclusao dos arquivos fisicos."); } } catch (Throwable e) { Log.e(TAG, "Falha na exclusao dos registros da digitalizacao.", e); if (realm.isInTransaction()) { realm.cancelTransaction(); } throw e; } finally { realm.close(); } } private void update(Long id, DigitalizacaoModel.Status status) { update(id, status, null); } private void update(Long id, DigitalizacaoModel.Status status, String mensagem) { Realm realm = Realm.getDefaultInstance(); try { Log.d(TAG, "Atualizando status da digitalizacao para " + status.name() + "..."); realm.beginTransaction(); Digitalizacao digitalizacao = realm.where(Digitalizacao.class) .equalTo("id", id) .findFirst(); digitalizacao.status = status.name(); digitalizacao.mensagem = mensagem; Date data = new Date(); if (DigitalizacaoModel.Status.ENVIANDO.equals(status)) { Integer tentativas = digitalizacao.tentativas; digitalizacao.tentativas = tentativas + 1; digitalizacao.dataHoraEnvio = data; Log.d(TAG, "Tentativa da digitalizacao incrementada de " + tentativas + " para " + digitalizacao.tentativas + "."); } else if (DigitalizacaoModel.Status.ERRO.equals(status) || DigitalizacaoModel.Status.ENVIADO.equals(status)) { digitalizacao.dataHoraRetorno = data; } realm.commitTransaction(); Log.d(TAG, "Sucesso na atualizacao da digitalizacao."); } catch (Throwable e) { Log.e(TAG, "Falha na atualizacao da digitalizacao.", e); if (realm.isInTransaction()) { realm.cancelTransaction(); } throw e; } finally { realm.close(); } } private DigitalizacaoModel find(DigitalizacaoModel.Tipo tipo, String referencia, DigitalizacaoModel.Status... status) { String[] names = new String[status.length]; for (int i = 0; i < status.length; i++) { names[i] = status[i].name(); } String join = StringUtils.join(status, ", "); Log.d(TAG, "Buscando digitalizacao " + referencia + " status [" + join + "]..."); Realm realm = Realm.getDefaultInstance(); try { RealmQuery<Digitalizacao> query = realm.where(Digitalizacao.class) .equalTo("tipo", tipo.name()) .equalTo("referencia", referencia); query.beginGroup(); for (int i = 0; i < status.length; i++) { if (i > 0) { query.or(); } query.equalTo("status", status[i].name()); } query.endGroup(); Digitalizacao digitalizacao = query.findFirst(); DigitalizacaoModel digitalizacaoModel = DigitalizacaoModel.from(digitalizacao); Log.d(TAG, "Sucesso na busca da digitalizacao " + referencia + " status [" + join + "]."); return digitalizacaoModel; } catch (Throwable e) { Log.e(TAG, "Falha na busca da digitalizacao " + referencia + " status [" + join + "].", e); throw e; } finally { realm.close(); } } private void upload(DigitalizacaoModel.Tipo tipo, String referencia, List<ArquivoModel> models) throws Throwable { Log.d(TAG, "Iniciando o upload dos arquivos da digitalizacao " + referencia + "...."); if (CollectionUtils.isNotEmpty(models)) { Log.d(TAG, "Listando imagens para enviar..."); List<File> files = new ArrayList<>(models.size()); for (ArquivoModel model : models) { File file = new File(model.caminho); if (file.exists()) { files.add(file); Log.d(TAG, "Imagem '" + file.getAbsolutePath() + "' encontrado..."); } } if (CollectionUtils.isNotEmpty(files)) { Log.d(TAG, "Criando Multipart..."); MultipartBody.Builder builder = new MultipartBody.Builder(); builder.setType(MultipartBody.FORM); for (File file : files) { String name = file.getName(); String extension = MimeTypeMap.getFileExtensionFromUrl(name); String mimeTypeExtension = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); MediaType mediaType = MediaType.parse(mimeTypeExtension); RequestBody requestBody = MultipartBody.create(mediaType, file); builder.addFormDataPart("files", name, requestBody); } Log.d(TAG, "Multipart criado."); RequestBody multipartBody = builder.build(); Long id = Long.valueOf(referencia); // ID DO PROCESSO OU DOCUMENTO Long timeout = Long.valueOf(60 * 10); // 10 minutos para conexao, leitura e escrita DigitalizacaoEndpoint endpoint = Endpoint.create(DigitalizacaoEndpoint.class, timeout); Call<ResultModel> call = endpoint.digitalizar(tipo.name(), id, multipartBody); Log.d(TAG, "Enviando imagens..."); ResultModel resultModel = Endpoint.execute(call); if (!resultModel.success) { Log.e(TAG, "Falha no envio das imagens."); String messages = resultModel.getMessages(); throw new AppException(messages); } Log.d(TAG, "Sucesso no envio das imagens."); } } } }
package baguchan.earthmobsmod.client.render.layer; import baguchan.earthmobsmod.EarthMobsMod; import baguchan.earthmobsmod.client.model.ModelMoobloom; import baguchan.earthmobsmod.entity.MooBloomEntity; import net.minecraft.client.renderer.entity.IEntityRenderer; import net.minecraft.client.renderer.entity.layers.LayerRenderer; import net.minecraft.util.ResourceLocation; public class EyelidsLayer extends LayerRenderer<MooBloomEntity, ModelMoobloom<MooBloomEntity>> { private static final ResourceLocation EYELIDS_TEXTURE = new ResourceLocation(EarthMobsMod.MODID, "textures/entity/moobloom/moobloom_blink.png"); public EyelidsLayer(IEntityRenderer<MooBloomEntity, ModelMoobloom<MooBloomEntity>> render) { super(render); } @Override public void render(MooBloomEntity entityIn, float p_212842_2_, float p_212842_3_, float p_212842_4_, float p_212842_5_, float p_212842_6_, float p_212842_7_, float p_212842_8_) { if (entityIn.isSleep()) { this.bindTexture(EYELIDS_TEXTURE); this.getEntityModel().setModelAttributes(this.getEntityModel()); ((ModelMoobloom) this.getEntityModel()).render(entityIn, p_212842_2_, p_212842_3_, p_212842_5_, p_212842_6_, p_212842_7_, p_212842_8_); } } @Override public boolean shouldCombineTextures() { return true; } }
package com.pjtec.domain.service.repository; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; @Mapper public interface SampleRepository { @Select("SELECT 2") int select(); }
/* * ServiceBus inter-component communication bus * * Copyright (c) 2021- Rob Ruchte, rob@thirdpartylabs.com * * Licensed under the License specified in file LICENSE, included with the source code. * You may not use this file except in compliance with the License. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thirdpartylabs.servicebus; import com.thirdpartylabs.servicebus.commands.ChangeWombatVisibilityServiceBusCommand; import com.thirdpartylabs.servicebus.commands.ChangeWombatVisibilityServiceBusCommandExecutor; import com.thirdpartylabs.servicebus.exceptions.ServiceBusCommandExecutorNotAssignedException; import com.thirdpartylabs.servicebus.commands.CommandSubscription; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import static org.junit.jupiter.api.Assertions.*; class CommandBusTest { private CommandBus commandBus; private boolean wombatVisibility; private boolean executorToOverrideCalled; @BeforeEach void setUp() { commandBus = CommandBus.getInstance(); wombatVisibility = false; executorToOverrideCalled = false; } @AfterEach void tearDown() { commandBus = null; } @Test void assignExecutor() { // Ensure that a proper executor assignment does not raise an exception commandBus.assignExecutor(ChangeWombatVisibilityServiceBusCommand.class, this::executeChangeWombatVisibilityCommand); } @Test void issue() throws ServiceBusCommandExecutorNotAssignedException, ExecutionException, InterruptedException, TimeoutException { /* Assign our executeChangeWombatVisibilityCommand method as the handler for the ChangeWombatVisibilityServiceBusCommand class */ commandBus.assignExecutor(ChangeWombatVisibilityServiceBusCommand.class, this::executeChangeWombatVisibilityCommand); // Instantiate a command and issue it on the bus ChangeWombatVisibilityServiceBusCommand command = new ChangeWombatVisibilityServiceBusCommand(true); Future<Void> future = commandBus.issue(command); /* Block while waiting for a max of 100ms It is not necessary to do this unless you need to do something with the results of the command. You can just fire and forget with commandBus.issue(command); For these test, we need to make sure that the commands executed properly, so we will use issueBlocking from here on out. */ future.get(100, TimeUnit.MILLISECONDS); // Verify that the command handler performed the expected action assertTrue(wombatVisibility, "ServiceBusCommand execution should result in updated member variable."); } @Test void testExecutorsAreReplaced() throws ServiceBusCommandExecutorNotAssignedException { //Assign the bogus handler that should be overridden for the ChangeWombatVisibilityServiceBusCommand class commandBus.assignExecutor(ChangeWombatVisibilityServiceBusCommand.class, this::executeChangeWombatVisibilityCommand); /* Assign our executeChangeWombatVisibilityCommand method as the handler for the ChangeWombatVisibilityServiceBusCommand class */ commandBus.assignExecutor(ChangeWombatVisibilityServiceBusCommand.class, this::executeChangeWombatVisibilityCommand); // Instantiate a command and issue it on the bus ChangeWombatVisibilityServiceBusCommand command = new ChangeWombatVisibilityServiceBusCommand(true); commandBus.issueBlocking(command); // Verify that executor that was initially assigned was not called assertFalse(executorToOverrideCalled, "Overridden executor should not have been called"); // Verify that the command handler performed the expected action assertTrue(wombatVisibility, "ServiceBusCommand execution should result in updated member variable."); } @Test void issueWithConcreteExecutorClass() throws ServiceBusCommandExecutorNotAssignedException { ChangeWombatVisibilityServiceBusCommandExecutor executor = new ChangeWombatVisibilityServiceBusCommandExecutor(); /* Assign our executeChangeWombatVisibilityCommand method as the handler for the ChangeWombatVisibilityServiceBusCommand class */ commandBus.assignExecutor(ChangeWombatVisibilityServiceBusCommand.class, executor); // Instantiate a command and issue it on the bus ChangeWombatVisibilityServiceBusCommand command = new ChangeWombatVisibilityServiceBusCommand(true); commandBus.issueBlocking(command); // Verify that the command handler performed the expected action assertTrue(executor.isWombatVisible(), "ServiceBusCommand execution should result in updated member variable."); } @Test void testRemoveExecutor() { /* Assign our executeChangeWombatVisibilityCommand method as the handler for the ChangeWombatVisibilityServiceBusCommand class */ commandBus.assignExecutor(ChangeWombatVisibilityServiceBusCommand.class, this::executeChangeWombatVisibilityCommand); commandBus.removeExecutor(ChangeWombatVisibilityServiceBusCommand.class); // Instantiate a command and issue it on the bus ChangeWombatVisibilityServiceBusCommand command = new ChangeWombatVisibilityServiceBusCommand(true); assertThrows(ServiceBusCommandExecutorNotAssignedException.class, () -> { commandBus.issue(command); }, "ServiceBusCommandExecutorNotAssignedException should be thrown"); assertThrows(ServiceBusCommandExecutorNotAssignedException.class, () -> { commandBus.issueBlocking(command); }, "ServiceBusCommandExecutorNotAssignedException should be thrown"); } @Test void testSubscribe() throws ServiceBusCommandExecutorNotAssignedException { // Subscribe to commands CommandSubscription<ChangeWombatVisibilityServiceBusCommand> subscription = commandBus.subscribe(ChangeWombatVisibilityServiceBusCommand.class); // Instantiate a command and issue it on the bus ChangeWombatVisibilityServiceBusCommand command = new ChangeWombatVisibilityServiceBusCommand(true); commandBus.issueBlocking(command); ChangeWombatVisibilityServiceBusCommand receivedCommand = subscription.getQueue().poll(); // Verify that the command handler performed the expected action assertEquals(command, receivedCommand, "Command received from queue should be same as sent command"); } @Test void testSubscribeWithSubscriptionInstance() throws ServiceBusCommandExecutorNotAssignedException { // Subscribe to commands CommandSubscription<ChangeWombatVisibilityServiceBusCommand> subscription = new CommandSubscription<>(ChangeWombatVisibilityServiceBusCommand.class); commandBus.subscribe(subscription); // Instantiate a command and issue it on the bus ChangeWombatVisibilityServiceBusCommand command = new ChangeWombatVisibilityServiceBusCommand(true); commandBus.issueBlocking(command); ChangeWombatVisibilityServiceBusCommand receivedCommand = subscription.getQueue().poll(); // Verify that the command handler performed the expected action assertEquals(command, receivedCommand, "Command received from queue should be same as sent command"); } @Test void testUnsubscribe() throws ServiceBusCommandExecutorNotAssignedException { // Subscribe to commands CommandSubscription<ChangeWombatVisibilityServiceBusCommand> subscription = commandBus.subscribe(ChangeWombatVisibilityServiceBusCommand.class); // Unsubscribe commandBus.unsubscribe(subscription); // Instantiate a command and issue it on the bus ChangeWombatVisibilityServiceBusCommand command = new ChangeWombatVisibilityServiceBusCommand(true); assertThrows(ServiceBusCommandExecutorNotAssignedException.class, () -> { commandBus.issueBlocking(command); }, "ServiceBusCommandExecutorNotAssignedException should be thrown"); } /** * A rudimentary executor for our test command. Sets the value of a member variable to the value specified in the * command. * * @param command */ private void executeChangeWombatVisibilityCommand(ChangeWombatVisibilityServiceBusCommand command) { wombatVisibility = command.isVisible(); } /** * This executor should be overridden, it simply sets a flag to indicate whether or not it has been called * * @param command */ private void executeChangeWombatVisibilityCommandToOverride(ChangeWombatVisibilityServiceBusCommand command) { executorToOverrideCalled = true; } }
package org.sarge.jove.audio; import static org.lwjgl.openal.AL10.alBufferData; import static org.lwjgl.openal.AL10.alDeleteBuffers; import static org.lwjgl.openal.AL10.alGenBuffers; import org.sarge.jove.common.AbstractGraphicResource; import org.sarge.jove.util.BufferFactory; import org.sarge.lib.util.ToString; /** * OpenAL implementation. */ public class LightweightAudioTrack extends AbstractGraphicResource implements AudioTrack { @Override public void buffer( AudioData data ) { // Allocate ID final int id = alGenBuffers(); super.setResourceID( id ); // Buffer audio data alBufferData( id, data.getFormat(), BufferFactory.createByteBuffer( data.getData() ), data.getSampleRate() ); LightweightAudioSystem.checkError( "Error initialising audio buffer" ); } @Override protected void delete( int id ) { alDeleteBuffers( id ); LightweightAudioSystem.checkError( "Error releasing audio buffer" ); } @Override public String toString() { return ToString.toString( this ); } }
package com.infoworks.lab.components.db.source; import com.infoworks.lab.components.crud.components.datasource.GridDataSource; import com.it.soul.lab.sql.entity.Entity; import com.it.soul.lab.sql.query.QueryType; import com.it.soul.lab.sql.query.SQLQuery; import com.it.soul.lab.sql.query.SQLScalarQuery; import com.it.soul.lab.sql.query.SQLSelectQuery; import com.it.soul.lab.sql.query.models.Predicate; import com.vaadin.flow.data.provider.Query; import java.sql.SQLException; public class SqlDataSource<E extends Entity> extends AbstractJsqlDataSource<E> { @Override public GridDataSource addSearchFilter(String filter) { if (filter.length() <= 3) { if (filter.length() <= 0){ SQLSelectQuery query = getSearchQuery(copyWith(getQuery(), null)); executeQuery(query); return super.addSearchFilter(""); }else { return super.addSearchFilter(filter); } } Query query = copyWith(getQuery(), filter); SQLSelectQuery sqlquery = getSearchQuery(query); executeQuery(sqlquery); reloadGrid(); return this; } @Override public SQLSelectQuery getSearchQuery(Query<E, String> query) { SQLSelectQuery selectQuery = null; Predicate clause = createSearchPredicate(query); if (clause != null){ selectQuery = new SQLQuery.Builder(QueryType.SELECT) .columns() .from(E.tableName(getBeanType())) .where(clause) //.addLimit(query.getLimit(), query.getOffset()) .build(); } return selectQuery; } @Override public SQLSelectQuery getSelectQuery(Query<E, String> query) { SQLSelectQuery selectQuery = new SQLQuery.Builder(QueryType.SELECT) .columns() .from(E.tableName(getBeanType())) .addLimit(query.getLimit(), query.getOffset()) .build(); return selectQuery; } public int getRowCount(){ try { int max = getExecutor().getScalarValue(getCountQuery()); return max; } catch (SQLException e) { LOG.warning(e.getMessage()); } return getQuery().getOffset(); } protected SQLScalarQuery getCountQuery() { SQLScalarQuery scalarQuery = new SQLQuery.Builder(QueryType.COUNT) .columns() .on(E.tableName(getBeanType())) .build(); return scalarQuery; } }
package com.algorithm.trie; /** * 暴力匹配算法 */ public class BruteForce { public static boolean match(String mainStr,String pattern){ boolean flag = true; for (int i = 0; i < mainStr.length()-pattern.length()+1; i++) { in:for (int j = 0; j < pattern.length(); j++) { if(mainStr.charAt(i+j) != pattern.charAt(j)){ flag = false; break in; }else { flag = true; } if(j == pattern.length() - 1){ if(flag){ return true; } } } } return false; } public static void main(String[] args) { String a = "aaaaaaaaaaaaaab"; String b = "abc"; System.out.println(match(a,b)); } }
package br.com.logicmc.bedwars.game.addons; import org.bukkit.Bukkit; import org.bukkit.Location; public class SimpleBlock { private final int x,y,z; public SimpleBlock(Location location) { this.x = location.getBlockX(); this.y = location.getBlockY(); this.z = location.getBlockZ(); } public Location toLocation(String world){ return new Location(Bukkit.getWorld(world), x , y ,z); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SimpleBlock that = (SimpleBlock) o; return x == that.x && y == that.y && z == that.z; } @Override public int hashCode() { int hash = 3; hash = 19 * hash + x; hash = 19 * hash + y; hash = 19 * hash + z; return hash; } }
package com.amplify.apc.services.azure; import java.io.IOException; import java.net.URISyntaxException; import java.security.InvalidKeyException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.microsoft.azure.management.storage.StorageAccount; import com.microsoft.azure.storage.CloudStorageAccount; import com.microsoft.azure.storage.blob.CloudBlobClient; /** * Manages the storage blob client */ public class BlobClientProvider { private static final Logger LOGGER = LoggerFactory.getLogger(BlobClientProvider.class); /** * Validates the connection string and returns the storage blob client. The * connection string must be in the Azure connection string format. * * @return The newly created CloudBlobClient object * * @throws RuntimeException * @throws IOException * @throws URISyntaxException * @throws IllegalArgumentException * @throws InvalidKeyException */ public static CloudBlobClient getBlobClientReference(StorageAccount azureStorageAccount) throws RuntimeException, IOException, IllegalArgumentException, URISyntaxException, InvalidKeyException { String storageConnectionString = "DefaultEndpointsProtocol=https;" + "AccountName=" + azureStorageAccount.name() + ";" + "AccountKey=" + azureStorageAccount.getKeys().get(0).value(); CloudStorageAccount storageAccount; try { storageAccount = CloudStorageAccount.parse(storageConnectionString); } catch (IllegalArgumentException | URISyntaxException e) { LOGGER.error( "Connection string specifies an invalid URI [{}] - Please confirm it is in Azure connection string format", storageConnectionString); throw e; } catch (InvalidKeyException e) { LOGGER.error( "Connection string specifies an invalid KEY [{}] - Please confirm that the AccountName and AccountKey in the connection string are valid.", storageConnectionString); throw e; } return storageAccount.createCloudBlobClient(); } }
package com.qifan.movieapp; import android.net.Uri; import android.support.annotation.Nullable; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; public class MovieInfo { //Here Enter your API Key final static String API_Key = "Enter You API KEY here"; final static String BaseWebAdress = "https://api.themoviedb.org/3/movie/"; final static String API_PARAM="api_key"; final static String title="original_title"; final static String popularity_desc="popular"; final static String topRate ="top_rated"; final static String base_img_url="https://image.tmdb.org/t/p"; final static String small_img_size ="/w185"; final static String large_img_size="/w780"; @Nullable public static URL buildURL(String sort_param){ Uri builtUri=Uri.parse(BaseWebAdress+sort_param).buildUpon() .appendQueryParameter(API_PARAM,API_Key).build(); URL url=null; try{ url=new URL(builtUri.toString()); }catch (MalformedURLException e){ e.printStackTrace(); } return url; } public static String buildBaseWebAddress(int movieID, String queue){ String ID=String.valueOf(movieID); String requestWebAdress=BaseWebAdress+ID+"/"+queue; return requestWebAdress; } @Nullable public static URL buildURL1(String requestWebAdress){ Uri builtUri=Uri.parse(requestWebAdress).buildUpon() .appendQueryParameter(API_PARAM,API_Key).build(); URL url=null; try{ url=new URL(builtUri.toString()); }catch (MalformedURLException e){ e.printStackTrace(); } return url; } }
class Solution { public int rob(int[] nums) { if(nums.length == 0) return 0; if(nums.length == 1) return nums[0]; if(nums.length == 2) return Math.max(nums[0], nums[1]); int[] sum = new int[nums.length]; sum[0] = nums[0]; sum[1] = nums[1]; for(int i = 2; i < nums.length; i++){ int max = 0; for(int j = 0; j < i - 1; j++){ if(sum[j] > max) max = sum[j]; } sum[i] = nums[i] + max; } return Math.max(sum[nums.length - 1], sum[nums.length - 2]); } }
/** * */ /** * @author liuboying * */ package boying.Interface;
package View_Controller; import java.net.URL; import java.util.ResourceBundle; import Model.Product; import com.sun.tools.javac.util.Name; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.Initializable; import Model.Inventory; import Model.Part; import View_Controller.AddPartController; import View_Controller.MainFormController; import Model.InHouse; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.text.Text; import java.util.Random; import javafx.scene.control.ToggleGroup; import javafx.stage.Stage; import javafx.event.Event; /** * FXML Controller class * * @author carmenau */ public class ModifyProductController implements Initializable { Inventory inv; Product selectedProduct; int indexSelectedProduct; @FXML private ObservableList<Part> associatedParts = FXCollections.observableArrayList(); @FXML private Button cancelModify; @FXML private Button addPart; @FXML private Button removeAssociatedPart; @FXML private Button saveModifiedProduct; @FXML private TextField searchPartTextField; @FXML private TextField productId; @FXML private TextField productName; @FXML private TextField productInventory; @FXML private TextField productCost; @FXML private TextField productMaxInv; @FXML private TextField productMinInv; //configure existing associated part tableview @FXML private TableView<Part> associatedPartTableView; @FXML private TableColumn partIdColumn; @FXML private TableColumn partNameColumn; @FXML private TableColumn partStockColumn; @FXML private TableColumn partPriceColumn; @FXML private ObservableList<Product> productAssocPartsList = FXCollections.observableArrayList(); //configure all parts in inventory tableview @FXML private TableView<Part> allPartsTableView; @FXML private TableColumn allPartIdColumn; @FXML private TableColumn allPartNameColumn; @FXML private TableColumn allPartInvColumn; @FXML private TableColumn allPartPriceColumn; /** * Initializes the controller class. * * @param indexSelectedProduct the index of the array where the selected product is located * @param selectedProduct the product selected by the user * @param inv the inventory object * */ public ModifyProductController(int indexSelectedProduct, Product selectedProduct, Inventory inv) { this.inv = inv; this.selectedProduct = selectedProduct; this.indexSelectedProduct = indexSelectedProduct; this.associatedParts = selectedProduct.getAllAssociatedParts(); } /** * initializes the text fields with existing product data and tableview with part data from inventory * * */ public void initialize(URL url, ResourceBundle rb) { productId.setText(String.valueOf(this.selectedProduct.getProductID())); productName.setText(this.selectedProduct.getProductName()); productInventory.setText(String.valueOf(this.selectedProduct.getProductStock())); productCost.setText(String.valueOf(this.selectedProduct.getPrice())); productMaxInv.setText((String.valueOf(this.selectedProduct.getMaxItems()))); productMinInv.setText((String.valueOf(this.selectedProduct.getMinItems()))); associatedPartTableView.setItems(selectedProduct.getAllAssociatedParts()); partIdColumn.setCellValueFactory(new PropertyValueFactory<>("id")); partNameColumn.setCellValueFactory(new PropertyValueFactory<>("name")); partStockColumn.setCellValueFactory(new PropertyValueFactory<>("stock")); partPriceColumn.setCellValueFactory(new PropertyValueFactory<>("price")); allPartsTableView.setItems(inv.getAllParts()); allPartIdColumn.setCellValueFactory(new PropertyValueFactory<>("id")); allPartNameColumn.setCellValueFactory(new PropertyValueFactory<>("name")); allPartInvColumn.setCellValueFactory(new PropertyValueFactory<>("stock")); allPartPriceColumn.setCellValueFactory(new PropertyValueFactory<>("price")); } /** * returns an observable array list of all parts associated with the product the user selected * @param selectedProduct the product object user selected * @return the list of associated parts */ public ObservableList<Part> getProductAssocPartsList(Product selectedProduct) { String productName = selectedProduct.getProductName(); ObservableList<Part> searchResult = FXCollections.observableArrayList(); for (Product product : inv.getAllProducts()) { if (product.getProductName().contains(productName)) { for (Part part : product.getAllAssociatedParts()) { searchResult.add(part); } return searchResult; } } return null; } /** * Saves the modified product when user clicks the save button. * After saving the data, the scene will redirect to the Main Form. * * @param event redirects the user to the main form * @throws IOException */ public void saveModifiedProduct(ActionEvent event) throws IOException { int new_id = Integer.valueOf(productId.getText()); String new_name = productName.getText(); int new_stock = Integer.valueOf(productInventory.getText()); double new_price = Double.valueOf(productCost.getText()); int new_inv_min = Integer.valueOf(productMinInv.getText()); int new_inv_max = Integer.valueOf(productMaxInv.getText()); Product product = new Product(new_id, new_name, new_price, new_stock, new_inv_min, new_inv_max); for (Part part : associatedParts) { product.addAssociatedPart(part); } inv.updateProduct(indexSelectedProduct, product); changeToMainForm(event); } /** * * this method removes the selected associated part from the product object */ public void removeSelectedAssociatedPart() { Part selectedPart = associatedPartTableView.getSelectionModel().getSelectedItem(); if (associatedParts.isEmpty()) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Error"); alert.setHeaderText(null); alert.setContentText("No Part was selected"); alert.show(); return; } else if (associatedParts.contains(selectedPart)) { associatedParts.remove(selectedPart); associatedPartTableView.refresh(); } } /** * this method adds the selected part to the product object's associated parts array list * */ public void addPartToList(){ Part selectedPart = allPartsTableView.getSelectionModel().getSelectedItem(); if (selectedPart == null){ Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Error"); alert.setHeaderText(null); alert.setContentText("Please select an associated Part"); alert.show(); } else { associatedParts.add(selectedPart); associatedPartTableView.setItems(associatedParts); associatedPartTableView.refresh(); } return; } /** * when the user clicks the cancel button * this method will redirect the user to the main form. * @param event redirects the user to the main form * @throws IOException */ public void cancelModifyProduct(ActionEvent event) throws IOException { changeToMainForm(event); } /** * Sets the tableview for All Parts (inventory) * */ public void getPartsTableView() { allPartsTableView.setItems(inv.getAllParts()); } /** * Searches Part by Part Name or Part ID * */ public void searchPartTableView() { String searchPart = searchPartTextField.getText(); if (searchPartTextField.getText().isEmpty()) { getPartsTableView(); } else if (isNumeric(searchPart)){ int searchPartId = Integer.valueOf(searchPart); Part searchPartIdResults = inv.lookupPart(searchPartId); if (searchPartIdResults != null) { allPartIdColumn.setCellValueFactory(new PropertyValueFactory<>("id")); allPartNameColumn.setCellValueFactory(new PropertyValueFactory<>("name")); allPartInvColumn.setCellValueFactory(new PropertyValueFactory<>("stock")); allPartPriceColumn.setCellValueFactory(new PropertyValueFactory<>("price")); ObservableList<Part> searchResultPartList = FXCollections.observableArrayList(); searchResultPartList.add(searchPartIdResults); allPartsTableView.setItems(searchResultPartList); } else { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Search Result"); alert.setHeaderText(null); alert.setContentText("Part not found in Inventory."); alert.show(); return; } } else { ObservableList<Part> partNameSearch = inv.lookupPart(searchPart); if (partNameSearch.size() > 0) { allPartIdColumn.setCellValueFactory(new PropertyValueFactory<>("id")); allPartNameColumn.setCellValueFactory(new PropertyValueFactory<>("name")); allPartInvColumn.setCellValueFactory(new PropertyValueFactory<>("stock")); allPartPriceColumn.setCellValueFactory(new PropertyValueFactory<>("price")); allPartsTableView.setItems(partNameSearch); } else{ Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Search Result"); alert.setHeaderText(null); alert.setContentText("Part not found in Inventory."); alert.show(); return; } } allPartsTableView.refresh(); } /** * * @param event redirects user to Main Form * @throws IOException */ public void changeToMainForm(Event event) throws IOException { FXMLLoader loader = new FXMLLoader(getClass().getResource("MainForm.fxml")); MainFormController controller = new MainFormController(inv); loader.setController(controller); Parent root = loader.load(); Scene scene = new Scene(root); //get the stage information Stage window = (Stage) ((Node) event.getSource()).getScene().getWindow(); window.setScene(scene); window.show(); } /** * checks if the string is a number * @param strNum the string to be checked * @return boolean. True (if a number) or false (if not a number) */ public static boolean isNumeric(String strNum) { if (strNum == null) { return false; } try { double d = Double.parseDouble(strNum); } catch (NumberFormatException nfe) { return false; } return true; } }
package com.hcsc.enrollment.contract.docusign; import java.net.MalformedURLException; import java.net.URL; import javax.xml.namespace.QName; import javax.xml.ws.WebEndpoint; import javax.xml.ws.WebServiceClient; import javax.xml.ws.WebServiceFeature; import javax.xml.ws.Service; /** * This class was generated by Apache CXF 2.7.11 * 2016-11-18T19:08:56.440-06:00 * Generated source version: 2.7.11 * */ @WebServiceClient(name = "EnrollmentConnectService", wsdlLocation = "file:/C:/Users/i30062c/git/BA-ENROLL/com.hcsc.enrollment/com.hcsc.enrollment.facade/src/main/webapp/WEB-INF/wsdl/docusign-connect-enrollment.wsdl", targetNamespace = "http://enrollment.hcsc.com/contract/docusign") public class EnrollmentConnectService extends Service { public final static URL WSDL_LOCATION; public final static QName SERVICE = new QName("http://enrollment.hcsc.com/contract/docusign", "EnrollmentConnectService"); public final static QName EnrollmentConnectGatewayPort = new QName("http://enrollment.hcsc.com/contract/docusign", "EnrollmentConnectGatewayPort"); static { URL url = null; try { url = new URL("file:/C:/Users/i30062c/git/BA-ENROLL/com.hcsc.enrollment/com.hcsc.enrollment.facade/src/main/webapp/WEB-INF/wsdl/docusign-connect-enrollment.wsdl"); } catch (MalformedURLException e) { java.util.logging.Logger.getLogger(EnrollmentConnectService.class.getName()) .log(java.util.logging.Level.INFO, "Can not initialize the default wsdl from {0}", "file:/C:/Users/i30062c/git/BA-ENROLL/com.hcsc.enrollment/com.hcsc.enrollment.facade/src/main/webapp/WEB-INF/wsdl/docusign-connect-enrollment.wsdl"); } WSDL_LOCATION = url; } public EnrollmentConnectService(URL wsdlLocation) { super(wsdlLocation, SERVICE); } public EnrollmentConnectService(URL wsdlLocation, QName serviceName) { super(wsdlLocation, serviceName); } public EnrollmentConnectService() { super(WSDL_LOCATION, SERVICE); } /** * * @return * returns EnrollmentConnectGatewaySoap */ @WebEndpoint(name = "EnrollmentConnectGatewayPort") public EnrollmentConnectGatewaySoap getEnrollmentConnectGatewayPort() { return super.getPort(EnrollmentConnectGatewayPort, EnrollmentConnectGatewaySoap.class); } /** * * @param features * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values. * @return * returns EnrollmentConnectGatewaySoap */ @WebEndpoint(name = "EnrollmentConnectGatewayPort") public EnrollmentConnectGatewaySoap getEnrollmentConnectGatewayPort(WebServiceFeature... features) { return super.getPort(EnrollmentConnectGatewayPort, EnrollmentConnectGatewaySoap.class, features); } }
package com.spr.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; /** * Created by Catalina on 5/12/2017. */ @Entity @Table(name = "payment") public class Payment { @Id @GeneratedValue private Integer id; private String type; private Float transportMoney; private Float total; public Payment() { } public Payment(String type, Float transportMoney, Float total) { this.type = type; this.transportMoney = transportMoney; this.total = total; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Float getTransportMoney() { return transportMoney; } public void setTransportMoney(Float transportMoney) { this.transportMoney = transportMoney; } public Float getTotal() { return total; } public void setTotal(Float total) { this.total = total; } }
package com.kevin.cloud.commons.platform.dto; /** * @program: kevin-cloud-dubbo2.0 * @description: 云平台基础dto模型 * @author: kevin * @create: 2020-01-10 17:13 **/ public class CloudBaseDto { private String fallbackReason; public String getFallbackReason() { return fallbackReason; } public void setFallbackReason(String fallbackReason) { this.fallbackReason = fallbackReason; } }
package com.apssouza.mytrade.trading.forex.order; public enum OrderStatus { CREATED, FILLED, FAILED, EXECUTED, PROCESSING, CANCELLED }
package com.examples.io.oops.methodoverloading; public class Adder { public void add(int a,long b) { System.out.println("Add 1"); } public void add(long a,int b) { System.out.println("Add 2"); } }
package com.binarysprite.evemat.entity; import java.util.List; import org.seasar.doma.Dao; import org.seasar.doma.Delete; import org.seasar.doma.Insert; import org.seasar.doma.Script; import org.seasar.doma.Select; import org.seasar.doma.Update; import com.binarysprite.evemat.DB; /** */ @Dao(config = DB.class) public interface ProductBlueprintDao { /** * テーブルを作成します。 */ @Script void createTable(); /** * @param id * @return the ProductBlueprint entity */ @Select ProductBlueprint selectById(Integer id); /** * * @return */ @Select List<ProductBlueprint> selectAll(); /** * * @return */ @Select List<ProductBlueprint> selectByGroupId(int groupId); /** * * @return */ @Select List<Integer> selectProductAndMaterialIdList(); /** * @param entity * @return affected rows */ @Insert int insert(ProductBlueprint entity); /** * @param entity * @return affected rows */ @Update int update(ProductBlueprint entity); /** * @param entity * @return affected rows */ @Delete int delete(ProductBlueprint entity); }
package com.gxtc.huchuan.bean; import java.io.Serializable; /** * Created by Steven on 17/2/16. */ public class DealListBean implements Serializable{ private static final long serialVersionUID = 1L; private String id; //交易信息ID private String userId; //发布人ID private String userName; //发布人名称 private String userPic; //发布人头像 private String liuYan; //留言数量 private String tradeTypeSonId; //交易分类ID private String tradeTypeSonName;//交易分类 private String tradeType; //0:出售,1:求购(必选) private String title; private String createTime; //发布时间 private String isTop; //是否置顶(0、否;1、是) private String isfinish; //0:未完成,1,交易中,2:完成 private String read; //阅读量 private String anonymous = ""; //是否匿名 private String picUrl ; //封面图片 private String pattern ; //模式。 0、交易;1、论坛 private String workOff ; //已售数量 private String remainNum ; //剩余数量 private String isRecommendEntry ; //0、普通推荐;1、优质推荐 public String getIsRecommendEntry() { return isRecommendEntry; } public void setIsRecommendEntry(String isRecommendEntry) { this.isRecommendEntry = isRecommendEntry; } public String getWorkOff() { return workOff; } public void setWorkOff(String workOff) { this.workOff = workOff; } public String getRemainNum() { return remainNum; } public void setRemainNum(String remainNum) { this.remainNum = remainNum; } public String getPattern() { return pattern; } public void setPattern(String pattern) { this.pattern = pattern; } public String getPicUrl() { return picUrl; } public void setPicUrl(String picUrl) { this.picUrl = picUrl; } public String getRead() { return read; } public void setRead(String read) { this.read = read; } public DealListBean() { } public String getAnonymous() { return anonymous; } public void setAnonymous(String anonymous) { this.anonymous = anonymous; } public String getUserPic() { return userPic; } public void setUserPic(String userPic) { this.userPic = userPic; } public String getLiuYan() { return liuYan; } public void setLiuYan(String liuYan) { this.liuYan = liuYan; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getTradeTypeSonId() { return tradeTypeSonId; } public void setTradeTypeSonId(String tradeTypeSonId) { this.tradeTypeSonId = tradeTypeSonId; } public String getTradeTypeSonName() { return tradeTypeSonName; } public void setTradeTypeSonName(String tradeTypeSonName) { this.tradeTypeSonName = tradeTypeSonName; } public String getTradeType() { return tradeType; } public void setTradeType(String tradeType) { this.tradeType = tradeType; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getIsTop() { return isTop; } public void setIsTop(String isTop) { this.isTop = isTop; } public String getIsfinish() { return isfinish; } public void setIsfinish(String isfinish) { this.isfinish = isfinish; } }
package de.bjoern.ahlfeld.shoplytics.api; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.util.Log; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.estimote.sdk.Beacon; import de.bjoern.ahlfeld.shoplytics.ShoplyticsApplication; import de.bjoern.ahlfeld.shoplytics.models.Customer; public class ApiService { private static final String TAG = ApiService.class.getName(); /** * Tries to get the locations from the endpoints */ public static void notifyCustomer(final Beacon beacon) { final Customer customer = ShoplyticsApplication.getInstance().getCustomer(); JSONObject obj = createMessage(beacon, customer); JsonObjectRequest req = new JsonObjectRequest(Endpoints.NOTIFY_ME, obj, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject result) { } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if(error != null && error.getLocalizedMessage() != null) { Log.e(TAG, error.getLocalizedMessage() ); } else { Log.e(TAG, "Volley error "); } } }); ShoplyticsApplication.getInstance().addToRequestQueue(req); } private static JSONObject createMessage(Beacon beacon, final Customer customer) { final JSONObject obj = new JSONObject(); try { obj.put("customer_id", customer.getCustomerUUID().toString()); obj.put("uuid", beacon.getProximityUUID()); obj.put("major_value", beacon.getMajor()); obj.put("minor_value", beacon.getMinor()); } catch (JSONException e) { Log.e(TAG, e.getMessage()); } return obj; } public static void addCustomer(final Customer customer, final Context ctx) { JsonObjectRequest req = new JsonObjectRequest(Endpoints.ADD_CUSTOMER, customer.toJson(), new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject result) { Log.d(TAG, "RESULT"); customer.writeToSharedPreferences(ctx); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if(error != null && error.getLocalizedMessage() != null) { Log.e(TAG, error.getLocalizedMessage() ); } else { Log.e(TAG, "Volley error "); } } }); ShoplyticsApplication.getInstance().addToRequestQueue(req); } }
package org.patsimas.mongo.convert; import org.patsimas.mongo.domain.Movie; import org.patsimas.mongo.dto.MovieDto; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; @Component public class MovieDtoToMovieConverter implements Converter<MovieDto, Movie> { @Override public Movie convert(MovieDto movieDto) { return Movie.builder() .id(movieDto.getId()) .title(movieDto.getTitle()) .genre(movieDto.getGenre()) .director(movieDto.getDirector()) .year(movieDto.getYear()) .revenue(movieDto.getRevenue()) .build(); } }
package com.model; import java.io.Serializable; import javax.swing.JButton; public class Message implements Serializable{ private String id; private String from; private String to; private String text; private String time; private int isRead; public Message(String id, String from, String to, String text, String time, int isRead) { super(); this.id = id; this.from = from; this.to = to; this.text = text; this.time = time; this.isRead = isRead; } public String getFrom() { return from; } public String getTo() { return to; } public void setFrom(String from) { this.from = from; } public void setTo(String to) { this.to = to; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public int getIsRead() { return isRead; } public void setIsRead(int isRead) { this.isRead = isRead; } }
package com.codecool.app; import java.util.ArrayList; import java.util.List; public class Deck { private List<Card> cards; private List<Card> gamerCards = new ArrayList<Card>(); private List<Card> computerCards = new ArrayList<Card>(); public Deck(List<Card> cards){ this.cards = cards; drawCards(); } public void displayCards(){ for(Card card : cards){ System.out.println(card.getName()); } } private void drawCards(){ int counter = 0; for(Card card : cards){ if(counter % 2 == 0){ gamerCards.add(card); counter++; }else{ computerCards.add(card); counter++; } } } public List<Card> getGamerCards(){ return gamerCards; } public List<Card> getComputerCards(){ return computerCards; } }
/* * Copyright 2002-2023 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.socket.adapter.jetty; import org.eclipse.jetty.websocket.api.Session; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.WebSocketHandler; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * Tests for {@link JettyWebSocketHandlerAdapter}. * * @author Rossen Stoyanchev */ class JettyWebSocketHandlerAdapterTests { private Session session = mock(); private WebSocketHandler webSocketHandler = mock(); private JettyWebSocketSession webSocketSession = new JettyWebSocketSession(null, null); private JettyWebSocketHandlerAdapter adapter = new JettyWebSocketHandlerAdapter(this.webSocketHandler, this.webSocketSession); @BeforeEach void setup() { given(this.session.getUpgradeRequest()).willReturn(mock()); given(this.session.getUpgradeResponse()).willReturn(mock()); } @Test void onOpen() throws Exception { this.adapter.onWebSocketConnect(this.session); verify(this.webSocketHandler).afterConnectionEstablished(this.webSocketSession); } @Test void onClose() throws Exception { this.adapter.onWebSocketClose(1000, "reason"); verify(this.webSocketHandler).afterConnectionClosed(this.webSocketSession, CloseStatus.NORMAL.withReason("reason")); } @Test void onError() throws Exception { Exception exception = new Exception(); this.adapter.onWebSocketError(exception); verify(this.webSocketHandler).handleTransportError(this.webSocketSession, exception); } }
package com.yunxiaotian.common.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.yunxiaotian.common.dao.IDao; import com.yunxiaotian.common.dao.IUserDao; import com.yunxiaotian.common.dao.impl.UserDao; import com.yunxiaotian.common.entity.User; import com.yunxiaotian.common.service.IUserService; @Service("userService") public class UserService extends Manage<User, IDao<User>>implements IUserService { private IUserDao dao; @Resource(name = "userDao") public void setDao(UserDao dao) { this.dao = dao; super.dao = dao; } public User findUserById(Long id) { return dao.findUserById(id); } }
package Lithe_Data; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import Lithe_Data.Mail.MailBox; import Lithe_Data.Mail.Message; import Lithe_Data.Post.Comment; import Lithe_Data.Post.Event; import Lithe_Data.Post.Listing; import Lithe_Data.Post.Offer.Offer; import Lithe_Data.Post.Offer.OfferItem; import Lithe_Data.Post.Offer.OfferMoney; import Lithe_Data.Post.Offer.OfferOther; import Lithe_Data.Post.Post; import Lithe_Data.Post.Request; import Lithe_Data.Post.RideShare; import Lithe_Data.Post.Ticket; public class User { //USER INFORMATION //UserName for login, is unique private String UserName; private String Password; //Name for Display, not unique private String Name,LawrenceEmail,ContactEmail,PhoneNumber,SelfBio, Gender,LawrenceAddress; private String[] labels; private MailBox myMailBox; private int PermissionLevel; private Bitmap photo; private GateWay gateway; private Post[] myPost; public User(){ } public User(GateWay gateway){ myMailBox=new MailBox(); labels=new String[10]; this.gateway = gateway; this.myPost = new Post[10]; for(int i=0;i<10;i++) myPost[i]=new Post(); } public void InitializerUser(){ this.Name="anonymous"; this.PermissionLevel = 0; } public String getUserName() { return UserName; } public void setUserName(String userName) { UserName = userName; } public GateWay getGateway() { return gateway; } public void setGateway(GateWay gateway) { this.gateway = gateway; } public Bitmap getPhoto() { return photo; } public void setPhoto(Bitmap photo) { this.photo = photo; } public int getPermissionLevel() { return PermissionLevel; } public void setPermissionLevel(int permissionLevel) { PermissionLevel = permissionLevel; } public MailBox getMyMailBox() { return myMailBox; } public void setMyMailBox(MailBox myMailBox) { this.myMailBox = myMailBox; } public String[] getLabels() { return labels; } public void setLabels(String[] labels) { this.labels = labels; } public String getLawrenceAddress() { return LawrenceAddress; } public void setLawrenceAddress(String lawrenceAddress) { LawrenceAddress = lawrenceAddress; } public String getGender() { return Gender; } public void setGender(String gender) { Gender = gender; } public String getSelfBio() { return SelfBio; } public void setSelfBio(String selfBio) { SelfBio = selfBio; } public String getPhoneNumber() { return PhoneNumber; } public void setPhoneNumber(String phoneNumber) { PhoneNumber = phoneNumber; } public String getContactEmail() { return ContactEmail; } public void setContactEmail(String contactEmail) { ContactEmail = contactEmail; } public String getLawrenceEmail() { return LawrenceEmail; } public void setLawrenceEmail(String lawrenceEmail) { LawrenceEmail = lawrenceEmail; } public String getName() { return Name; } public void setName(String name) { Name = name; } public String getPassword() { return Password; } public void setPassword(String password) { Password = password; } public Post[] getMyPost() { return myPost; } public void setMyPost(Post[] myPost) { this.myPost = myPost; } public int Login(String UserName,String Password){ return gateway.Login(UserName,Password);} public int CreateAccount(String UserName,String Password,String LUEmail){return gateway.CreateAccount(UserName, Password, LUEmail);} public int ChangePassword(String NewPassword){return gateway.ChangePassword(UserName,NewPassword);} public int EditAccount(String UserName,String name,String ContactEmail, String PhoneNo, String selfBio,String Gender, String LUaddress,Bitmap Photo){return gateway.EditAccount(UserName, name, ContactEmail, PhoneNo, selfBio, Gender, LUaddress, Photo);} public void setUser(String Username){ String UserInformation=gateway.GetUser(Username); this.UserName=Username; if(!UserInformation.equals("ERROR")){ String[] UserInfo=UserInformation.split("///"); this.Password=UserInfo[0]; this.LawrenceEmail=UserInfo[1]; this.Name=UserInfo[2]; this.ContactEmail=UserInfo[3]; this.PhoneNumber=UserInfo[4]; this.SelfBio=UserInfo[5]; this.Gender=UserInfo[6]; this.LawrenceAddress=UserInfo[7]; if(UserInfo[8].equals("1")) this.PermissionLevel=1; else if(UserInfo[8].equals("2"))this.PermissionLevel=2;} } public int CreateListing(String title,String Description,String duration,String ExpectedPrice,String quantity,Bitmap Photo){ return gateway.CreateListing(title,Description,UserName,duration,ExpectedPrice,quantity,Photo);} public int CreateRequest(String title,String Description,String duration,String Price,String quantity,Bitmap Photo){ return gateway.CreateRequest(title,Description,UserName,duration,Price,quantity,Photo);} public int CreateTicket(String title,String Description,String duration,String ticket_type,String LostFoundLocation,String LostFoundTime,Bitmap Photo){ return gateway.CreateTicket(title,Description,UserName,duration,ticket_type,LostFoundLocation,LostFoundTime,Photo);} public int CreateEvent(String title,String Description,String duration,String EventTime,String EventLocation,Bitmap Photo){ return gateway.CreateEvent(title,Description,UserName,duration,EventTime,EventLocation,Photo);} public int CreateRideShare(String title,String Description,String duration,String Price,String RSTime,String RSDestination,String RSStartingLocation,String RSType,String RSDuration,Bitmap Photo){ return gateway.CreateRideShare(title,Description,UserName,duration,Price,RSTime,RSDestination,RSStartingLocation,RSType,RSDuration,Photo);} public void GetListing(){ String[] Listing=gateway.GetPost(1); String[] temp; myPost=new Post[Listing.length]; for (int i=0;i<Listing.length;i++) { myPost[i]=new Listing(); temp=Listing[Listing.length-1-i].split("///"); myPost[i].setPostID(Integer.parseInt(temp[0])); myPost[i].setPostingtime(temp[1]); myPost[i].setTitle(temp[2]); myPost[i].setDescription(temp[3]); myPost[i].setOwner(temp[4]); myPost[i].setDuration(temp[5]); myPost[i].setStatus(Integer.parseInt(temp[6])); myPost[i].setExpectedPrice(Double.parseDouble(temp[7])); myPost[i].setQuantity(Integer.parseInt(temp[8])); } } public void GetRequest(){ String[] Listing=gateway.GetPost(2); String[] temp; myPost=new Request[Listing.length]; for (int i=0;i<Listing.length;i++) { myPost[i]=new Request(); temp=Listing[Listing.length-1-i].split("///"); myPost[i].setPostID(Integer.parseInt(temp[0])); myPost[i].setPostingtime(temp[1]); myPost[i].setTitle(temp[2]); myPost[i].setDescription(temp[3]); myPost[i].setOwner(temp[4]); myPost[i].setDuration(temp[5]); myPost[i].setStatus(Integer.parseInt(temp[6])); myPost[i].setExpectedPrice(Double.parseDouble(temp[7])); myPost[i].setQuantity(Integer.parseInt(temp[8])); } } public void GetTicket(){ String[] Listing=gateway.GetPost(3); String[] temp; myPost=new Ticket[Listing.length]; for (int i=0;i<Listing.length;i++) { myPost[i]=new Ticket(); temp=Listing[Listing.length-1-i].split("///"); myPost[i].setPostID(Integer.parseInt(temp[0])); myPost[i].setPostingtime(temp[1]); myPost[i].setTitle(temp[2]); myPost[i].setDescription(temp[3]); myPost[i].setOwner(temp[4]); myPost[i].setDuration(temp[5]); myPost[i].setStatus(Integer.parseInt(temp[6])); if(temp[7].equals("lost"))myPost[i].setType(true); else myPost[i].setType(false); myPost[i].setLocation(temp[8]); myPost[i].setTime(temp[9]); } } public void GetEvent(){ // 4->post_id///posting_time///title///description///username///duration///status///EventTime///EventLocation String[] Listing=gateway.GetPost(4); String[] temp; myPost=new Event[Listing.length]; for (int i=0;i<Listing.length;i++) { myPost[i]=new Event(); temp=Listing[Listing.length-1-i].split("///"); myPost[i].setPostID(Integer.parseInt(temp[0])); myPost[i].setPostingtime(temp[1]); myPost[i].setTitle(temp[2]); myPost[i].setDescription(temp[3]); myPost[i].setOwner(temp[4]); myPost[i].setDuration(temp[5]); myPost[i].setStatus(Integer.parseInt(temp[6])); myPost[i].setTime(temp[7]); myPost[i].setLocation(temp[8]); }} //5->post_id///posting_time///title///description///username///duration///status///price////RideShareTime///RideShareDestination///RideShareStartingLocation///RideShareType///RideShareDuration public void GetRideShare() {String[] Listing=gateway.GetPost(5); String[] temp; myPost=new RideShare[Listing.length]; for (int i=0;i<Listing.length;i++) { myPost[i]=new RideShare(); temp=Listing[Listing.length-1-i].split("///"); myPost[i].setPostID(Integer.parseInt(temp[0])); myPost[i].setPostingtime(temp[1]); myPost[i].setTitle(temp[2]); myPost[i].setDescription(temp[3]); myPost[i].setOwner(temp[4]); myPost[i].setDuration(""+temp[5]); myPost[i].setStatus(Integer.parseInt(temp[6])); myPost[i].setExpectedPrice(Double.parseDouble(temp[7])); myPost[i].setTime(temp[8]); myPost[i].setDestination(temp[9]); myPost[i].setLocation(temp[10]); if(temp[11].equals("offer"))myPost[i].setType(true); else myPost[i].setType(false); myPost[i].setRSduration(temp[12]); }} //GetMyPost // 3.4%username // return: // Posttype///post_id///posting_time///title///description///username///duration////status///price///quantity///10.ticket_type///11.LostFoundLocation///12.LostFoundTime///EventTime///14.EventLocation///RideShareTime///16.RideShareDestination///RideShareStartingLocation///RideShareType///RSDuration public void GetMyPost(int gettype)//gettpye 4or 5; 4 for all my post; 5 for all my offer {String[] Listing=gateway.GetMyPost(UserName,gettype); String[] temp; int type; myPost=new Post[Listing.length]; for (int i=0;i<Listing.length;i++) { temp=Listing[Listing.length-1-i].split("///"); myPost[i]=new Listing(); type=Integer.parseInt(temp[0]); switch (type) { case 1: myPost[i]=new Listing(); myPost[i].setExpectedPrice(Double.parseDouble(temp[8])); myPost[i].setQuantity(Integer.parseInt(temp[9])); break; case 2: myPost[i]=new Request(); myPost[i].setExpectedPrice(Double.parseDouble(temp[8])); myPost[i].setQuantity(Integer.parseInt(temp[9])); break; case 3: myPost[i]=new Ticket(); if(temp[10].equals("lost"))myPost[i].setType(true); else myPost[i].setType(false); myPost[i].setLocation(temp[11]); myPost[i].setTime(temp[12]); break; case 4: myPost[i]=new Event(); myPost[i].setTime(temp[13]); myPost[i].setLocation(temp[14]); break; case 5: myPost[i]=new RideShare(); myPost[i].setExpectedPrice(Double.parseDouble(temp[8])); myPost[i].setTime(temp[15]); myPost[i].setDestination(temp[16]); myPost[i].setLocation(temp[17]); if(temp[18].equals("offer"))myPost[i].setType(true); else myPost[i].setType(false); myPost[i].setRSduration(temp[12]); break; } myPost[i].setPostID(Integer.parseInt(temp[1])); myPost[i].setPostingtime(temp[2]); myPost[i].setTitle(temp[3]); myPost[i].setDescription(temp[4]); myPost[i].setOwner(temp[5]); myPost[i].setDuration(temp[6]); myPost[i].setStatus(Integer.parseInt(temp[7])); }} public void GetPostByKeyword(String Keyword) {String[] Listing=gateway.GetPostBYKeyWord(Keyword); String[] temp; int type; myPost=new Post[Listing.length]; for (int i=0;i<Listing.length;i++) { temp=Listing[Listing.length-1-i].split("///"); myPost[i]=new Listing(); type=Integer.parseInt(temp[0]); switch (type) { case 1: myPost[i]=new Listing(); myPost[i].setExpectedPrice(Double.parseDouble(temp[8])); myPost[i].setQuantity(Integer.parseInt(temp[9])); break; case 2: myPost[i]=new Request(); myPost[i].setExpectedPrice(Double.parseDouble(temp[8])); myPost[i].setQuantity(Integer.parseInt(temp[9])); break; case 3: myPost[i]=new Ticket(); if(temp[10].equals("lost"))myPost[i].setType(true); else myPost[i].setType(false); myPost[i].setLocation(temp[11]); myPost[i].setTime(temp[12]); break; case 4: myPost[i]=new Event(); myPost[i].setTime(temp[13]); myPost[i].setLocation(temp[14]); break; case 5: myPost[i]=new RideShare(); myPost[i].setExpectedPrice(Double.parseDouble(temp[8])); myPost[i].setTime(temp[15]); myPost[i].setDestination(temp[16]); myPost[i].setLocation(temp[17]); if(temp[18].equals("offer"))myPost[i].setType(true); else myPost[i].setType(false); myPost[i].setRSduration(temp[12]); break; } myPost[i].setPostID(Integer.parseInt(temp[1])); myPost[i].setPostingtime(temp[2]); myPost[i].setTitle(temp[3]); myPost[i].setDescription(temp[4]); myPost[i].setOwner(temp[5]); myPost[i].setDuration(temp[6]); myPost[i].setStatus(Integer.parseInt(temp[7])); }} public int addContact(String ContactName){return gateway.addContact(UserName,ContactName);} public int deleteContact(String ContactName){return gateway.deleteContact(UserName, ContactName);} public void SetContactList(){myMailBox.setMyContactList(gateway.GetContact(UserName));} public void setSendMessage(){ String[] mysendMessage=gateway.GetSendMessage(UserName); String[] temp; Message[] tempM=new Message[mysendMessage.length]; for (int i=0;i<mysendMessage.length;i++) { tempM[i]=new Message(); temp=mysendMessage[i].split("///"); tempM[i].setMessageID(Integer.parseInt(temp[0])); tempM[i].setSender(temp[1]); tempM[i].setReceiver(temp[2]); tempM[i].setTitle(temp[3]); tempM[i].setContent(temp[4]); tempM[i].setSendtime(temp[5]); tempM[i].setReceiver_status(Integer.parseInt(temp[6])); tempM[i].setSender_status(Integer.parseInt(temp[7])); } myMailBox.setMySendMessage(tempM); } public void setReceiveMessage(){ String[] myReceiveMessage=gateway.GetReceivedMessage(UserName); String[] temp; Message[] tempM=new Message[myReceiveMessage.length]; for (int i=0;i<myReceiveMessage.length;i++) { tempM[i]=new Message(); temp=myReceiveMessage[i].split("///"); tempM[i].setMessageID(Integer.parseInt(temp[0])); tempM[i].setSender(temp[1]); tempM[i].setReceiver(temp[2]); tempM[i].setTitle(temp[3]); tempM[i].setContent(temp[4]); tempM[i].setSendtime(temp[5]); tempM[i].setReceiver_status(Integer.parseInt(temp[6])); tempM[i].setSender_status(Integer.parseInt(temp[7])); } myMailBox.setMyReceiveMessage(tempM); } public void ReadInboxMessage(int MessageID){gateway.EditMessageReceiverStatus(MessageID,2);} public void DeleteInboxMessage(int MessageID){gateway.EditMessageReceiverStatus(MessageID,3);} public void DeleteSendboxMessage(int MessageID){gateway.EditMessageSenderStatus(MessageID,2);} public int CheckNewMessage(){return gateway.CheckNewMessage(UserName);} public void GetOfferDetails(int PostNo){ String[] mOffer=gateway.getOfferDetails(myPost[PostNo].getPostID()); String[] temp; Offer[] tempOffer=new Offer[mOffer.length]; for (int i=0;i<mOffer.length;i++) { temp=mOffer[i].split("///"); if(temp[4].equals("1")) { tempOffer[i]=new OfferItem(); tempOffer[i].setQuantity(Integer.parseInt(temp[5])); tempOffer[i].setItem(temp[8]); }else if (temp[4].equals("2")){ tempOffer[i]=new OfferMoney(); tempOffer[i].setPrice(Double.parseDouble(temp[7])); }else if (temp[4].equals("3")) { tempOffer[i]=new OfferOther(); tempOffer[i].setOther(temp[9]); } tempOffer[i].setPostID(myPost[PostNo].getPostID()); tempOffer[i].setOfferId(Integer.parseInt(temp[0])); tempOffer[i].setOwner(temp[1]); tempOffer[i].setTime(temp[2]); tempOffer[i].setDescription(temp[3]); tempOffer[i].setType(Integer.parseInt(temp[4])); tempOffer[i].setStatus(Integer.parseInt(temp[6])); } myPost[PostNo].setOfferList(tempOffer); } public void followlabel(){} public void removelabel(){} public int SendMessage(String sender,String receiver,String title,String content){return gateway.SendAMessage(sender,receiver,title,content);} public void EditPost(){} public int DeletePost(int PostNo){return gateway.DeletePost(myPost[PostNo].getPostID());} public void GetCommentDetails(int PostNo){ String[] mComment=gateway.getCommentDetails(myPost[PostNo].getPostID()); String[] temp; Comment[] tempComment=new Comment[mComment.length]; for (int i=0;i<mComment.length;i++) { temp=mComment[i].split("///"); tempComment[i]=new Comment(); tempComment[i].setCommentID(Integer.parseInt(temp[0])); tempComment[i].setOwner(temp[1]); tempComment[i].setText(temp[2]); tempComment[i].setTime(temp[3]); } myPost[PostNo].setCommentList(tempComment); } public int createComment(int PostID,String text){return gateway.CreateComment(PostID,UserName,text);} public int deleteComment(int PostNo,int CommentNo){return gateway.DeleteComment(myPost[PostNo].getCommentList()[CommentNo].getCommentID());} public void sendSpamReport(){} public void getSpamReport(){} public void deleteSpamReport(){} public int selectOffer(int OfferID,int status){return gateway.SelectBestOffer(OfferID,status);} public int createOffer(int PostID,String description, int type, int quantity,int status, double price,String item,String other ) {return gateway.CreateOffer(PostID,UserName,description,type,quantity,status,price,item,other);} public void editOffer(){} public int deleteOffer(int PostNo,int OfferNo){return gateway.DeleteOffer(myPost[PostNo].getOfferList()[OfferNo].getOfferId());} public int setPhoto(int PostNO){ byte[] photoByte=gateway.getPostPhoto(myPost[PostNO].getPostID()); if(photoByte!=null) {if(photoByte.length>0) { photo= BitmapFactory.decodeByteArray(photoByte , 0, photoByte .length); return 1; } else{return 0;}} else return 0; } public int setUserPhoto(String Username){ byte[] photoByte=gateway.getUserPhoto(Username); if(photoByte!=null) {if(photoByte.length>0) { photo= BitmapFactory.decodeByteArray(photoByte , 0, photoByte .length); return 1; }else{return 0;}} else return 0; } public int DeleteUser(String username){ return gateway.DeleteUser(username); } }
package com.github.sd; import org.json.*; /** * User: Daniil Sosonkin * Date: 12/7/2018 3:45 PM */ public interface Endpoint { String getPath(); default Class getDatatype() { return JSONObject.class; } }
/* * Copyright 2002-2012 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.expression.spel; import org.junit.jupiter.api.Test; /** * Tests the messages and exceptions that come out for badly formed expressions * * @author Andy Clement */ public class ParserErrorMessagesTests extends AbstractExpressionTests { @Test public void testBrokenExpression01() { // will not fit into an int, needs L suffix parseAndCheckError("0xCAFEBABE", SpelMessage.NOT_AN_INTEGER); evaluate("0xCAFEBABEL", 0xCAFEBABEL, Long.class); parseAndCheckError("0xCAFEBABECAFEBABEL", SpelMessage.NOT_A_LONG); } @Test public void testBrokenExpression02() { // rogue 'G' on the end parseAndCheckError("0xB0BG", SpelMessage.MORE_INPUT, 5, "G"); } @Test public void testBrokenExpression04() { // missing right operand parseAndCheckError("true or ", SpelMessage.RIGHT_OPERAND_PROBLEM, 5); } @Test public void testBrokenExpression05() { // missing right operand parseAndCheckError("1 + ", SpelMessage.RIGHT_OPERAND_PROBLEM, 2); } @Test public void testBrokenExpression07() { // T() can only take an identifier (possibly qualified), not a literal // message ought to say identifier rather than ID parseAndCheckError("null instanceof T('a')", SpelMessage.NOT_EXPECTED_TOKEN, 18, "qualified ID","literal_string"); } }
/* * 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.reactive.config; import java.util.LinkedHashMap; import java.util.Map; import java.util.function.Predicate; import org.springframework.lang.Nullable; import org.springframework.web.util.pattern.PathPatternParser; /** * Assist with configuring {@code HandlerMapping}'s with path matching options. * * @author Rossen Stoyanchev * @author Brian Clozel * @since 5.0 */ public class PathMatchConfigurer { @Nullable private Boolean trailingSlashMatch; @Nullable private Boolean caseSensitiveMatch; @Nullable private Map<String, Predicate<Class<?>>> pathPrefixes; /** * Whether to match to URLs irrespective of their case. * If enabled a method mapped to "/users" won't match to "/Users/". * <p>The default value is {@code false}. */ public PathMatchConfigurer setUseCaseSensitiveMatch(Boolean caseSensitiveMatch) { this.caseSensitiveMatch = caseSensitiveMatch; return this; } /** * Whether to match to URLs irrespective of the presence of a trailing slash. * If enabled a method mapped to "/users" also matches to "/users/". * <p>The default was changed in 6.0 from {@code true} to {@code false} in * order to support the deprecation of the property. * @deprecated as of 6.0, see * {@link PathPatternParser#setMatchOptionalTrailingSeparator(boolean)} */ @Deprecated(since = "6.0") public PathMatchConfigurer setUseTrailingSlashMatch(Boolean trailingSlashMatch) { this.trailingSlashMatch = trailingSlashMatch; return this; } /** * Configure a path prefix to apply to matching controller methods. * <p>Prefixes are used to enrich the mappings of every {@code @RequestMapping} * method whose controller type is matched by the corresponding * {@code Predicate}. The prefix for the first matching predicate is used. * <p>Consider using {@link org.springframework.web.method.HandlerTypePredicate * HandlerTypePredicate} to group controllers. * @param prefix the path prefix to apply * @param predicate a predicate for matching controller types * @since 5.1 */ public PathMatchConfigurer addPathPrefix(String prefix, Predicate<Class<?>> predicate) { if (this.pathPrefixes == null) { this.pathPrefixes = new LinkedHashMap<>(); } this.pathPrefixes.put(prefix, predicate); return this; } @Nullable @Deprecated protected Boolean isUseTrailingSlashMatch() { return this.trailingSlashMatch; } @Nullable protected Boolean isUseCaseSensitiveMatch() { return this.caseSensitiveMatch; } @Nullable protected Map<String, Predicate<Class<?>>> getPathPrefixes() { return this.pathPrefixes; } }
package net.sf.throughglass.utils; import android.content.Context; import android.content.SharedPreferences; import android.os.Environment; public class ApplicationContext { public static Context context; public static Context getContext() { return context; } public static void setContext(Context context) { ApplicationContext.context = context; } public static SharedPreferences getDefaultSharedPreferences(final String name, final int mode) { return context.getSharedPreferences(name, mode); } public static String getContextPath() { return Environment.getDataDirectory().getAbsolutePath() + "/data/" + getPackageName(); } public static String getPackageName() { return context.getPackageName(); } }
package rpquest; import io.vertx.core.AbstractVerticle; public class ChildVerticle extends AbstractVerticle { @Override public void start() throws Exception { System.out.println("ChildVerticle.start"); getVertx().eventBus().consumer("child", message -> System.out.println("message = " + message.body())); } }
package common.util.web; import java.text.SimpleDateFormat; import java.util.Date; import common.util.reflection.ReflectionUtil; public class XDateAdapter { private static final SimpleDateFormat sdf = ReflectionUtil.getIso8601DateFormat(); public static String marshal(Date arg0) throws Exception { return sdf.format(arg0); } public static Date unmarshal(String arg0) throws Exception { return sdf.parse(arg0); } }
package com.trannguyentanthuan2903.yourfoods.my_cart.presenter; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.trannguyentanthuan2903.yourfoods.my_cart.model.MyCart; import com.trannguyentanthuan2903.yourfoods.my_cart.model.MyCartSubmitter; /** * Created by Administrator on 10/17/2017. */ public class MyCartPresenter { private DatabaseReference mData; private MyCartSubmitter submitter; public MyCartPresenter() { mData = FirebaseDatabase.getInstance().getReference(); submitter = new MyCartSubmitter(mData); } public void addProductToCart (String idUser, String idMyCart, String idStore, MyCart myCart){ submitter.addProductToCart(idUser, idMyCart, idStore, myCart); } public void deleteProductOrder (String idUser, String idMyCart, String idStore){ submitter.deleteProductOrder(idUser, idMyCart, idStore); } public void updateCountProduct (String idUser, String idMyCart, String idStore, int count){ submitter.updateCountProduct(idUser, idMyCart, idStore, count); } public void updatePrice (String idUser, String idMyCart, String idStore, float price){ submitter.updatePrice(idUser, idMyCart, idStore, price); } }
package org.sinhro.ForeignLanguageCourses.repository; import org.sinhro.ForeignLanguageCourses.domain.Group; import org.sinhro.ForeignLanguageCourses.domain.Listener; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface ListenerRepository extends JpaRepository<Listener, Integer> { List<Listener> findListenersByGroup(Group group); List<Listener> findListenersByBeginWeek(Integer beginWeek); }
package de.hofuniversity.ejbbean.bean.impl; import java.util.ArrayList; import java.util.List; import javax.ejb.Stateless; import de.hofuniversity.ejbbean.bean.TestRemote; /** * * @author Michael Jahn * */ @Stateless(name = TestRemote.MAPPED_NAME, mappedName = TestRemote.MAPPED_NAME) public class TestBean implements TestRemote { public TestBean() {} public String getExmapleString() { return "Example"; } public List<String> getExampleList() { List<String> exampleList = new ArrayList<String>(); exampleList.add("E"); exampleList.add("x"); exampleList.add("a"); exampleList.add("m"); exampleList.add("p"); exampleList.add("l"); exampleList.add("e"); return exampleList; } }
package dk.aau.oose; import org.newdawn.slick.Image; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; import org.lwjgl.util.vector.Vector2f; import dk.aau.oose.core.GameElement; import dk.aau.oose.core.GameWorld; import dk.aau.oose.Zombie; public class Plant extends GameElement { public int amountOfLives=5; // defines amount of lifes that player has got public Life[] health; // creates health of a player public int totalSuns=405; // defines total amount of suns on the screen, which is later on used to check whether all of them were collected public int points=0; // amount of points player has got public int speed = 2; // speed of a player public boolean ateCherry=false; // boolean, which is used to define whether player has eaten a cherry object or not public long timerAteCherry=0; // a number, which is used to define a number for a timmer, that represents how long has it passed since player has eaten a cherry object public float initialX; // variable, that is used later on to define initial player X coordinate public float initialY; // variable, that is used later on to define initial player Y coordinate public Maze lvl= new Maze(); // creates new maze object public Congratz congratulations=new Congratz (400, 300); // defines and creates a new "congratz" class object, that is later on used in order to show a sprite (image), whenever a player wins the game public Plant() throws SlickException { super(new Image ("assets/Plant.png")); position = new Vector2f(GameWorld.getGameContainer().getWidth()-100,GameWorld.getGameContainer().getHeight()-20); size=new Vector2f(9,9); // defines a sprite for a player and it's location and size lvl.buildMaze(); // calls for a buildMaze function that builds the maze to the stage this.initialX=position.x; // initial player position X this.initialY=position.y; // initial player position Y health= new Life[amountOfLives]; for (int i=0;i<amountOfLives;i++) { health[i]=new Life(); health[i].position.x=GameWorld.getGameContainer().getWidth()-55; health[i].position.y=100-(i*18); } for(int i=0;i<amountOfLives;i++) GameWorld.add(health[i]); // the code lines above create 5 life objects for a player. The lifes are added as gameobjects to gameworld as well as shown on the top right of the screen } @Override public void update(){ movement (); // calls for 'movement' function, that is explained later on controlPower(); // calls for 'controlpower' function, that is explained later on System.out.println(points); // prints out the amount of points to the console for (GameElement g: GameWorld.getGameObjects()) if (g.interacts(this) && g instanceof Zombie) if (fight((Zombie)g)) g.destroy(); // checks whether player interacted with a zombie, if yes - then a fight function is called for (GameElement g: GameWorld.getGameObjects()) if (g.interacts(this) && g instanceof SuperZombie) if (fightSuper((SuperZombie)g)) g.destroy(); // checks whether player interacted with a superzombie, if yes - then a superfight function is called if (this.amountOfLives<0) {this.destroy(); ; // if amount of lifes is gets to 0 - the game ends and a player object is destroyed } if (this.totalSuns==0) { lvl.updateMaze(); GameWorld.add(congratulations); // checks whether player has eaten all of the 'sun' objects on the screen. If yes - then the game should end, thus a congratulations screen is being called and added to the screen. } } private boolean isInteracting(Class c){ for (GameElement g: GameWorld.getGameObjects()) if (g != this && c.isInstance(g) && g.interacts(this)) return true; return false; // a function that is used to check whether object A is interacting with object B, and returns true/false based on that } public void movement () { if (GameWorld.getGameContainer().getInput().isKeyDown(Input.KEY_LEFT)) if (position.x > 0) {position.x-=speed; if (isInteracting(Wall.class)) position.x+=speed; } if (GameWorld.getGameContainer().getInput().isKeyDown(Input.KEY_RIGHT)) if (position.x< GameWorld.getGameContainer().getWidth() && !isInteracting(Wall.class)) {position.x+=speed; if (isInteracting(Wall.class)) position.x-=speed; } if (GameWorld.getGameContainer().getInput().isKeyDown(Input.KEY_UP)) if (position.y> 0 && !isInteracting(Wall.class)) {position.y-=speed; if (isInteracting(Wall.class)) position.y+=speed; } if (GameWorld.getGameContainer().getInput().isKeyDown(Input.KEY_DOWN)) if (position.y < GameWorld.getGameContainer().getHeight() && !isInteracting(Wall.class) ) {position.y+=speed; if (isInteracting(Wall.class)) position.y-=speed; } // the function above checks whether player would interact with a wall or not if he would move either left/right/up/down (depends on what he has chosen). If he would not interact with a wall - a player location is changed. } public boolean fight(Zombie zombie){ if (ateCherry==true) { points+=zombie.fightPoints; return true; // if player is under effects of cherry object and interacts with zombie - he receives zombie.fightpoints amount of points for that that is added to his points pool } else { this.health[amountOfLives-1].lifeChanged(amountOfLives-1, health); this.amountOfLives--; this.position.x=initialX; this.position.y=initialY; // if player is not under effects of cherry object - when he interacts with zombie, his life is decreased by one and position resets to starting position } return false; } public boolean fightSuper(SuperZombie superzombie){ if (ateCherry==true) { points+=superzombie.fightPoints; return true; // if player is under effects of cherry object and interacts with SUPERzombie - he receives SUPERzombie.fightpoints amount of points for that that is added to his points pool } else { this.health[amountOfLives-1].lifeChanged(amountOfLives-1, health); this.amountOfLives--; this.position.x=initialX; this.position.y=initialY; // if player is not under effects of cherry object - when he interacts with SUPERzombie, his life is decreased by one and position resets to starting position } return false; } public void controlPower (){ if (ateCherry==true ) if (System.currentTimeMillis()-timerAteCherry>10000) {ateCherry=false; } } // the function above checks whether the timer after eating a cherry object has expired or not, and based on that defines whether player ate cherry recently enough or not }
/* * 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 DAL; import DTO.DTO_Quyen; import GUI.Assignment; import java.sql.ResultSet; /** * * @author Asus */ public class DAL_Quyen { public static int ThemQuyen(DTO_Quyen item) { String CauTruyVan = "insert into QUYEN (TENQUYEN,MOTA) values (N'"+item.getTenQuyen()+"',N'"+item.getMoTa()+"')"; int result = Assignment.connection.ExcuteNonQuery(CauTruyVan); return result; } public static int XoaQuyen(int item) { String CauTruyVan ="delete QUYEN where MaQuyen = "+item+""; int result = Assignment.connection.ExcuteNonQuery(CauTruyVan); return result; } public static int SuaQuyen(DTO_Quyen item) { String CauTruyVan ="update QUYEN set TENQUYEN=N'"+item.getTenQuyen()+"',MOTA='"+item.getMoTa()+"' where MAQUYEN="+item.getMaQuyen()+""; int result = Assignment.connection.ExcuteNonQuery(CauTruyVan); return result; } public static ResultSet GetALL_Quyen() { String query = "select * from QUYEN"; return Assignment.connection.ExcuteQuerySelect(query); } }
package com.trinary.security; import java.io.IOException; import java.util.Collections; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; import org.springframework.web.context.support.SpringBeanAutowiringSupport; import org.springframework.web.filter.GenericFilterBean; import com.trinary.security.auth.TokenAuthentication; import com.trinary.security.entities.User; import com.trinary.security.exceptions.TokenExpiredException; import com.trinary.security.exceptions.TokenInvalidException; import com.trinary.security.token.Token; import com.trinary.security.token.TokenManager; @Component public class TokenBasedAuthenticationFilter extends GenericFilterBean { @Autowired private AuthenticationManager authenticationManager; @Autowired private TokenManager manager; private Authentication emptyAuth = createEmptyAuthentication(); Logger LOGGER = Logger.getLogger(TokenBasedAuthenticationFilter.class.getSimpleName()); @PostConstruct public void init() { SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); } public TokenBasedAuthenticationFilter() {} public TokenBasedAuthenticationFilter(AuthenticationManager authenticationManager, TokenManager tokenManager) { this.authenticationManager = authenticationManager; this.manager = tokenManager; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain next) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; String authHeader = httpRequest.getHeader("Authorization"); if (authHeader == null) { SecurityContextHolder.getContext().setAuthentication(emptyAuth); next.doFilter(request, response); return; } String[] authHeaderParts = authHeader.split(" "); if (!authHeaderParts[0].trim().equals("Bearer")) { SecurityContextHolder.getContext().setAuthentication(emptyAuth); next.doFilter(request, response); return; } LOGGER.warning("TOKEN MANAGER: " + manager); LOGGER.warning("AUTH MANAGER: " + authenticationManager); Token token = null; try { token = manager.authenticateToken(authHeaderParts[1]); } catch (TokenInvalidException | TokenExpiredException e) { e.printStackTrace(); } if (token != null) { Authentication auth = authenticationManager.authenticate(new TokenAuthentication(token)); SecurityContextHolder.getContext().setAuthentication(auth); next.doFilter(request, response); return; } else { SecurityContextHolder.getContext().setAuthentication(emptyAuth); next.doFilter(request, response); return; } } public Authentication createEmptyAuthentication() { User user = new User(); user.setUsername("anonymous"); user.setRoles(Collections.emptyList()); user.setPassword(""); TokenAuthentication auth = new TokenAuthentication(""); auth.setAuthenticated(false); auth.setPrincipal(user); return auth; } }
package com.matterickson.sidescroller.item; import java.awt.Point; import com.matterickson.sidescroller.GameObject; import com.matterickson.sidescroller.Player; import com.matterickson.sidescroller.World; public class ItemCoin extends Item { public ItemCoin(int x, int y) { super(x, y, 35, 35, "res/coin_gold.png", 35, 35); this.applyGravity = false; } @Override protected Point rightSideHit(GameObject o, Point speed){ if(o instanceof Player){ this.isDead = true; } return speed; } @Override protected Point leftSideHit(GameObject o, Point speed){ if(o instanceof Player){ this.isDead = true; } return speed; } @Override protected Point topSideHit(GameObject o, Point speed){ if(o instanceof Player){ this.isDead = true; } return speed; } @Override protected Point bottomSideHit(GameObject o, Point speed){ if(o instanceof Player){ this.isDead = true; } return speed; } @Override public void update(World w){ if(this.isDead){ w.getGameObjects().remove(this); w.getItems().remove(this); w.getPlayer().addCoin(); } } }
package com.example.money.dto.request; import io.swagger.annotations.ApiModelProperty; import lombok.Data; @Data public class RequestMoneyDto { @ApiModelProperty(value = "sender", required = true) private String sender; @ApiModelProperty(value = "recipient", required = true) private String recipient; @ApiModelProperty(value = "amount", required = true) private Long amount; }