text
stringlengths
10
2.72M
package com.trump.auction.goods.service.impl; import com.alibaba.fastjson.JSON; import com.cf.common.util.mapping.BeanMapper; import com.cf.common.utils.JsonResult; import com.trump.auction.goods.dao.ProductInfoDao; import com.trump.auction.goods.dao.ProductInventoryLogDao; import com.trump.auction.goods.dao.ProductManageDao; import com.trump.auction.goods.dao.ProductPicDao; import com.trump.auction.goods.domain.ProductInfo; import com.trump.auction.goods.domain.ProductInventoryLog; import com.trump.auction.goods.domain.ProductManage; import com.trump.auction.goods.domain.ProductPic; import com.trump.auction.goods.enums.ProductStatusEnum; import com.trump.auction.goods.enums.ResultCode; import com.trump.auction.goods.enums.ResultEnum; import com.trump.auction.goods.model.ProductInfoModel; import com.trump.auction.goods.model.ProductInventoryLogModel; import com.trump.auction.goods.model.ProductPicModel; import com.trump.auction.goods.service.ProductInfoService; import com.trump.auction.goods.service.ProductInventoryLogService; import com.trump.auction.goods.util.DateUtil; import com.trump.auction.goods.vo.ProductManageVo; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.*; /** * @description: 商品 * @author: zhangqingqiang * @date: 2017-12-21 14:31 **/ @Service @Slf4j public class ProductInfoServiceImpl implements ProductInfoService{ @Autowired private ProductInfoDao productInfoDao; @Autowired private BeanMapper beanMapper; @Autowired private ProductManageDao productManageDao; @Autowired private ProductInventoryLogService productInventoryLogService; @Autowired private ProductPicDao productPicDao; @Override public JsonResult saveProducts(List<ProductInfo> products) { if (CollectionUtils.isEmpty(products)){ return new JsonResult(ResultEnum.NULL_PRODUCT.getCode(), ResultEnum.NULL_PRODUCT.getDesc()); } JsonResult jsonResult = new JsonResult(); List<Integer> failProductIds = new ArrayList<>(); int result = 0; for (ProductInfo product : products){ ProductInfo productInfo = productInfoDao.getProductByProductId(product.getProductId()); if (null!=productInfo){ failProductIds.add(productInfo.getProductId()); continue; } result += productInfoDao.insert(product); } jsonResult.setCode("0000"); jsonResult.setData(result); jsonResult.setMsg("保存成功"+result+"条数据,保存失败"+failProductIds.size()+"条,保存失败商品ID:"+failProductIds); return jsonResult; } /** * 商品添加 * @param productInfoModel * @return */ @Override @Transactional(propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class) public JsonResult saveProduct(ProductInfoModel productInfoModel) throws Exception { log.info("saveProduct param :" + JSON.toJSONString(productInfoModel)); JsonResult jsonResult = new JsonResult(); //必传参数 if(productInfoModel == null || StringUtils.isBlank(productInfoModel.getProductName())|| StringUtils.isBlank(productInfoModel.getProductTitle()) || productInfoModel.getProductNum() == null || productInfoModel.getProductAmount() == null || CollectionUtils.isEmpty(productInfoModel.getPics())){ jsonResult.setCode(ResultCode.PARAM_MISSING.getCode()); jsonResult.setMsg( ResultCode.PARAM_MISSING.getMsg()); return jsonResult; } //判断商品是否存在 ProductInfo productInfo = productInfoDao.getProductByProductId(productInfoModel.getProductId()); if (null!=productInfo){ jsonResult.setCode(ResultCode.OBJECT_IS_EXIST.getCode()); jsonResult.setMsg( ResultCode.OBJECT_IS_EXIST.getMsg()); return jsonResult; } //判断商品状态 ,如果已上架不能修改 ProductManage manage = productManageDao.selectByProductId(productInfoModel.getProductId()); if(manage != null && manage.getStatus().equals(1)){ jsonResult.setCode(ResultCode.PRODUCT_GROUNDING.getCode()); jsonResult.setMsg( ResultCode.PRODUCT_GROUNDING.getMsg()); return jsonResult; } productInfo = new ProductInfo(); beanMapper.map(productInfoModel,productInfo); productInfo.setProductStatus(0); productInfo.setCreateTime(DateUtil.getCurrentDate()); int result = productInfoDao.insertSelective(productInfo); if (result <= 0){ jsonResult.setCode(ResultCode.FAIL.getCode()); jsonResult.setMsg(ResultCode.FAIL.getMsg()); return jsonResult; }else{ //库存添加 ProductInventoryLogModel productInventoryLog = new ProductInventoryLogModel(); productInventoryLog.setProductId(productInfo.getId()); productInventoryLog.setUserId(productInfoModel.getUserId()); productInventoryLog.setUserIp(productInfoModel.getUserIp()); productInventoryLog.setProductNum(productInfoModel.getProductNum()); productInventoryLog.setCreateTime(DateUtil.getCurrentDate()); //添加库存 int stockResult = productInventoryLogService.addStock(productInventoryLog); if(stockResult <= 0){ throw new Exception("库存添加失败"); } //商品图片添加 productInfoModel.setId(productInfo.getId()); List<ProductPic> pics = getPics(productInfoModel); if(CollectionUtils.isNotEmpty(pics)) { productPicDao.batchInsert(pics); } } jsonResult.setCode(ResultEnum.SAVE_SUCCESS.getCode()); jsonResult.setData(productInfo.getProductId()); jsonResult.setMsg(ResultEnum.SAVE_SUCCESS.getDesc()); return jsonResult; } /** * 商品修改 * @param productInfoModel * @return */ @Override @Transactional(propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class) public JsonResult updateProduct(ProductInfoModel productInfoModel) throws Exception { log.info("updateProduct param :" + JSON.toJSONString(productInfoModel)); JsonResult jsonResult = new JsonResult(); if(productInfoModel.getProductId() == null){ jsonResult.setCode(ResultCode.PARAM_MISSING.getCode()); jsonResult.setMsg( ResultCode.PARAM_MISSING.getMsg()); return jsonResult; } ProductInfo productInfo = productInfoDao.getProductByProductId(productInfoModel.getProductId()); if (null==productInfo){ jsonResult.setCode(ResultCode.OBJECT_ISNOT_EXIST.getCode()); jsonResult.setMsg(ResultCode.OBJECT_ISNOT_EXIST.getMsg()); return jsonResult; } productInfoModel.setId(productInfo.getId()); productInfoModel.setUpdateTime(DateUtil.getCurrentDate()); beanMapper.map(productInfoModel,productInfo); int result = productInfoDao.updateByPrimaryKeySelective(beanMapper.map(productInfoModel,ProductInfo.class)); //库存修改 if(result > 0) { if (productInfoModel.getProductNum() != null) { //库存修改 ProductInventoryLogModel productInventoryLog = new ProductInventoryLogModel(); productInventoryLog.setProductId(productInfo.getId()); productInventoryLog.setUserId(productInfoModel.getUserId()); productInventoryLog.setUserIp(productInfoModel.getUserIp()); productInventoryLog.setProductNum(productInfoModel.getProductNum()); //修改库存 int updateStockResult = productInventoryLogService.updateStock(productInventoryLog); if(updateStockResult <= 0){ throw new Exception("库存修改失败"); } } if(CollectionUtils.isNotEmpty(productInfoModel.getPics())){ //先删除后添加 Map<String,Object> map = new HashMap<>(); //map.put("picType",0); map.put("productId",productInfo.getId()); productPicDao.deleteByProductIdOrType(map); //商品图片添加 productInfoModel.setId(productInfo.getId()); List<ProductPic> pics = getPics(productInfoModel); if(CollectionUtils.isNotEmpty(pics)) { productPicDao.batchInsert(pics); } } } if (result==0){ jsonResult.setCode(ResultCode.FAIL.getCode()); jsonResult.setMsg( ResultCode.FAIL.getMsg()); return jsonResult; } jsonResult.setCode(ResultCode.SUCCESS.getCode()); jsonResult.setData(productInfoModel.getProductId()); jsonResult.setMsg(ResultCode.SUCCESS.getMsg()); return jsonResult; } /** * 获取需要更新的图片 * @param productInfoModel * @return */ private List<ProductPic> getUpdatePics(ProductInfoModel productInfoModel) { List<ProductPic> pics = new ArrayList<>(); ProductPic pic = null; for (ProductPicModel model:productInfoModel.getPics() ) { pic = new ProductPic(); beanMapper.map(model,pic); pic.setCreateTime(DateUtil.getCurrentDate()); pic.setProductId(productInfoModel.getId()); pic.setPicType(model.getPicType()); pics.add(pic); } return pics; } private List<ProductPic> getPics(ProductInfoModel productInfoModel) { List<ProductPic> pics = new ArrayList<>(); ProductPic pic = null; for (ProductPicModel model:productInfoModel.getPics() ) { pic = new ProductPic(); beanMapper.map(model,pic); pic.setCreateTime(DateUtil.getCurrentDate()); pic.setProductId(productInfoModel.getId()); pics.add(pic); } return pics; } @Override public JsonResult updateStatus(Integer productId){ int result = productInfoDao.updateStatus(productId, ProductStatusEnum.DELETED.getCode()); if (result==0){ return new JsonResult(ResultEnum.DELETE_PRODUCT_FAIL.getCode(), "删除失败,productId:"+productId); } return new JsonResult(ResultEnum.DELETE_PRODUCT_SUCCESS.getCode(), "删除成功,productId:"+productId); } @Override public ProductInfoModel getProductByProductId(Integer productId) { ProductInfo productInfo = productInfoDao.getProductByProductId(productId); return beanMapper.map(productInfo,ProductInfoModel.class); } @Override public JsonResult updateCollectCount(Integer productId, int collectCount) { try { int result = productInfoDao.updateCollectCount(productId, collectCount); if (result==0){ return new JsonResult(ResultEnum.UPDATE_PRODUCT_FAIL.getCode(), "修改收藏数量失败,productId:"+productId); } } catch (Exception e) { log.error("updateCollectCount error. product:{},error:{}",productId,e); return new JsonResult(ResultEnum.UPDATE_PRODUCT_FAIL.getCode(), "修改收藏数量失败,productId:"+productId); } return new JsonResult(ResultEnum.UPDATE_PRODUCT_SUCCESS.getCode(), "修改收藏数量成功,productId:"+productId); } }
package co.sblock.machines.type; import java.util.ArrayList; import java.util.UUID; import co.sblock.Sblock; import co.sblock.captcha.Captcha; import co.sblock.machines.MachineInventoryTracker; import co.sblock.machines.Machines; import co.sblock.machines.utilities.Direction; import co.sblock.machines.utilities.Shape; import co.sblock.machines.utilities.Shape.MaterialDataValue; import co.sblock.utilities.InventoryUtils; import org.apache.commons.lang3.tuple.ImmutableTriple; import org.apache.commons.lang3.tuple.Triple; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; import org.bukkit.event.block.Action; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryDragEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.util.Vector; import net.md_5.bungee.api.ChatColor; /** * Simulate a Sburb Punch Designix in Minecraft. * * @author Jikoo */ public class PunchDesignix extends Machine { /* The ItemStacks used to create usage help trade offers */ private static Triple<ItemStack, ItemStack, ItemStack> exampleRecipes; private final ItemStack drop; private final Captcha captcha; private final MachineInventoryTracker tracker; public PunchDesignix(Sblock plugin, Machines machines) { super(plugin, machines, new Shape(), "Punch Designix"); this.captcha = plugin.getModule(Captcha.class); tracker = machines.getInventoryTracker(); Shape shape = getShape(); shape.setVectorData(new Vector(0, 0, 0), shape.new MaterialDataValue(Material.QUARTZ_STAIRS, Direction.WEST, "upperstair")); shape.setVectorData(new Vector(1, 0, 0), shape.new MaterialDataValue(Material.QUARTZ_STAIRS, Direction.EAST, "upperstair")); MaterialDataValue m = shape.new MaterialDataValue(Material.QUARTZ_STAIRS, Direction.NORTH, "upperstair"); shape.setVectorData(new Vector(0, 1, 0), m); shape.setVectorData(new Vector(1, 1, 0), m); m = shape.new MaterialDataValue(Material.STEP, (byte) 15); shape.setVectorData(new Vector(0, 0, -1), m); shape.setVectorData(new Vector(1, 0, -1), m); m = shape.new MaterialDataValue(Material.CARPET, (byte) 8); shape.setVectorData(new Vector(0, 1, -1), m); shape.setVectorData(new Vector(1, 1, -1), m); drop = new ItemStack(Material.QUARTZ_STAIRS); ItemMeta meta = drop.getItemMeta(); meta.setDisplayName(ChatColor.WHITE + "Punch Designix"); drop.setItemMeta(meta); createExampleRecipes(); } @Override public boolean handleInteract(PlayerInteractEvent event, ConfigurationSection storage) { if (super.handleInteract(event, storage)) { return true; } if (event.getAction() != Action.RIGHT_CLICK_BLOCK) { return true; } if (event.getPlayer().isSneaking()) { return false; } openInventory(event.getPlayer(), storage); return true; } @Override @SuppressWarnings("deprecation") public boolean handleClick(InventoryClickEvent event, ConfigurationSection storage) { if (event.getSlot() != 2 || event.getRawSlot() != event.getView().convertSlot(event.getRawSlot())) { updateInventory(event.getWhoClicked().getUniqueId(), false); return false; } if (event.getCurrentItem() == null || event.getCurrentItem().getType() == Material.AIR) { updateInventory(event.getWhoClicked().getUniqueId(), false); return true; } // Clicking an item in result slot Inventory merchant = event.getInventory(); // Possible results: // 1) slot 0 is Captcha, slot 1 is null. Result: slot 2 = punch 0. 0, 1 consumed. // 2) slot 0 is Punch, slot 1 is Captcha. Result: slot 2 = copy 0. 1 consumed. // 3) slot 0 is Punch, slot 1 is Punch. Result: slot 2 = combine 0, 1. 0, 1 consumed. ItemStack result = captcha.createCombinedPunch(merchant.getItem(0), merchant.getItem(1)); if (result == null) { updateInventory(event.getWhoClicked().getUniqueId(), false); return true; } int crafts = 1; boolean copyPunch = Captcha.isCaptcha(merchant.getItem(1)); boolean updateInputSlot0 = false; // Clicking a villager result slot with vanilla client treats right clicks as left clicks. if (event.getClick().name().contains("SHIFT")) { // Shift-clicks are craft-max attempts. if (Captcha.isPunch(merchant.getItem(0)) && copyPunch) { crafts = merchant.getItem(1).getAmount(); } else { crafts = getMaximumCrafts(merchant.getItem(0), merchant.getItem(1)); } result.setAmount(crafts); // Decrement number of crafts by number of items that failed to be added // This is only works because the result will always be a single item that stacks to 64 crafts -= InventoryUtils.getAddFailures(event.getWhoClicked().getInventory().addItem(result)); } else if (event.getCursor() == null || event.getCursor().getType() == Material.AIR || event.getCursor().isSimilar(result) && event.getCursor().getAmount() < event.getCursor().getType().getMaxStackSize()) { // Set cursor to single stack result.setAmount(event.getCursor() == null || event.getCursor().getType() == Material.AIR ? 1 : event.getCursor().getAmount() + 1); event.setCursor(result); updateInputSlot0 = copyPunch; } else { // Invalid craft, cancel and update result updateInventory(event.getWhoClicked().getUniqueId(), false); return true; } // This will be recalculated in the synchronous delayed inventory update task. event.setCurrentItem(InventoryUtils.decrement(result, crafts)); // If second item is a captcha, first item is a punchcard being copied. Do not decrement. if (!copyPunch) { merchant.setItem(0, InventoryUtils.decrement(merchant.getItem(0), crafts)); } // In all cases (combine, punch single, copy punch) if second is not null it decrements. merchant.setItem(1, InventoryUtils.decrement(merchant.getItem(1), crafts)); updateInventory(event.getWhoClicked().getUniqueId(), updateInputSlot0); return true; } @Override public boolean handleClick(InventoryDragEvent event, ConfigurationSection storage) { updateInventory(event.getWhoClicked().getUniqueId(), false); return false; } /** * Calculates the maximum number of items that can be crafted with the given ItemStacks. * * @param slot1 the first ItemStack * @param slot2 the second ItemStack * * @return the least of the two, or, if slot2 is null, the amount in slot1 */ private int getMaximumCrafts(ItemStack slot1, ItemStack slot2) { return slot2 == null || slot2.getType() == Material.AIR ? slot1.getAmount() : Math.min(slot1.getAmount(), slot2.getAmount()); } /** * Calculate result slot and update inventory on a delay (post-event completion) * * @param name the name of the player who is using the Punch Designix */ public void updateInventory(final UUID id, final boolean updateInputSlot0) { Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), new Runnable() { @Override public void run() { // Must re-obtain player or update doesn't seem to happen Player player = Bukkit.getPlayer(id); if (player == null || !tracker.hasMachineOpen(player)) { // Player has logged out or closed inventory. Inventories are per-player, ignore. return; } if (updateInputSlot0) { InventoryUtils.updateWindowSlot(player, 0); } Inventory open = player.getOpenInventory().getTopInventory(); // TODO this seems to fail to update properly when punch in slot 0 is re-punched ItemStack result = captcha.createCombinedPunch(open.getItem(0), open.getItem(1)); open.setItem(2, result); ItemStack inputSlot1 = open.getItem(0); if (inputSlot1 != null) { inputSlot1 = inputSlot1.clone(); inputSlot1.setAmount(1); } ItemStack inputSlot2 = open.getItem(1); if (inputSlot2 != null) { inputSlot2 = inputSlot2.clone(); inputSlot2.setAmount(1); } InventoryUtils.updateVillagerTrades(player, getExampleRecipes(), new ImmutableTriple<>(inputSlot1, inputSlot2, result)); InventoryUtils.updateWindowSlot(player, 2); } }); } /** * Open a PunchDesignix inventory for a Player. * * @param player the Player */ public void openInventory(Player player, ConfigurationSection storage) { tracker.openVillagerInventory(player, this, getKey(storage)); InventoryUtils.updateVillagerTrades(player, getExampleRecipes()); } @Override public ItemStack getUniqueDrop() { return drop; } /** * Singleton for getting usage help ItemStacks. */ public static Triple<ItemStack, ItemStack, ItemStack> getExampleRecipes() { if (exampleRecipes == null) { exampleRecipes = createExampleRecipes(); } return exampleRecipes; } /** * Creates the ItemStacks used in displaying usage help. * * @return */ private static Triple<ItemStack, ItemStack, ItemStack> createExampleRecipes() { ItemStack is1 = new ItemStack(Material.BOOK); ItemMeta im = is1.getItemMeta(); im.setDisplayName(ChatColor.GOLD + "Slot 1 options:"); ArrayList<String> lore = new ArrayList<>(); lore.add(ChatColor.GOLD + "1) Captchacard " + ChatColor.DARK_RED + "(consumed)"); lore.add(ChatColor.GOLD + "2) Punchcard"); lore.add(ChatColor.GOLD + "3) Punchcard " + ChatColor.DARK_RED + "(consumed)"); im.setLore(lore); is1.setItemMeta(im); ItemStack is2 = new ItemStack(Material.BOOK); im = is2.getItemMeta(); im.setDisplayName(ChatColor.GOLD + "Slot 2 options:"); lore = new ArrayList<>(); lore.add(ChatColor.GOLD + "1) Empty"); lore.add(ChatColor.GOLD + "2) Captchacard " + ChatColor.DARK_RED + "(consumed)"); lore.add(ChatColor.GOLD + "3) Punchcard " + ChatColor.DARK_RED + "(consumed)"); im.setLore(lore); is2.setItemMeta(im); ItemStack is3 = new ItemStack(Material.BOOK); im = is3.getItemMeta(); im.setDisplayName(ChatColor.GOLD + "Punchcard Result:"); lore = new ArrayList<>(); lore.add(ChatColor.GOLD + "1) Card 1 punched"); lore.add(ChatColor.GOLD + "2) Copy of card 1"); lore.add(ChatColor.GOLD + "3) Card 1 and lore of 2"); im.setLore(lore); is3.setItemMeta(im); return new ImmutableTriple<>(is1, is2, is3); } }
/** * @author DengYouming * @since 2016-8-16 下午6:30:02 */ package org.hpin.webservice.service; import java.io.File; import java.util.Calendar; import java.util.Date; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.hpin.webservice.bean.*; import org.hpin.webservice.dao.ErpReportdetailPDFContentDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; /** * @author DengYouming * @since 2016-8-16 下午6:30:02 */ @Service(value = "org.hpin.webservice.service.ErpReportdetailPDFContentService") @Transactional() public class ErpReportdetailPDFContentService { Logger dealLog = Logger.getLogger("dealReport"); @Autowired private ErpReportdetailPDFContentDao dao; @Autowired private ErpPrintTaskContentService contentService; /** * * @param pdfContentList * @throws Exception * @author DengYouming * @since 2016-8-30 下午8:47:36 */ public void save(List<ErpReportdetailPDFContent> pdfContentList) throws Exception{ dao.save(pdfContentList); } /** * * @param obj * @throws Exception * @author DengYouming * @since 2016-10-10 下午12:06:17 */ public void saveEntity(ErpReportdetailPDFContent obj) throws Exception{ dao.saveEntity(obj); } /** * * @param obj * @throws Exception * @author DengYouming * @since 2016-8-30 下午8:47:40 */ public void update(ErpReportdetailPDFContent obj) throws Exception{ dao.update(obj); } /** * * @param pdfName * @param code * @return * @throws Exception * @author DengYouming * @since 2016-8-30 下午8:47:43 */ public List<ErpReportdetailPDFContent> findByProps(String code, String pdfName) throws Exception{ List<ErpReportdetailPDFContent> list = null; if(StringUtils.isNotEmpty(code)&&StringUtils.isNotEmpty(pdfName)){ list = dao.findByProps( code,pdfName); } return list; } /** * 把要打印的文件添加到打印任务 * @param filePath 文件的物理路径 * @param entity 客户信息 * @param events 场次信息 * @return boolean * @author DengYouming * @since 2016-10-26 下午2:14:56 */ public boolean deal4PrintTask(String filePath, Integer fileSize, ErpCustomer entity, ErpEvents events){ //返回标志 boolean flag = false; ErpReportdetailPDFContent pdfContentObj = null; String name = entity.getName(); String barcode = entity.getCode(); String age = entity.getAge(); String gender = entity.getSex(); String combo = entity.getSetmealName(); Date date = Calendar.getInstance().getTime(); //查找PDF匹配报告 List<ErpReportdetailPDFContent> pdfList = null; String pdfName = filePath.substring(filePath.lastIndexOf(File.separator)+1); try { pdfList = this.findByProps(barcode, pdfName); if(StringUtils.isNotEmpty(filePath)&&filePath.contains(".")){ String type = "3"; if(StringUtils.containsIgnoreCase(filePath, "pdf")){ type = "2"; } if(!CollectionUtils.isEmpty(pdfList)){ pdfContentObj = pdfList.get(0); if(pdfContentObj!=null){ //无文件路径或者文件路径不正常,则更新,否则不更新 pdfContentObj.setUsername(name); //修复bug用 pdfContentObj.setFilepath(filePath); pdfContentObj.setFilesize(""+fileSize); // add by me 2016-12-19 pdfContentObj.setUpdateTime(date); this.update(pdfContentObj); /**@since 2016年10月8日15:18:37 @author Carly*/ List<ErpPrintTaskContent> contentList = contentService.getContentByPdfId(pdfContentObj.getId()); if (!CollectionUtils.isEmpty(contentList)) { ErpPrintTaskContent content2 = contentList.get(0); content2.setFilePath(filePath); content2.setUserName(name); content2.setUpdateTime(date); content2.setType(type); contentService.update(content2); } flag = true; dealLog.info("姓名:"+name+",条码:"+barcode+",ERP_REPORTDETAIL_PDFCONTENT表中信息已更新!"); } }else{ pdfContentObj = new ErpReportdetailPDFContent(); pdfContentObj.setPdfname(pdfName); pdfContentObj.setUsername(name); pdfContentObj.setAge(""+age); pdfContentObj.setCode(barcode); pdfContentObj.setSex(gender); pdfContentObj.setSetmeal_name(combo); pdfContentObj.setFilesize(""+fileSize); // pdfContentObj.setMd5(md5); pdfContentObj.setBatchno(events.getBatchNo()); pdfContentObj.setFilepath(filePath); pdfContentObj.setIsrecord(2); pdfContentObj.setIsrepeat(0); pdfContentObj.setMatchstate(2); //匹配状态 add 2016-12-30 pdfContentObj.setCreatedate(Calendar.getInstance().getTime()); pdfContentObj.setProvice(entity.getProvice()); pdfContentObj.setCity(entity.getCity()); pdfContentObj.setBranch_company(events.getBranchCompanyId()); pdfContentObj.setEvents_no(events.getEventsNo()); pdfContentObj.setPs("0"); pdfContentObj.setSettlement_status("0"); this.saveEntity(pdfContentObj); //add by chenqi @since 2016年10月11日12:01:34 添加到需要打印的表(ErpPrintTaskContent)中 List<ErpCustomer> customerList = contentService.getCustomerInfoByCode(pdfContentObj.getCode()); CustomerRelationShipPro shipPro = contentService.getProjectCodeByEvent(customerList.get(0).getEventsNo()); ErpPrintTaskContent contents = new ErpPrintTaskContent(); contents.setAge(pdfContentObj.getAge()); contents.setBatchNo(pdfContentObj.getBatchno()); contents.setBranchCompanyId(pdfContentObj.getBranch_company()); contents.setProvince(pdfContentObj.getProvice()); contents.setCity(pdfContentObj.getCity()); contents.setCode(pdfContentObj.getCode()); contents.setUserName(pdfContentObj.getUsername()); contents.setCombo(pdfContentObj.getSetmeal_name()); contents.setGender(pdfContentObj.getSex()); contents.setBatchNo(pdfContentObj.getBatchno()); contents.setFilePath(pdfContentObj.getFilepath()); contents.setSaleman(pdfContentObj.getSales_man()); contents.setPdfContentId(pdfContentObj.getId()); contents.setCustomerId(customerList.get(0).getId()); contents.setDept(customerList.get(0).getDepartment()); contents.setOwnedCompanyId(customerList.get(0).getOwnedCompanyId()); if (shipPro!=null) { contents.setProjectCode(shipPro.getProjectCode()); } contents.setPs("0"); contents.setType(type); contents.setIsManuallyAdd("2"); contents.setCreateTime(date); contents.setCreateUser("金域"); contents.setReportType(1); // modify 2016-12-12 contentService.save(contents); flag = true; } } } catch (Exception e) { dealLog.info(e); } return flag; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package poo.estacionamiento; import java.math.BigDecimal; import java.util.Date; /** * * @author Candelaria */ public class Tarifa { private int cantidadIngresosSinSaldo; private boolean esDeAbono; private Date fecha; private BigDecimal montoIngreso; /** * Constructor por Defecto */ public Tarifa() { } /** * Constructor con parámetros. * @param cantidadIngresosSinSaldo * @param esDeAbono; * @param fecha; * @param montoIngreso; */ public Tarifa(int cantidadIngresosSinSaldo, boolean esDeAbono, Date fecha, BigDecimal montoIngreso) { this.cantidadIngresosSinSaldo = cantidadIngresosSinSaldo; this.esDeAbono = esDeAbono; this.fecha = fecha; this.montoIngreso = montoIngreso; } public int getCantidadIngresosSinSaldo() { return cantidadIngresosSinSaldo; } public void setCantidadIngresosSinSaldo(int cantidadIngresosSinSaldo) { this.cantidadIngresosSinSaldo = cantidadIngresosSinSaldo; } public boolean isEsDeAbono() { return esDeAbono; } public void setEsDeAbono(boolean esDeAbono) { this.esDeAbono = esDeAbono; } public Date getFecha() { return fecha; } public void setFecha(Date fecha) { this.fecha = fecha; } public BigDecimal getMontoIngreso() { return montoIngreso; } public void setMontoIngreso(BigDecimal montoIngreso) { this.montoIngreso = montoIngreso; } }
package br.com.mixfiscal.prodspedxnfe.dao.questor; import br.com.mixfiscal.prodspedxnfe.dao.util.QuestorHibernateUtil; import br.com.mixfiscal.prodspedxnfe.domain.questor.FatorConversaoUnidade; import java.math.BigDecimal; import java.util.List; import org.junit.Test; import static org.junit.Assert.*; public class FatorConversaoUnidadeDAOTest { public FatorConversaoUnidadeDAOTest() { } @Test public void testListar() throws Exception { try { QuestorHibernateUtil.beginTransaction(); FatorConversaoUnidadeDAO fcuDao = new FatorConversaoUnidadeDAO(); List<FatorConversaoUnidade> list = fcuDao.listar(); QuestorHibernateUtil.commitCurrentTransaction(); assertTrue(list.size() > 0); } catch(Exception ex) { fail(ex.getMessage()); throw ex; } } @Test public void testSalvar() throws Exception { try { QuestorHibernateUtil.beginTransaction(); FatorConversaoUnidade fcu = new FatorConversaoUnidade(); fcu.setCodigoEmpresa(9999); fcu.setCodigoProduto(0); fcu.setCodigoUnidadeMedida("CX"); fcu.setFator(new BigDecimal(55.55)); FatorConversaoUnidadeDAO fcuDao = new FatorConversaoUnidadeDAO(); fcuDao.salvar(fcu); QuestorHibernateUtil.commitCurrentTransaction(); } catch(Exception ex) { QuestorHibernateUtil.rollbackCurrentTransaction(); fail(ex.getMessage()); throw ex; } } @Test public void testExcluir() throws Exception { try { QuestorHibernateUtil.beginTransaction(); FatorConversaoUnidade fcu = new FatorConversaoUnidade(); fcu.setCodigoEmpresa(9999); fcu.setCodigoProduto(0); fcu.setCodigoUnidadeMedida("CX"); FatorConversaoUnidadeDAO fcuDao = new FatorConversaoUnidadeDAO(); fcuDao.excluir(fcu); QuestorHibernateUtil.commitCurrentTransaction(); } catch(Exception ex) { QuestorHibernateUtil.rollbackCurrentTransaction(); fail(ex.getMessage()); throw ex; } } }
package com.example.sieunhan.github_client.core.commit; import android.accounts.Account; import android.content.Context; import android.util.Log; import com.github.mobile.accounts.AuthenticatedUserTask; import com.github.mobile.util.HtmlUtils; import com.github.mobile.util.HttpImageGetter; import com.google.inject.Inject; import org.eclipse.egit.github.core.Commit; import org.eclipse.egit.github.core.CommitComment; import org.eclipse.egit.github.core.IRepositoryIdProvider; import org.eclipse.egit.github.core.RepositoryCommit; import org.eclipse.egit.github.core.service.CommitService; import java.util.List; /** * Task to load a commit by SHA-1 id */ public class RefreshCommitTask extends AuthenticatedUserTask<FullCommit> { private static final String TAG = "RefreshCommitTask"; @Inject private CommitStore store; @Inject private CommitService service; private final IRepositoryIdProvider repository; private final String id; private final HttpImageGetter imageGetter; /** * @param context * @param repository * @param id * @param imageGetter */ public RefreshCommitTask(Context context, IRepositoryIdProvider repository, String id, HttpImageGetter imageGetter) { super(context); this.repository = repository; this.id = id; this.imageGetter = imageGetter; } @Override protected FullCommit run(Account account) throws Exception { RepositoryCommit commit = store.refreshCommit(repository, id); Commit rawCommit = commit.getCommit(); if (rawCommit != null && rawCommit.getCommentCount() > 0) { List<CommitComment> comments = service.getComments(repository, commit.getSha()); for (CommitComment comment : comments) { String formatted = HtmlUtils.format(comment.getBodyHtml()) .toString(); comment.setBodyHtml(formatted); imageGetter.encode(comment, formatted); } return new FullCommit(commit, comments); } else return new FullCommit(commit); } @Override protected void onException(Exception e) throws RuntimeException { super.onException(e); Log.d(TAG, "Exception loading commit", e); } }
package reseau.couches; import reseau.Message; import reseau.adresses.Adresse; /** * @author martine */ public class UDP extends Transport4 { public UDP() { super(); } @Override protected Message getEntete(int portSource, Adresse adrDest, int portDest, Message message) { Message entete= new Message(portSource); entete.ajouter(portDest); entete.ajouter(8+message.size()); entete.ajouter(0); return entete; } }
/* * 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 bin2dec; import java.util.Scanner; /** * * @author emwhfm */ public class Bin2Dec { /** * @param args the command line arguments */ public static void main(String[] args) { // Create a Scanner Scanner input = new Scanner(System.in); // Prompt the user to enter a string System.out.print("Enter a bin number: "); String bin = input.nextLine(); try { System.out.println("The decimal value for bin number " + bin + " is " + binToDecimal(bin)); } catch (NumberFormatException ex) { System.out.println(ex.getMessage()); System.out.println("================================"); System.out.println(ex.toString()); System.out.println("================================"); ex.printStackTrace(); } } public static int binToDecimal(String bin) throws NumberFormatException { int decimalValue = 0; for (int i = 0; i < bin.length(); i++) { char binChar = bin.charAt(i); decimalValue = decimalValue * 2 + binCharToDecimal(binChar); } return decimalValue; } public static int binCharToDecimal(char ch) throws NumberFormatException { if (ch >= '0' && ch <= '1') return ch - '0'; else { throw new NumberFormatException("Illegal char: " + ch); } } }
package com.thonline.business.logic; import java.math.BigDecimal; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.sql.Timestamp; import java.util.Arrays; import java.util.Calendar; import java.util.EnumSet; import javax.sql.DataSource; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ibm.as400.access.AS400JDBCConnectionPool; import com.ibm.as400.access.ConnectionPoolException; import com.ism.common.util.Utility; import com.thonline.common.THConstant; import com.tbhj.eai.be.common.THException; import com.tbhj.eai.be.dao.QueAuditDAO; import com.tbhj.eai.be.entity.BaseDO; import com.tbhj.eai.be.entity.QueAuditDO; import com.tbhj.eai.be.helper.DateHelper; import com.tbhj.eai.be.helper.LogHelper; import com.tbhj.eai.be.util.ConnectionUtil; public class BaseService { protected DataSource dataSource = null; protected int sysOut = 1; protected boolean verbose = true; protected LogHelper logHelper = null; private QueAuditDAO oQueAuditDAO = null; private QueAuditDO queAudit = null; protected Connection conn = null; private static Logger logger = LoggerFactory.getLogger(BaseService.class); protected String logId; protected String logTag; public BaseService() { } public BaseService(DataSource dataSource) throws THException { this.dataSource = dataSource; } // protected Connection GetConnection() throws SQLException, ConnectionPoolException { // if (this.dataSource != null) { // if ( conn == null ) { // logger.info("BS *.*.*", "Fetching Connection from datasource!"); // conn = this.dataSource.getConnection(); // } // // } else { // logger.info("BS *.*.*", "Fetching Connection from connection util!"); // AS400JDBCConnectionPool pool = ConnectionUtil.getPool(); // logger.info("BS *.*.*", "AVAILABLE:" + pool.getAvailableConnectionCount() + ", ACTIVE:" + pool.getActiveConnectionCount() + ", MAX:" + pool.getMaxConnections()); // conn = ConnectionUtil.getConnection(); // // pool = ConnectionUtil.getPool(); // logger.info("BS *.*.*", "AVAILABLE:" + pool.getAvailableConnectionCount() + ", ACTIVE:" + pool.getActiveConnectionCount() + ", MAX:" + pool.getMaxConnections()); // } // DatabaseMetaData connData = conn.getMetaData(); // logger.info("BS *.*.*", "ConnUserName: " + connData.getUserName()); // logger.info("BS *.*.*", "Catalog/" + connData.getCatalogTerm() + ": " + conn.getCatalog()); // logger.info("BS *.*.*", "Schema/" + connData.getSchemaTerm() + ": "); // // return conn; // } public DataSource getDataSource() { return this.dataSource; } public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; logger.debug("BS *.*.*", "DataSource Set To : {}", dataSource.toString()); } // protected void InitLog(String LogID, String LogTag) { // if (this.logHelper == null) { // this.logHelper = new LogHelper(LogID, this.sysOut, this.verbose); // this.logHelper.setLogTag(LogTag); // this.logHelper.Info("", "New Logs Created ID:" + LogID + " Tag:" + LogTag); // } else { // this.logHelper.Info("", "New Logs NOT Created ID:" + LogID + " Tag:" + LogTag); // } // this.logId = LogID; // this.logTag = LogTag; // } // protected void LogPrint() { // if (this.logHelper != null) { // this.logHelper.PrintLog(this.sysOut, this.verbose); // } else { // System.out.println("Log Not Initialized"); // System.out.println("LOGGER NOT INITIALIZED"); // } // } private String insertQueueUTL(String noAkaun) throws SQLException, ConnectionPoolException { String retVal = "000"; boolean err0803 = false; SQLException sqException = null; _QueAuditDO().setNo_akaun(noAkaun); if (this.logHelper != null) { _QueAuditDO().setOrigin(this.logHelper.getLogTag() + " - " + this.logHelper.getLogID()); _QueAuditDO().setTransId(this.logHelper.getAppTransID()); } try { logger.info("[QUE-BS Insert]", "Inserting Audit Que: " + _QueAuditDO().toString()); QueAuditDAO oQueDAO = _QueAuditDAO(); oQueDAO.addQueAuditDO(_QueAuditDO()); this.queAudit = oQueDAO.findQueAudit(noAkaun); logger.info("[QUE-BS Insert]", "Audit Que Inserted :" + _QueAuditDO().toString()); } catch (SQLException exc) { err0803 = exc.getErrorCode() == -803; logger.error("[QUE-BS Insert]", "SQLState[" + exc.getSQLState() + "] SQLError[" + exc.getErrorCode() + "]"); if (!err0803) { sqException = exc; } } if (err0803) { logger.error("[QUE-BS Insert]", " Collision Detected on Account " + noAkaun); retVal = "989"; } else if (sqException != null) { throw sqException; } return retVal; } protected String insertQueueUTL(String noAkaun, String functionID, String serviceID) throws SQLException, ConnectionPoolException { _QueAuditDO().setFunctionID(functionID); _QueAuditDO().setServiceName(serviceID); _QueAuditDO().setOrigin("UNITELLER"); _QueAuditDO().setTransId("UNITELLER"); return insertQueueUTL(noAkaun); } protected void deleteCompletedQueue(String noAkaun) { try { logger.info("[QUE-BS Acct]", "Deleting Audit Que - Acct:" + noAkaun + "*"); _QueAuditDAO().deleteCompletedQue(noAkaun); logger.info("[QUE-BS Acct]", "Audit Que Deleted - Acct:" + noAkaun + "*"); } catch (SQLException exc) { logger.error("[QUE-BS Acct]", "SQLState[" + exc.getSQLState() + "] SQLError[" + exc.getErrorCode() + "]"); logger.error("[QUE-BS Acct]", "Audit Que NOT Deleted - Acct:" + noAkaun + "*"); } catch (ConnectionPoolException cpx) { logger.error("[QUE-BS Expired]", "Connection Pool[" + cpx.getReturnCode() + "] SQLError[" + cpx.getLocalizedMessage() + "]"); logger.error("[QUE-BS Expired]", "Expired Que NOT Deleted"); } } protected void deleteCompletedTrans(String transID) { try { logger.info("[QUE-BS Trans]", "Deleting Audit Que - Trans:" + transID + "*"); _QueAuditDAO().deleteCompletedTrans(transID); logger.info("[QUE-BS Trans]", "Audit Que Deleted - Trans:" + transID + "*"); } catch (SQLException exc) { logger.error("[QUE-BS Trans]", "SQLState[" + exc.getSQLState() + "] SQLError[" + exc.getErrorCode() + "]"); logger.error("[QUE-BS Trans]", "Audit Que NOT Deleted - Trans:" + transID + "*"); } catch (ConnectionPoolException cpx) { logger.error("[QUE-BS Expired]", "Connection Pool[" + cpx.getReturnCode() + "] SQLError[" + cpx.getLocalizedMessage() + "]"); logger.error("[QUE-BS Expired]", "Expired Que NOT Deleted"); } } protected void deleteExpiredQue() { try { logger.info("[QUE-BS Expired]", "Deleting Expired Que"); _QueAuditDAO().deleteExpiredQue(); logger.info("[QUE-BS Expired]", "Expired Que Deleted"); } catch (SQLException eql) { logger.error("Failed to delete expired queue", eql); logger.error("[QUE-BS Expired]", "SQLState[" + eql.getSQLState() + "] SQLError[" + eql.getErrorCode() + "]"); logger.error("[QUE-BS Expired]", "Expired Que NOT Deleted"); } catch (ConnectionPoolException cpx) { logger.error("[QUE-BS Expired]", "Connection Pool[" + cpx.getReturnCode() + "] SQLError[" + cpx.getLocalizedMessage() + "]"); logger.error("[QUE-BS Expired]", "Expired Que NOT Deleted"); } } protected void closeQue() { // try { // if (this.qConn != null) { // if (!this.qConn.isClosed()) this.qConn.close(); // logger.info("[QUE-BS Close]", "Queue Connection Closed"); // } // } catch (SQLException eql) { // logger.info("[QUE-BS Close]", "SQLState[" + eql.getSQLState() + "] SQLError[" + eql.getErrorCode() + "]"); // } } protected QueAuditDAO _QueAuditDAO() throws SQLException, ConnectionPoolException { Connection cnn = _logConn(); if (this.oQueAuditDAO == null) this.oQueAuditDAO = new QueAuditDAO(cnn); else { this.oQueAuditDAO.refreshConnection(cnn); } return this.oQueAuditDAO; } protected Connection _logConn() throws SQLException, ConnectionPoolException { // logger.info("[LOG-BS DAO]", "Fetching LOG Connection"); // if (this.qConn == null) { // logger.info("[LOG-BS DAO]", "qConn Is Null, Requesting new connection"); // qConn = GetConnection(); // } // if ((this.qConn != null) && (this.qConn.isClosed())) { // logger.info("[LOG-BS DAO]", "qConn was Closed, Requesting new connection"); // qConn = GetConnection(); // } // qConn.setAutoCommit(true); return conn; } private QueAuditDO _QueAuditDO() { if (this.queAudit == null) { this.queAudit = new QueAuditDO(); } return this.queAudit; } protected void RollBackTrans(Connection cnn) throws SQLException { if (cnn != null) { if (!cnn.isClosed()) { cnn.rollback(); }else { logger.error("", "Unable to rollback - Connection is Already Closed"); } }else { logger.error("", "Unable to rollback - Connection is Null"); } } protected void CommitTrans(Connection cnn) throws SQLException { if (cnn != null) { if (!cnn.isClosed()) { cnn.commit(); } else{ logger.error("", "Unable to commit - Connection is Already Closed"); } } else logger.error("", "Unable to commit - Connection is Null"); } protected void updateEntityBase(BaseDO data, Timestamp currentTimeStamp, boolean newRecord, String user) { if (user.length() > 10) { user = StringUtils.left(user, 10); } if (newRecord) { data.setTH_id_pengujud(user); data.setTH_tkh_pengujud(currentTimeStamp); data.setTH_id_kemaskini(""); data.setTH_tkh_kemaskini(DateHelper.convert_String_To_JavaDate("0001-01-01 00:00:00.000", "yyyy-MM-dd HH:mm:ss.SSS")); data.setTH_status_rekod("2"); } else { data.setTH_id_kemaskini(user); data.setTH_tkh_kemaskini(currentTimeStamp); data.setTH_status_rekod("2"); } } protected BigDecimal getBDValue(String strValue) { BigDecimal retVal = new BigDecimal("0"); if (!StringUtils.isBlank(strValue)) { retVal = new BigDecimal(strValue); retVal = retVal.movePointLeft(2); } retVal = retVal.setScale(2, 4); return retVal; } } /* Location: /Users/dhyunkang/Desktop/Broker 1/tbhjbe.jar * Qualified Name: com.tbhj.eai.be.service.BaseService * JD-Core Version: 0.6.2 */
package algorithm; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class School { public static void main(String[] args) { School school = new School(); // 학생들 저장 List<Student> studentList = school.getStudentList(); List<Student> registStudentList = new ArrayList<>(); // 검색 및 저장 boolean flag = true; Scanner sc = new Scanner(System.in); while (flag) { System.out.println("검색하고 싶은 학생 이름을 입력하세요!!"); String search = sc.next(); boolean searchResult = false; for (Student student : studentList) { if (student.name.equals(search)) { System.out.println("찾았습니다."); registStudentList.add(student); searchResult = true; break; } } if (!searchResult) { System.out.println("검색 결과가 없습니다!!"); } System.out.println("계속 검색을 하겠느냐 true, 종료하고싶으면 false"); flag = sc.nextBoolean(); } // 종료 System.out.println("종료합니다.!!"); System.out.println("등록된 학생 목록입니다."); for (Student student : registStudentList) { System.out.println(student.toString()); } } private List<Student> getStudentList() { List<Student> studentList = new ArrayList<>(); studentList.add(new StudentBuilder("손오공", 1).build()); studentList.add(new StudentBuilder("저팔계", 2).build()); studentList.add(new StudentBuilder("사오정", 3).build()); studentList.add(new StudentBuilder("삼장법사", 4).build()); return studentList; } public class StudentBuilder { private Student student; public StudentBuilder(String name, int no) { this.student = new Student(); this.student.setName(name); this.student.setNo(no); } public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } public Student build() { return this.student; } } public class Student { private String name; private int no; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNo() { return no; } public void setNo(int no) { this.no = no; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", no=" + no + '}'; } } }
package gameData.fireAlgorithms; import gameData.Boards.BoardAbstract; import gameData.Boards.Coordinates; import gameData.enums.TileState; import java.util.concurrent.ThreadLocalRandom; /** * Created by corentinl on 2/14/16. */ public class FireAlgorithmRandom extends FireAlgorithmAbstract { public FireAlgorithmRandom(int nbRows, int nbColumns, BoardAbstract board) { super(nbRows, nbColumns, board); } @Override public Coordinates getNextHit() { int x = -1; int y = -1; boolean coordinatesFound = false; do { x = ThreadLocalRandom.current().nextInt(0, this.nbRows); y = ThreadLocalRandom.current().nextInt(0, this.nbColumns); TileState state = board.checkState(x, y); if (state == TileState.UNKNOWN) { coordinatesFound = true; } } while (coordinatesFound == false); return new Coordinates(x, y); } }
package controllers; import models.Line; import models.Ticket; import play.libs.Json; import play.mvc.Controller; import play.mvc.Result; import java.util.*; import java.util.stream.Collectors; /** * This controller contains a set of actions to handle HTTP requests * to the application's lottery tickets. */ public class LotteryController extends Controller { private final List<Ticket> tickets = new ArrayList<>(); private final static Random random = new Random(); /** * Lists all lottery tickets * <p> * Example: curl -X GET http://localhost:9000/ticket * * @return A http 200 response with a body containing all tickets as json */ public Result allTickets() { return ok(Json.toJson(this.tickets.toString())) .as("application/json"); } /** * Generate a new ticket and add it to the collection of tickets * <p> * Example (with 3 lines): curl -X POST http://localhost:9000/ticket/3 * * @param numberOfLines the number of lines to add to the ticket * @return A http 200 response with a body containing the new ticket */ public Result createTicket(int numberOfLines) { if (this.validateNumberOfLines(numberOfLines).isPresent()) { return this.validateNumberOfLines(numberOfLines).get(); } Ticket t = new Ticket(); this.addLines(t, numberOfLines); this.tickets.add(t); return ok(Json.toJson(t).toString()) .as("application/json"); } /** * Searches the collection of tickets using the ticket ID as the key * <p> * Example: curl -X GET http://localhost:9000/ticket/3d8df83f-3b08-479b-b4ac-2aa542de0b58 * * @param id the ticket to search for * @return if a corresponding ticket is found a http 200 response with a body containing the ticket, * otherwise a http 400 (not found) is returned */ public Result findTicket(String id) { Optional<Ticket> maybeTicket = this.searchTicketsById(id); if (maybeTicket.isPresent()) { return ok(Json.toJson(maybeTicket).toString()) .as("application/json"); } return notFound("Could not find specified ticket"); } /** * Adds the specified number of lines to the lottery ticket * <p> * Example (adding 3 lines): curl -X PUT http://localhost:9000/ticket/3d8df83f-3b08-479b-b4ac-2aa542de0b58/3 * * @param id the lottery ticket to modify * @param numberOfLines the number of lines to add to the ticket * @return if a corresponding ticket is found a http 200 response with a body containing the modified ticket, * otherwise a http 400 (not found) is returned */ public Result addLines(String id, int numberOfLines) { if (this.validateNumberOfLines(numberOfLines).isPresent()) { return this.validateNumberOfLines(numberOfLines).get(); } Optional<Ticket> maybeTicket = this.searchTicketsById(id); if (maybeTicket.isPresent()) { if (maybeTicket.get().isAmended()) { return forbidden("Not allowed to amend ticket"); } this.addLines(maybeTicket.get(), numberOfLines); this.updateTicket(maybeTicket.get()); return ok(Json.toJson(maybeTicket).toString()) .as("application/json"); } return notFound("Could not find specified ticket"); } /** * Checks the status of a ticket for winning lines and marks it as checked * <p> * Example: curl -X PUT http://localhost:9000/status/3d8df83f-3b08-479b-b4ac-2aa542de0b58 * * @param id the lottery ticket to check * @return if a corresponding ticket is found a http 200 response with a body containing the modified ticket, * otherwise a http 400 (not found) is returned */ public Result status(String id) { Optional<Ticket> maybeTicket = this.searchTicketsById(id); if (maybeTicket.isPresent()) { if (!maybeTicket.get().isAmended()) { maybeTicket.get().setAmended(true); this.checkTicket(maybeTicket.get()); this.sortResults(maybeTicket.get()); this.updateTicket(maybeTicket.get()); } return ok(Json.toJson(maybeTicket).toString()) .as("application/json"); } return notFound("Could not find specified ticket"); } /** * Generates a new line consisting of 3 random integers between 0 and 2 inclusive * * @return an array of 3 numbers, with each element being 0, 1 or 2 */ private int[] newLine() { return new int[]{ random.nextInt(3), random.nextInt(3), random.nextInt(3) }; } /** * Searches the collection of tickets for a ticket with the given ID * * @param id The ticket to look for * @return an option of the requested ticket */ private Optional<Ticket> searchTicketsById(String id) { return this.tickets.stream() .filter(ticket -> ticket.getId().equals(id)) .findAny(); } /** * Adds a specified number of lines to the ticket * * @param ticket the lottery ticket to modify * @param numberOfLines the number of lines to add to the ticket */ private void addLines(Ticket ticket, int numberOfLines) { for (int i = 0; i < numberOfLines; i++) { int[] line = this.newLine(); ticket.addLine(line); } } /** * Update the collection of tickets to reflect the change in a ticket * * @param ticket the updated ticket */ private void updateTicket(Ticket ticket) { Optional<Ticket> toRemove = this.searchTicketsById(ticket.getId()); toRemove.ifPresent(foundTicket -> { this.tickets.remove(foundTicket); this.tickets.add(ticket); }); } /** * Calculates whether the lines in a ticket are winning lines * * @param ticket the ticket to check */ private void checkTicket(Ticket ticket) { List<Line> lines = ticket.getLines(); for (Line line : lines) { if (line.getNumbers()[0] + line.getNumbers()[1] + line.getNumbers()[2] == 2) { line.setResult(Ticket.RESULT_EQUAL_TWO); } else if ((line.getNumbers()[0] == line.getNumbers()[1]) && (line.getNumbers()[0] == line.getNumbers()[2])) { line.setResult(Ticket.RESULT_ALL_SAME); } else if ((line.getNumbers()[0] != line.getNumbers()[1]) && (line.getNumbers()[0] != line.getNumbers()[2])) { line.setResult(Ticket.RESULT_UNIQUE_FIRST); } else { line.setResult(Ticket.RESULT_DEFAULT); } } } /** * Takes a ticket and sorts them by line result * * @param ticket the ticket to sort */ private void sortResults(Ticket ticket) { ticket.setLines(ticket.getLines().stream() .sorted(Comparator.comparing(Line::getResult).reversed()) .collect(Collectors.toList())); } /** * Validate the user input when supplying lines * * @param numberOfLines the number of lines to verify * @return An option of a Result or an empty option when there are no errors */ private Optional<Result> validateNumberOfLines(int numberOfLines) { if (numberOfLines <= 0) { return Optional.of(badRequest("Please ensure the number of lines is a positive number")); } return Optional.empty(); } }
package com.example.kyle.myapplication.Database.Role; import com.example.kyle.myapplication.Database.Abstract.Abstract_Table; /** * Created by Kyle on 1/31/2016. */ public class Tbl_Role extends Abstract_Table { public long roleID = -1; public String title = ""; public Tbl_Role() { } public Tbl_Role(long roleID) { this.roleID = roleID; } public Tbl_Role( String title) { this.title = title; } @Override public String isValidRecord() { String anyErrors = ""; if (title.isEmpty()) { anyErrors += "\nTitle is a required field"; } if (!anyErrors.isEmpty()) { anyErrors = "Please fix the following errors:" + anyErrors; } return anyErrors; } @Override public String getDataGridDisplayValue() { return this.roleID + " - " + this.title; } @Override public String toString() { return this.title; } @Override public String getDataGridPopupMessageValue() { return "ID: " + Long.toString(this.roleID) + "\n" + "Title: " + this.title; } }
package com.receiptify.data.Entities; import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.OnConflictStrategy; import androidx.room.Query; import java.util.List; @Dao public interface CompaniesDao { @Query("SELECT * from companies") LiveData<List<Companies>> getAll(); @Insert(onConflict = OnConflictStrategy.IGNORE) void insert(Companies word); @Query("DELETE FROM companies") void deleteAll(); @Delete void delete(Companies word); }
package com.lynch.search.twothreetree; import java.util.ArrayList; import java.util.Collections; /** * Created by lynch on 2018/10/6. <br> **/ public class TwoThreeTree { private Node root; //root of the tree /** * create an empty root */ public TwoThreeTree() { root = new Node(); } /** * insert method * * @param x * @return */ public boolean insert(int x) { Node currNode = root.search(x); if (!currNode.keys.contains(x)) { currNode.insert(x); return true; } return false; } /** * search method * * @param x * @return */ public String search(int x) { String str = ""; Node currNode = root.search(x); for (int i = 0; i < currNode.size(); i++) { if (i > 0) str += " "; str += currNode.keys.get(i); } return str; } //set Node to store information private class Node implements Comparable<Node> { private final int NODE_MAX = 2; private Node parent; private ArrayList<Integer> keys; private ArrayList<Node> children; //root node public Node() { parent = null; keys = new ArrayList<>(); children = new ArrayList<>(); } //child node public Node(int key) { parent = null; keys = new ArrayList<>(); keys.add(key); children = new ArrayList<>(); } public Node search(int key) { if (isLeaf()) return this; // Check if key value is in the current node for (int i = 0; i < size(); i++) { int check = keys.get(i); if (check == key) return this; else if (key < check) return children.get(i).search(key); } return children.get(children.size() - 1).search(key); } public void insert(int value) { Node currNode = search(value); currNode.add(value); } public void add(int value) { keys.add(value); Collections.sort(keys); if (size() > NODE_MAX) split(); } public void split() { Node parentNode; Node left = new Node(keys.get(0)); Node right = new Node(keys.get(2)); int key = keys.get(1); if (!isLeaf()) { for (int i = 0; i < 2; i++) { left.children.add(children.get(i)); children.get(i).parent = left; right.children.add(children.get(i + 2)); children.get(i + 2).parent = right; } } if (parent == null) { parentNode = this; children.clear(); keys.clear(); } else { parentNode = parent; parentNode.children.remove(this); } parentNode.children.add(left); left.parent = parentNode; parentNode.children.add(right); right.parent = parentNode; Collections.sort(parentNode.children); parentNode.add(key); } /** * @return Size of keys ArrayList. */ public int size() { return keys.size(); } /** * Check if has children * * @return */ public boolean isLeaf() { return children.size() == 0; } /** * compare to other node * * @param other * @return */ public int compareTo(Node other) { return this.keys.get(0).compareTo(other.keys.get(0)); } } }
package org.ufla.tsrefactoring.refactoring; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import org.ufla.tsrefactoring.dto.ResultTestSmellDTO; import com.github.javaparser.StaticJavaParser; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.body.MethodDeclaration; import com.github.javaparser.ast.visitor.ModifierVisitor; import com.github.javaparser.ast.visitor.Visitable; public class EmptyTestRefactoring { public static boolean executeRefactory(ResultTestSmellDTO emptyTestSmell) throws FileNotFoundException { File file = new File(emptyTestSmell.getFilePath()); CompilationUnit cu = StaticJavaParser.parse(file); cu.accept(new ModifierVisitor<Void>() { @Override public Visitable visit(MethodDeclaration n, Void arg) { if (n.getBody().get().getStatements().size() == 0) { if (n.getBegin().get().line == emptyTestSmell.getLineNumber()) { return null; } } return super.visit(n, arg); } }, null); try { // The second parameter says to append the file. // False, the file will be cleared before writing FileWriter fw = new FileWriter(file, false); fw.write(cu.toString()); fw.close(); return true; } catch (IOException e) { e.printStackTrace(); } return false; } }
class NumMatrix { int[][] dp; public NumMatrix(int[][] matrix) { dp = new int[matrix.length+1][matrix[0].length+1]; for(int i =0; i<matrix.length;i++){ for(int j=0;j<matrix[0].length;j++){ dp[i+1][j+1] = dp[i][j+1] + dp[i+1][j]+matrix[i][j]-dp[i][j]; } } } public int sumRegion(int row1, int col1, int row2, int col2) { return dp[row2+1][col2+1]+dp[row1][col1]-dp[row2+1][col1]-dp[row1][col2+1]; } }
package com.logicbig.example.injectingcollection.collection.jconfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.*; import java.util.Set; @PropertySource("classpath:app-props.properties") @Configuration public class SetInjectionRefQualifierExample { @Bean public TestBean testBean () { return new TestBean(); } @Bean @Qualifier("myRefBean") public RefBeanService refBean1 () { return new RefBean(); } @Bean public RefBeanService refBean2 () { return new RefBean2(); } @Bean @Qualifier("myRefBean") public RefBeanService refBean3 () { return new RefBean3(); } public static void main (String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( SetInjectionRefQualifierExample.class); TestBean bean = context.getBean(TestBean.class); System.out.println(bean.getRefBeanServices()); } public static class TestBean { private Set<RefBeanService> refBeanServices; @Autowired @Qualifier("myRefBean") public void setRefBeanServices (Set<RefBeanService> refBeanServices) { this.refBeanServices = refBeanServices; } public Set<RefBeanService> getRefBeanServices () { return refBeanServices; } } public static interface RefBeanService { String getStr (); } public static class RefBean implements RefBeanService { private String str; @Override public String getStr () { return str; } @Value("${some-prop1:defaultStr}") public void setStr (String str) { this.str = str; } @Override public String toString () { return "RefBean{" + "str='" + str + '\'' + '}'; } } public static class RefBean2 implements RefBeanService { private String str; @Override public String getStr () { return str; } @Value("${some-prop2:defaultStr}") public void setStr (String str) { this.str = str; } @Override public String toString () { return "RefBean{" + "str='" + str + '\'' + '}'; } } public static class RefBean3 implements RefBeanService { private String str; @Override public String getStr () { return str; } @Value("${some-prop3:defaultStr}") public void setStr (String str) { this.str = str; } @Override public String toString () { return "RefBean{" + "str='" + str + '\'' + '}'; } } }
package com.busekylin.springboottest.repository; import com.busekylin.springboottest.domain.Web; public interface WebRepository { void addWeb(Web web); Web getWeb(); }
package com.social.server.http; import com.social.server.dto.UserDto; import com.social.server.util.JsonUtil; import com.social.server.util.TokenUtil; import lombok.Data; import org.springframework.validation.ObjectError; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; @Data public class Response<T> { private boolean success; private String token; private T data; private List<String> errors; public static <T> Response ok(T data) { Response<T> response = new Response<>(); response.setSuccess(true); response.setData(data); return response; } public static <T> Response ok() { Response<T> response = new Response<>(); response.setSuccess(true); return response; } public static Response error() { Response response = new Response(); response.setSuccess(false); return response; } public static Response error(List<ObjectError> objectErrors) { Response response = error(); response.setErrors(objectErrors.stream() .map(ObjectError::getDefaultMessage) .collect(Collectors.toList())); return response; } public static Response error(String errorCode) { Response response = error(); response.setErrors(Collections.singletonList(errorCode)); return response; } public static Response authorized(UserDto userDto) { Response response = Response.ok(userDto); response.setToken(TokenUtil.generateToken(userDto)); return response; } public String toJson() { return JsonUtil.toJson(this); } }
package com.haku.light.scene.comp; import com.haku.jlm.matrix.Mat4f; import com.haku.lecs.component.Component; public class TransformComp extends Component { public final Mat4f model = new Mat4f(); }
package bank.accounts; import bank.customers.Customer; import bank.movements.Transfer; /** * * @author Castro */ public class TermAccount extends Account implements Transfer { /** * ammount deposited to allow the term account to be created */ private double termDeposit; /** * empty constructor */ public TermAccount() { } /** * constructor * * @param costumer the owner of the account * @param termDeposit of the term account */ public TermAccount(Customer costumer, double termDeposit) { super(costumer); this.termDeposit = termDeposit; Account.generalAccountsList.add(this); } /** * transfers between two current accounts */ @Override public void transferBetween(double amount, int numRecAcct) { } }
import java.util.ArrayList; import java.util.Comparator; /** * Kenny Akers * Mr. Paige * Homework #26 * 5/30/18 */ public class Population { private ArrayList<Route> routes = new ArrayList<>(GeneticAlgo.POPULATION_SIZE); public Population(int populationSize, GeneticAlgo algo) { for (int i = 0; i < populationSize; i++) { routes.add(new Route(algo.getInitialRoute())); } } public Population(int populationSize, ArrayList<City> cities) { for (int i = 0; i < populationSize; i++) { routes.add(new Route(cities)); } } public ArrayList<Route> getRoutes() { return routes; } public void sortRoutesByFitness() { routes.sort(new Comparator<Route>() { @Override public int compare(Route route1, Route route2) { int result = 0; if (route1.getFitness() > route2.getFitness()) { result = -1; } else if (route1.getFitness() < route2.getFitness()) { result = 1; } return result; } }); } }
package no.ntnu.stud.ubilearn.fragments.practise; import no.ntnu.stud.ubilearn.R; import no.ntnu.stud.ubilearn.db.PractiseDAO; import no.ntnu.stud.ubilearn.models.BalanceSPPB; import no.ntnu.stud.ubilearn.models.Patient; import no.ntnu.stud.ubilearn.models.StandUpSPPB; import android.annotation.SuppressLint; import android.app.Fragment; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.Button; import android.widget.Spinner; import android.widget.TextView; import android.widget.AdapterView.OnItemSelectedListener; @SuppressLint("ValidFragment") public class SPPBStandUpResultFragment extends Fragment { private StandUpSPPB test; private TextView poeng; private Spinner fail; private PractiseDAO dao; private Button finishBtn; public SPPBStandUpResultFragment(StandUpSPPB test) { this.test = test; } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_practise_standup_result, container, false); poeng= (TextView)view.findViewById(R.id.poeng1); finishBtn = (Button)view.findViewById(R.id.finishBtn); fail = (Spinner)view.findViewById(R.id.fail_chooser); dao = new PractiseDAO(getActivity()); /** * set score to 0, if test is not completed, * else set the correct score * */ fail.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Log.v("Item picked", arg2+""); if(arg2!=0){ poeng.setText("Poengsum: 0"); }else{ poeng.setText("Poengsum: "+test.getScore()); } } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }); /** * onClick for the finish button: save results to dao */ finishBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(fail.getSelectedItemPosition() != 0) test.failed(true); dao.open(); dao.insertSPPB(test); Patient patient = dao.getPatient(test.getPatientId()); dao.close(); // getFragmentManager().popBackStack(getFragmentManager().findFragmentByTag("patient").getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE); getFragmentManager().popBackStack(); getFragmentManager().popBackStack(); getFragmentManager().popBackStack(); getFragmentManager().beginTransaction().replace(R.id.content_frame, getFragmentManager().findFragmentByTag("patient")).commit(); } }); return view; } }
public class Apotek { public String nama; public String alamat; public String[] obat; public int[] harga; public Apotek(String nama, String alamat) { this.nama = nama; this.alamat = alamat; } public Apotek(String[] obat, int[] harga) { this.obat = obat; this.harga = harga; } public void listHarga() { System.out.println("OBAT | HARGA"); for (int i = 0; i < obat.length; i++) { System.out.printf("%2s%10d\n", obat[i], harga[i]); } } public void cetakBio() { System.out.println("Nama Pembeli: " + nama); System.out.println("Alamat: " + alamat); } public void listHarga(String[] item, int[] jumlah) { int i, j = 0, k; int total = 0; System.out.println("------------------------------"); System.out.printf("%s\t%s\t%s\t%s\n", "Obat", "Jumlah", "Harga", "Total"); for (i = 0; i < obat.length; i++, j++) { if (jumlah[i] == 0) { continue; } for (k = 0; k < obat.length; k++) { if (obat[k].equalsIgnoreCase(item[j])) { int tot = jumlah[i] * harga[k]; System.out.printf("%s\t%d\t%d\t%d\n", obat[k], jumlah[i], harga[k], tot); total += tot; } } } System.out.println("------------------------------"); System.out.println("Total Pembayaran:\t" + total); System.out.println("------------------------------"); } }
package com.internousdev.ecsite.action; import java.util.Map; import org.apache.struts2.interceptor.SessionAware; import com.internousdev.ecsite.dao.ItemCreateCompleteDAO; import com.opensymphony.xwork2.ActionSupport; public class ItemCreateCompleteAction extends ActionSupport implements SessionAware{ private Map<String,Object> session; private ItemCreateCompleteDAO itemCreateCompleteDAO = new ItemCreateCompleteDAO(); public String execute(){ itemCreateCompleteDAO.createItem( session.get("itemName").toString(), session.get("itemPrice").toString(), session.get("itemStock").toString()); return SUCCESS; } public Map<String,Object> getSession(){ return session; } public void setSession(Map<String,Object> session){ this.session = session; } }
package org.sinhro.ForeignLanguageCourses; import org.sinhro.ForeignLanguageCourses.domain.Request; import org.sinhro.ForeignLanguageCourses.repository.RequestRepository; import org.sinhro.ForeignLanguageCourses.service.ListenerService; import org.sinhro.ForeignLanguageCourses.service.NewRequestsGeneratorService; import org.sinhro.ForeignLanguageCourses.service.RequestsHandlerService; import org.sinhro.ForeignLanguageCourses.service.StatisticService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; @Component public class MainProcess { private Logger log = LoggerFactory.getLogger(MainProcess.class); @Autowired private StatisticService statisticService; @Autowired private RequestRepository requestRepository; @Autowired private ListenerService listenerService; @Autowired private NewRequestsGeneratorService newRequestsGeneratorService; @Autowired private RequestsHandlerService requestsHandlerService; public void weekTick() { statisticService.startNewWeek(); log.info(""); log.info("_____________________________"); log.info("Неделя номер " + statisticService.getCurrentWeek()); log.info("-----------------------------"); //новые заявки newRequestsGeneratorService.generate(); //Все имеющиеся на текущий момент заявки (новые + необработанные с прошлого раза) List<Request> requests = requestRepository.findAll(); //Обработаем заявки List<Request> handledRequests = requestsHandlerService.handleRequests(requests); for (Request hReq : handledRequests) { requestRepository.delete(hReq); } //удаляем уже отучившихся слушателей listenerService.removeFinishedListeners(); //Просчёт оплаты следующего периода обучения statisticService.endWeek(); } public void end() { // log.info("Общая выручка : " + ); } /** * ### Общий алгоритм на тик ### * * * * Сгенерировать новые заявки * Обработать ВСЕ заявки (в т.ч. с прошлого тика) * Распределим слушателей из заявок в старые группы/создав новые группы(курсы) * Собрать выручку за следующий период со всех слушателей * Убрать слушателей, которые закончили курс * */ }
package net.sf.throughglass; import android.app.Application; import net.sf.throughglass.utils.AndroidLogWritterImpl; import net.sf.throughglass.utils.ApplicationContext; import ye2libs.utils.Log; /** * Created by guang_hik on 14-7-31. */ public class TApplication extends Application { @Override public void onCreate() { super.onCreate(); // set up application context ApplicationContext.setContext(this); // set up log writer for android Log.writter = new AndroidLogWritterImpl(); } }
package com.citibank.ods.modules.product.broker.action; import com.citibank.ods.common.action.BaseODSDetailAction; import com.citibank.ods.common.functionality.BaseFnc; import com.citibank.ods.common.functionality.valueobject.BaseFncVO; import com.citibank.ods.modules.product.broker.functionality.BrokerDetailFnc; import com.citibank.ods.modules.product.broker.functionality.valueobject.BrokerDetailFncVO; /** * @author Hamilton Matos * */ public class BrokerDetailAction extends BaseODSDetailAction { /* * Parte do nome do módulo ou ação */ private static final String C_SCREEN_NAME = "Broker.BrokerDetail"; /** * @see com.citibank.ods.commom.action.BaseAction#getFncVOPublishName() */ public String getFncVOPublishName() { return BrokerDetailFncVO.class.getName(); } /* * (non-Javadoc) * @see com.citibank.ods.common.action.BaseODSAction#getODSFuncionality() */ protected BaseFnc getFuncionality() { return new BrokerDetailFnc(); } /* * (non-Javadoc) * @see com.citibank.ods.common.action.BaseODSAction#getScreenName() */ protected String getScreenName() { return C_SCREEN_NAME; } /* * (non-Javadoc) * @see com.citibank.ods.common.action.BaseODSAction#extraActions(com.citibank.ods.common.functionality.valueobject.BaseFncVO, * java.lang.String) */ protected String extraActions( BaseFncVO fncVO_, String invokePath_ ) { return null; } }
import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.stream.Collectors; /** * @author Brennan Ward * * The escape pods problem states that given a set of entrances and exits, and the path, we need to find the max throughput. * This is an example of a Maximum Flow Problem. However, the sources and the sink are broken up, so they need to be merged. * We also need to actually make the path into a graph for use. * * Once we have the graph, we can use the Ford-Fulkerson method via the Edmonds-Karp algorithm. * We also have the option of Dinic's algorithm, but that is harder to implement. */ public class EscapePods { public static int solution(int[] entrances, int[] exits, int[][] path) { Room[] graph = buildGraph(toList(entrances), toList(exits), path); Connection[] augPath; int flow = 0; while ((augPath = findPath(graph)) != null) { Connection c = augPath[graph.length - 1]; int flowConsumed = 1000000; while (c != null) { flowConsumed = Math.min(c.capacity - c.flow, flowConsumed); c = augPath[c.src]; } c = augPath[graph.length - 1]; while (c != null) { c.addFlow(flowConsumed); c = augPath[c.src]; } flow += flowConsumed; } return flow; } /** * Creates the undirected graph given the input data. * Creates a supersource and supersink that each have infinite (max int) flow to the true entrances/exits. * That is, the supersource has infinite flow to each entrance, * and the supersink has infinite flow from each exit. */ public static Room[] buildGraph(List<Integer> entrances, List<Integer> exits, int[][] path) { Room[] rooms = new Room[path.length + 2]; for (int i = 0; i < rooms.length; i++) { rooms[i] = new Room(i); } for (int i : entrances) { //Connect from Supersource to "real" entrances. makeConnection(rooms, rooms[0], i + 1, 1000000); } for (int i = 0; i < path.length; i++) { Room room = rooms[i + 1]; int[] connections = path[i]; for (int k = 0; k < connections.length; k++) { int dest = k + 1; int capacity = connections[k]; if (capacity <= 0) continue; makeConnection(rooms, room, dest, capacity); } } for (int i : exits) { //Connect from "real" exits to Supersink. makeConnection(rooms, rooms[i + 1], rooms.length - 1, 1000000); } return rooms; } /** * Creates a connection between src and dest. * Also handles creation of the reverse connection (with capacity zero), * and the link of the reverse and forward connections. */ public static void makeConnection(Room[] rooms, Room src, int dest, int capacity) { Connection forward = new Connection(src.id, dest, capacity); Connection rev = new Connection(dest, src.id, 0); forward.reverse = rev; rev.reverse = forward; src.connections.add(forward); rooms[dest].connections.add(rev); } /** * BFS method to find an augmenting path in the residual graph. * The main graph is actually the same thing as the residual graph, * as all connections hold their current flow. * @return The augmenting path, as an array of edges. */ public static Connection[] findPath(Room[] graph) { Queue<Room> queue = new LinkedList<>(); Connection[] path = new Connection[graph.length]; //Path array, which holds the backtrack of the paths. queue.add(graph[0]); while (!queue.isEmpty()) { Room room = queue.poll(); for (Connection c : room.connections) { Room n = graph[c.dest]; if (n.id != 0 && path[n.id] == null && c.capacity - c.flow > 0) { path[n.id] = c; queue.add(n); if (n.id == graph.length - 1) return path; //We've found the sink, exit. } } } return null; } static List<Integer> toList(int[] arr) { return Arrays.stream(arr).boxed().collect(Collectors.toList()); } public static class Room { final int id; int level = Integer.MAX_VALUE; List<Connection> connections = new ArrayList<>(); public Room(int id) { this.id = id; } } public static class Connection { final int src, dest, capacity; int flow = 0; Connection reverse; public Connection(int src, int dest, int capacity) { this.src = src; this.dest = dest; this.capacity = capacity; } public void addFlow(int flow) { if (this.flow + flow > capacity) throw new RuntimeException("Connection Flow Exceeded!"); this.flow += flow; this.reverse.flow -= flow; } } }
package fj.swsk.cn.eqapp.util; import android.content.Context; import android.os.Environment; import android.text.TextUtils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class FileUtils { public static boolean isReadableFile(File file) { return file != null && !file.isDirectory() && file.canRead(); } public static boolean isSystemFile(File file) { return !(file.isFile() || file.isDirectory()); } public static File newFile(String parent, String name) { File dir = new File(parent); if (!dir.exists()) dir.mkdirs(); File file = new File(dir, name); return file; } // formatFileSize public static String formatFileSize(long length) { String result = null; int sub_string = 0; if (length >= 1073741824) { sub_string = String.valueOf((float) length / 1073741824).indexOf( "."); result = ((float) length / 1073741824 + "000").substring(0, sub_string + 3) + " G"; } else if (length >= 1048576) { sub_string = String.valueOf((float) length / 1048576).indexOf("."); result = ((float) length / 1048576 + "000").substring(0, sub_string + 3) + " M"; } else if (length >= 1024) { sub_string = String.valueOf((float) length / 1024).indexOf("."); result = ((float) length / 1024 + "000").substring(0, sub_string + 3) + " K"; } else if (length < 1024) result = Long.toString(length) + " B"; return result; } public static String formatFileSize2(long length){ String[] unit = {"B","K","M","G","T"}; int idx = 0; double len = length; while (len>1000&&idx<unit.length-1){ len/=1000.0; idx+=1; } return String.format("%.2f"+unit[idx],len); } // getFileTypeName public static String getFileTypeName(File file) { return file.isDirectory() ? "文件夹" : file.isFile() ? "普通文件" : "系统文件"; } // getApplicationRootDir public static File getApplicationRootDir(Context context) { if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { return context.getExternalFilesDir(null).getParentFile(); } else { return context.getFilesDir().getParentFile(); } } // getDataDir public static File getDataDir() { if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { return new File(Environment.getExternalStorageDirectory().getPath() + File.separator + "Android" + File.separator + "src/data"); } else { return new File(Environment.getDataDirectory().getPath() + File.separator + "src/data"); } } // mkDir public static int mkDir(File parent, String filename) { if (parent == null || !parent.exists() || !parent.isDirectory() || !parent.canWrite() || TextUtils.isEmpty(filename)) return 0; File file = new File(parent.getPath() + File.separator + filename); if (file.exists()) return -1; if (file.mkdirs()) return 1; return 0; } // createNewFile public static int createNewFile(File parent, String filename) throws IOException { if (parent == null || !parent.exists() || !parent.isDirectory() || !parent.canWrite() || TextUtils.isEmpty(filename)) return 0; File file = new File(parent.getPath() + File.separator + filename); if (file.exists()) return -1; if (file.createNewFile()) return 1; return 0; } // deleteFileRecursively public static boolean deleteFileRecursively(File file, boolean retainDir) { if (!file.exists()) return true; boolean b = true; if (file.isDirectory()) { File[] files = file.listFiles(); for (int i = 0; files != null && i < files.length; i++) { b &= deleteFileRecursively(files[i], false); } if (!retainDir) b &= file.delete(); } else { return file.delete(); } return b; } public static String getSDPath() { File sdDir = null; boolean sdCardExist = Environment.getExternalStorageState() .equals(android.os.Environment.MEDIA_MOUNTED); //判断sd卡是否存在 if (sdCardExist) { sdDir = Environment.getExternalStorageDirectory();//获取跟目录 return sdDir.toString(); } return null; } public static boolean isFileExists(String filePath) { if (filePath == null || filePath.trim().isEmpty()) { return false; } File file = new File(filePath); return file.exists(); } public static void CopyAssets(Context context, String assetDir, String dir) throws IOException { String[] files; files = context.getResources().getAssets().list(assetDir); File mWorkingPath = new File(dir); // if this directory does not exists, make one. if (!mWorkingPath.exists()) { if (!mWorkingPath.mkdirs()) { } } for (int i = 0; i < files.length; i++) { InputStream in = null; OutputStream out = null; try { String fileName = files[i]; // we make sure file name not contains '.' to be a folder. if (!fileName.contains(".")) { if (0 == assetDir.length()) { CopyAssets(context, fileName, dir + fileName + "/"); } else { CopyAssets(context, assetDir + "/" + fileName, dir + fileName + "/"); } continue; } File outFile = new File(mWorkingPath, fileName); if (outFile.exists()) outFile.delete(); if (0 != assetDir.length()) in = context.getAssets().open(assetDir + "/" + fileName); else in = context.getAssets().open(fileName); out = new FileOutputStream(outFile); // Transfer bytes from in to out byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } } }
package com.soa.repository.def; import com.soa.domain.hero.Hero; import java.util.Comparator; public abstract class HeroRepository<H extends Hero> extends AbstractRepository<H> { protected HeroRepository(Class<H> type) { super(type); } public abstract H findReachest(); public H findStrongest() { return findAll().stream() .max(Comparator.comparing(h -> h.getPower().getIntValue())) .orElse(null); } }
package cn.com.signheart.common.reflation; import java.sql.Timestamp; import java.util.*; public class ClassTypeUtil { public static final int INTEGER = 0; public static final int FLOAT = 1; public static final int DOUBLE = 2; public static final int BIGDECIMAL = 3; public static final int BOOLEAN = 4; public static final int STRING = 5; public static final int DATE_SQL = 6; public static final int TIMESTAMP = 7; public static final int SYBASETIME = 8; public static final int LONG = 9; public static final int DATE_UTIL = 10; public static final int Byte = 11; public static final int COLLECTION = 12; public static final int LIST = 13; public static final int MAP = 14; public static final int SET = 15; public static final int INPUTSTREAM = 16; private static final HashMap map = new HashMap(); static { map.put("java.lang.Integer", String.valueOf(0)); map.put("java.lang.Float", String.valueOf(1)); map.put("java.lang.Double", String.valueOf(2)); map.put("java.math.BigDecimal", String.valueOf(3)); map.put("java.lang.Boolean", String.valueOf(4)); map.put("java.lang.String", String.valueOf(5)); map.put("java.sql.Date", String.valueOf(6)); map.put("java.util.Date", String.valueOf(10)); map.put("java.sql.Timestamp", String.valueOf(7)); map.put("com.sybase.jdbc2.tds.SybTimestamp", String.valueOf(8)); map.put("java.lang.Long", String.valueOf(9)); map.put("java.lang.Byte", String.valueOf(11)); map.put("java.util.Collection", String.valueOf(12)); map.put("java.util.List", String.valueOf(13)); map.put("java.util.Map", String.valueOf(14)); map.put("java.util.Set", String.valueOf(15)); map.put("java.io.InputStream", String.valueOf(16)); } public ClassTypeUtil() { } public static int getTypeByClass(Class _cls) { return getTypeByClassName(_cls.getName()); } public static int getTypeByClass(String _clsName) { return getTypeByClassName(_clsName); } public static int getTypeByClassName(String _clsName) { String riv = (String)map.get(_clsName); return riv == null?-1:Integer.valueOf(riv).intValue(); } public static boolean isNumberType(Class _cls) { return isNumberType(_cls.getName()); } public static boolean isNumberType(String _clsName) { switch(getTypeByClass(_clsName)) { case 0: return true; case 1: return true; case 2: return true; case 3: return true; case 4: case 5: case 6: case 7: case 8: default: return false; case 9: return true; } } private static boolean checkType(Class cls, Class objCls) { if(cls.getName().equals(objCls.getName())) { return true; } else { Class[] ifCls = objCls.getInterfaces(); if(ifCls != null && ifCls.length > 0) { Class[] var6 = ifCls; int var5 = ifCls.length; for(int var4 = 0; var4 < var5; ++var4) { Class icls = var6[var4]; if(icls.getName().equals(cls.getName())) { return true; } if(icls.getSuperclass() != null) { objCls = objCls.getSuperclass(); boolean tempBl = checkType(cls, objCls); if(tempBl) { return true; } } } } if(objCls.getSuperclass() != null) { objCls = objCls.getSuperclass(); return checkType(cls, objCls); } else { return false; } } } public static boolean isList(Class cls) { return checkType(List.class, cls); } public static boolean isCollection(Class cls) { return checkType(Collection.class, cls); } public static boolean isMap(Class cls) { return checkType(Map.class, cls); } public static boolean isSet(Class cls) { return checkType(Set.class, cls); } public static boolean isString(Class cls) { return checkType(String.class, cls); } public static boolean isData(Class<? extends Object> cls) { return checkType(Date.class, cls) || checkType(java.sql.Date.class, cls) || checkType(Timestamp.class, cls); } }
package com.lviv.football.constants; /** * Created by rudnitskih on 4/14/17. */ public interface Columns { String code = "code"; String from = "from"; String to = "to"; String eventTime = "eventTime"; String stadion = "stadion"; String startTime = "startTime"; String validationIssues = "validationIssues"; String team = "team"; String period = "period"; String actionDescription = "actionDescription"; }
package com.github.gaoyangthu.esanalysis.ebusi.impl; import java.util.Date; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.gaoyangthu.esanalysis.ebusi.AccountAnalyser; import com.github.gaoyangthu.esanalysis.ebusi.bean.AccountMeta; import com.github.gaoyangthu.esanalysis.ebusi.service.AccountService; import com.github.gaoyangthu.esanalysis.ebusi.service.impl.AccountServiceImpl; import com.github.gaoyangthu.esanalysis.hbase.service.UserIdService; import com.github.gaoyangthu.esanalysis.hbase.service.impl.UserIdServiceImpl; /** * Created with IntelliJ IDEA. * Author: gaoyangthu * Date: 14-3-12 * Time: 下午3:12 */ public class AccountAnalyserImpl implements AccountAnalyser { private static final Logger LOGGER = LoggerFactory.getLogger(AccountAnalyserImpl.class); private AccountService accountService; private UserIdService userIdService; public AccountAnalyserImpl() { accountService = new AccountServiceImpl(); userIdService = new UserIdServiceImpl(); } @Override public boolean analyseAccount(Date beginDate, Date endDate) { boolean flag = false; List<AccountMeta> accounts = accountService.findByDate(beginDate, endDate); if(accounts == null) { return false; } for (AccountMeta account : accounts) { if (account != null) { boolean f = processAccount(account); if (!f) { LOGGER.error("Get bdUserUuid error. accountId={}", account.getAccountId()); } } flag = true; } return flag; } private boolean processAccount(AccountMeta account) { String accountId = account.getAccountId(); String bdUserUuid = userIdService.getBdUserUuid(null, null, accountId); LOGGER.debug("Get bdUserUuid. bdUserUuid={}, accountId={}", bdUserUuid, accountId); return StringUtils.isNotBlank(bdUserUuid); } }
package com.kj_project.whereareyou.utils; public interface NumDialogListener { public void onPositiveClick(String number); public void onNegativeClick(); }
// SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org) package org.xbill.DNS; import java.io.IOException; /** * Next SECure name - this record contains the following name in an ordered list of names in the * zone, and a set of types for which records exist for this name. The presence of this record in a * response signifies a negative response from a DNSSEC-signed zone. * * <p>This replaces the NXT record. * * @author Brian Wellington * @author David Blacka * @see <a href="https://tools.ietf.org/html/rfc4034">RFC 4034: Resource Records for the DNS * Security Extensions</a> */ public class NSECRecord extends Record { private Name next; private TypeBitmap types; NSECRecord() {} /** * Creates an NSEC Record from the given data. * * @param next The following name in an ordered list of the zone * @param types An array containing the types present. */ public NSECRecord(Name name, int dclass, long ttl, Name next, int[] types) { super(name, Type.NSEC, dclass, ttl); this.next = checkName("next", next); for (int value : types) { Type.check(value); } this.types = new TypeBitmap(types); } @Override protected void rrFromWire(DNSInput in) throws IOException { next = new Name(in); types = new TypeBitmap(in); } @Override protected void rrToWire(DNSOutput out, Compression c, boolean canonical) { // Note: The next name is not lowercased. next.toWire(out, null, false); types.toWire(out); } @Override protected void rdataFromString(Tokenizer st, Name origin) throws IOException { next = st.getName(origin); types = new TypeBitmap(st); } /** Converts rdata to a String */ @Override protected String rrToString() { StringBuilder sb = new StringBuilder(); sb.append(next); if (!types.empty()) { sb.append(' '); sb.append(types.toString()); } return sb.toString(); } /** Returns the next name */ public Name getNext() { return next; } /** Returns the set of types defined for this name */ public int[] getTypes() { return types.toArray(); } /** Returns whether a specific type is in the set of types. */ public boolean hasType(int type) { return types.contains(type); } }
package practico15_bdd.steps; import cucumber.api.java.en.And; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; public class LinkedinSteps { @Given("^estoy en la pagina de linkedin$") public void estoy_en_la_pagina_de_linkedin() throws Throwable { // Write code here that turns the phrase above into concrete actions System.out.println("entro en el linkedin"); } @When("^ingreso mi email correctamente$") public void ingreso_mi_email_correctamente() throws Throwable { // Write code here that turns the phrase above into concrete actions System.out.println("ingreso el email correctamente"); } @And("^ingreso mi contrasena correctamente$") public void ingreso_mi_contrasena_correctamente() throws Throwable { // Write code here that turns the phrase above into concrete actions System.out.println("ingreso la contraseņa correctamente"); } @Then("^entro a la cuenta$") public void entro_a_la_cuenta() throws Throwable { // Write code here that turns the phrase above into concrete actions System.out.println("entro en mi cuenta"); } @When("^ingreso mi email incorrectamente$") public void ingreso_mi_email_incorrectamente() throws Throwable { // Write code here that turns the phrase above into concrete actions System.out.println("ingreso el email mal"); } @Then("^se despliega un error de login$") public void se_despliega_un_error_de_login() throws Throwable { // Write code here that turns the phrase above into concrete actions System.out.println("KO login"); } @And("^ingreso mi contrasena incorrectamente$") public void ingreso_mi_contrasena_incorrectamente() throws Throwable { // Write code here that turns the phrase above into concrete actions System.out.println("contraseņa mal"); } @Then("^se despliega un error de login \"([^\"]*)\"$") public void se_despliega_un_error_de_login(String arg1) throws Throwable { // Write code here that turns the phrase above into concrete actions System.out.println("mostrar "+ arg1); } }
//Lonnie Williams //Jump Training import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class arraySwap { public static final <T> void swap (T[] a, int i, int j) { T t = a[i]; a[i] = a[j]; a[j] = t; } public static final <T> void swap (List<T> l, int i, int j) { Collections.<T>swap(l, i, j); } private static void test() { String [] a = {"Adios", "Buenas Noches", "Good Afternoon"}; swap(a, 0, 1); System.out.println(Arrays.toString(a)); List<String> l = new ArrayList<String>(Arrays.asList(a)); swap(l, 0, 1); swap(l, 0, 2); System.out.println(l); } public static void main(String...args) { test(); } }
package etl; /** * Klasa sluzaa do zarzadzanie przebiegiem procesu ETL */ public class ETLManager { /** * ID produktu */ private String productId; /** * Parsuje i przechowuje informacje o produkcie oraz opinie */ private Product product; /** * Pobiera strony HTTP z informacjami o produkcie i opiniami * oraz zapisuje w pamięci * @throws Exception Blad polaczenia */ public void extract() throws Exception{ product = new Product(productId); GUI.printText("Pobieram dane dla id: "+productId+"..."); product.downloadProductPage(); product.downloadReviewPages(); GUI.printText(product.getCounter()+" plikow zostalo pobranych"); } /** * Przeksztalca pobrane dane */ public void transform(){ product.createReviewsArray(); product.parseReviews(); product.parseProduct(); GUI.printText("Dane zostaĹ‚y przeksztaĹ‚cone"); } /** * Wczytuje przeksztalcone dane do bazy danych * @throws Exception Blad polaczenia z baza danych */ public void load() throws Exception{ DatabaseManager dbManager = new DatabaseManager(product); dbManager.loadToDatabase(); // dbManager.print(); } /** * @return the productId */ public String getProductId() { return productId; } /** * @param productId the productId to set */ public void setProductId(String productId) { this.productId = productId; } /** * @return the product */ public Product getProduct() { return product; } }
package com.hackathon.lib; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import org.springframework.web.client.HttpServerErrorException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Crypto { public static String crypto(String text) { try { MessageDigest md = MessageDigest.getInstance("SHA-512"); md.update(text.getBytes(), 0, text.getBytes().length); return new BigInteger(1, md.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, "암호화 실패"); } } }
package com.example.administrator.panda_channel_app.MVP_Framework.module.home.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import com.example.administrator.panda_channel_app.MVP_Framework.modle.entity.HomeLightChinaBean; import com.example.administrator.panda_channel_app.R; import java.util.ArrayList; /** * Created by Administrator on 2017/7/14 0014. */ public class Home_LightChina_RecyclerAdapter extends RecyclerView.Adapter{ public interface setOnClickListener{ void setOnClickListener(View v,int position); } private setOnClickListener onClickListener; public void setOnClickListener(setOnClickListener onClickListener){ this.onClickListener=onClickListener; } private ArrayList<HomeLightChinaBean.ListBean> list; private Context context; public Home_LightChina_RecyclerAdapter(ArrayList<HomeLightChinaBean.ListBean> list, Context context) { this.list = list; this.context = context; } ViewHolder viewHolder; @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.home_panda_eye_viedorecycleritem,null); viewHolder=new ViewHolder(view); return viewHolder; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { viewHolder= (ViewHolder) holder; viewHolder.content.setText(list.get(position).getTitle()); viewHolder.data.setText(list.get(position).getDaytime()); viewHolder.time.setText(list.get(position).getVideoLength()); Glide.with(context).load(list.get(position).getImage()).into(viewHolder.img); viewHolder.homepaneye_linear.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onClickListener.setOnClickListener(v,position); } }); } @Override public int getItemCount() { return list.size(); } class ViewHolder extends RecyclerView.ViewHolder{ LinearLayout homepaneye_linear; ImageView img; TextView content; TextView data,time; public ViewHolder(View itemView) { super(itemView); homepaneye_linear= (LinearLayout) itemView.findViewById(R.id.homepaneye_linear); img= (ImageView) itemView.findViewById(R.id.home_landa_eye_viedeo_img); content= (TextView) itemView.findViewById(R.id.home_landa_eye_viedeo_title); data= (TextView) itemView.findViewById(R.id.home_landa_eye_viedeo_daytime); time= (TextView) itemView.findViewById(R.id.home_landa_eye_viedeo_time); } } }
package by.orion.onlinertasks.data.datasource.sections.remote; import android.support.annotation.NonNull; import javax.inject.Inject; import by.orion.onlinertasks.common.network.services.BaseService; import by.orion.onlinertasks.data.datasource.sections.SectionsDataSource; import by.orion.onlinertasks.data.models.sections.Section; import by.orion.onlinertasks.data.models.sections.Sections; import io.reactivex.Completable; import io.reactivex.Single; public class RemoteSectionsDataSource implements SectionsDataSource { @NonNull private final BaseService service; @Inject public RemoteSectionsDataSource(@NonNull BaseService service) { this.service = service; } @Override public Single<Integer> getValue(@NonNull Section key) { throw new UnsupportedOperationException(); } @Override public Completable setValue(@NonNull Section key, @NonNull Integer value) { throw new UnsupportedOperationException(); } @Override public Single<Sections> getSections() { return service.getSections(); } @Override public Single<Section> getSection(@NonNull Integer id) { return service.getSection(id); } @Override public Single<Sections> getSectionsWithCategories() { return service.getSectionsWithCategories(); } }
import java.util.Iterator; import java.util.List; public class TreeIterator<T> implements Iterator<Node<T>> { private List<Node<T>> tree; private int size; private int current; public TreeIterator(List<Node<T>> tree) { this.tree = tree; this.size = tree.size(); } @Override public boolean hasNext() { return current < size; } @Override public Node<T> next() { Node<T> ret = tree.get(current); current++; return ret; } }
/** * 香港理工大学-中国科学院研究生院数据挖掘-PageRank算法实现 * @author chaoyu * @right Copyright by PolyU team * @github https://github.com/yuchao86/pagerank.git * @date 2012-10-18 */ package polyu.gucas.rawPagerank.robot; /* * Tutorial 04: "Web Robots" * compile and run with LinkExtractor together with your own code. */ /** * This program parse the HTML files,look up for the href * store it into the external or internal iterator * @version jdk 1.6.0 */ import java.util.*; import javax.swing.text.*; import javax.swing.text.html.*; public class MyHtmlHrefHandler extends HTMLEditorKit.ParserCallback { public Set<String> extLinks = new HashSet<String>(); public Set<String> localLinks = new HashSet<String>(); //public String root; /*public MyHtmlHrefHandler(String url){ super(); root = url; } */ public MyHtmlHrefHandler(){ super(); } public void reset(){ extLinks.clear(); localLinks.clear(); } /* public static String eraseStr(String surl){ if(surl.indexOf("/") != 0 ){ surl = "/" + surl; } if(surl.length() >= 1 && surl.charAt(surl.length()-1)=='/'){ surl = surl.substring(0, surl.length()-1); } return surl; } */ // This method is inherited from the super class // HTMLEditorKit.ParserCallback public void handleStartTag( HTML.Tag tag, MutableAttributeSet attributes, int pos) { //If the element is not a link, i.e.: Not <A HREF="...">...</A> //Then ignore it if(!(tag.equals(HTML.Tag.A))){ return; } // If the element is <A HREF="hello.html">Hello</a> // Then link="hello.html" String link=(String) attributes.getAttribute(HTML.Attribute.HREF); if(link==null||link.length()==0)return; if(link.length()>=4&&link.substring(0,4).equalsIgnoreCase("http")){ // An external link is like "http://www.google.com/" extLinks.add(link); }else{ // An internal link is like "/~cs5286/index.html" //link = eraseStr(link); localLinks.add(link); } } }
package yinq.situation.dataModel; /** * Created by YinQ on 2018/11/29. */ public class MealSituationDetModel extends SituationDetModel { private int code; private int speed; private int amount; private int feed; private float score; public MealSituationDetModel(){ } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public int getSpeed() { return speed; } public void setSpeed(int speed) { this.speed = speed; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } public int getFeed() { return feed; } public void setFeed(int feed) { this.feed = feed; } public float getScore() { return score; } public void setScore(float score) { this.score = score; } }
/* Copyright (C) 2013-2014, Securifera, Inc All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Securifera, Inc nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================================================ Pwnbrew is provided under the 3-clause BSD license above. The copyright on this package is held by Securifera, Inc */ package pwnbrew.functions; import java.awt.Component; import java.awt.Image; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.swing.JList; import pwnbrew.MaltegoStub; import pwnbrew.StubConfig; import pwnbrew.log.LoggableException; import pwnbrew.manager.DataManager; import pwnbrew.misc.Constants; import pwnbrew.misc.CountSeeker; import pwnbrew.misc.DebugPrinter; import pwnbrew.misc.HostHandler; import pwnbrew.utilities.SocketUtilities; import pwnbrew.misc.Utilities; import pwnbrew.network.ClientPortRouter; import pwnbrew.network.control.messages.AutoSleep; import pwnbrew.network.control.messages.CheckInTimeMsg; import pwnbrew.network.control.messages.ClearSessions; import pwnbrew.network.control.messages.ControlMessage; import pwnbrew.network.control.messages.GetCheckInSchedule; import pwnbrew.network.control.messages.GetCount; import pwnbrew.network.control.messages.GetSessions; import pwnbrew.network.control.messages.RemoveHost; import pwnbrew.sessions.SessionJFrameListener; import pwnbrew.sessions.SessionsJFrame; import pwnbrew.xml.maltego.Field; import pwnbrew.xml.maltego.MaltegoTransformExceptionMessage; import pwnbrew.xml.maltego.custom.Host; /** * * @author Securifera */ public class ToSessionManager extends Function implements SessionJFrameListener, HostHandler, CountSeeker { private static final String NAME_Class = MaltegoStub.class.getSimpleName(); private volatile boolean notified = false; private final List<Host> theHostList = new ArrayList<>(); private volatile int theClientCount = 0; private SessionsJFrame theSessionsJFrame = null; //================================================================== /** * Constructor * @param passedManager */ public ToSessionManager( MaltegoStub passedManager ) { super(passedManager); } //=================================================================== /** * * @param passedObjectStr */ @Override public void run(String passedObjectStr) { String retStr = ""; Map<String, String> objectMap = getKeyValueMap(passedObjectStr); //Get server IP String serverIp = objectMap.get( Constants.SERVER_IP); if( serverIp == null ){ DebugPrinter.printMessage( NAME_Class, "ToSessionManager", "No pwnbrew server IP provided", null); return; } //Get server port String serverPortStr = objectMap.get( Constants.SERVER_PORT); if( serverPortStr == null ){ DebugPrinter.printMessage( NAME_Class, "ToSessionManager", "No pwnbrew server port provided", null); return; } StubConfig theConfig = StubConfig.getConfig(); theConfig.setServerIp(serverIp); theConfig.setSocketPort(serverPortStr); Integer anInteger = SocketUtilities.getNextId(); theConfig.setHostId(anInteger.toString()); int serverPort = Integer.parseInt( serverPortStr); ClientPortRouter aPR = (ClientPortRouter) theManager.getPortRouter( serverPort ); if(aPR == null){ try { aPR = (ClientPortRouter)DataManager.createPortRouter(theManager, serverPort, true); } catch (IOException ex) { DebugPrinter.printMessage( NAME_Class, "to_session_mgr", "Unable to create port router.", ex); return; } } theManager.initialize(); try { aPR.ensureConnectivity( serverPort, theManager ); //Get the client count ControlMessage aMsg = new GetCount( Constants.SERVER_ID, GetCount.HOST_COUNT, "0" ); DataManager.send( theManager, aMsg); //Wait for the response waitToBeNotified( 180 * 1000); //Get the client info if( theClientCount > 0 ){ //Get each client msg aMsg = new pwnbrew.network.control.messages.GetHosts( Constants.SERVER_ID, "0" ); DataManager.send( theManager, aMsg); //Wait for the response waitToBeNotified( 180 * 1000); if( theClientCount == 0 ){ //Create the file browser frame theSessionsJFrame = new SessionsJFrame( this, theHostList ); //Set to the first element JList hostList = theSessionsJFrame.getHostJList(); if( hostList.getModel().getSize() > 0) hostList.setSelectedIndex(0); //Set the title theSessionsJFrame.setTitle("Session Manager - "+serverIp); //Set the icon Image appIcon = Utilities.loadImageFromJar( Constants.SCHEDULE_IMG_STR ); if( appIcon != null ) theSessionsJFrame.setIconImage( appIcon ); //Pack and show theSessionsJFrame.setVisible(true); //Wait to be notified waitToBeNotified(); } } } catch( LoggableException ex ) { //Create a relay object pwnbrew.xml.maltego.Exception exMsg = new pwnbrew.xml.maltego.Exception( ex.getMessage() ); MaltegoTransformExceptionMessage malMsg = theReturnMsg.getExceptionMessage(); //Create the message list malMsg.getExceptionMessages().addExceptionMessage(exMsg); } } //======================================================================== /** * * @return */ @Override public Component getParentComponent(){ return null ; } // ========================================================================== /** * Causes the calling {@link Thread} to <tt>wait()</tt> until notified by * another. * <p> * <strong>This method most certainly "blocks".</strong> * @param anInt */ protected synchronized void waitToBeNotified( Integer... anInt ) { while( !notified ) { try { //Add a timeout if necessary if( anInt.length > 0 ){ wait( anInt[0]); break; } else { wait(); //Wait here until notified } } catch( InterruptedException ex ) { } } notified = false; } //=============================================================== /** * Notifies the thread */ @Override public synchronized void beNotified() { notified = true; notifyAll(); } //=============================================================== /** * * @param passedHostId * @param selected * @param passedOperation */ @Override public void setAutoSleepFlag( int passedHostId, boolean selected, byte passedOperation ) { if( passedOperation == AutoSleep.SET_VALUE ){ //Get flag and send a msg AutoSleep anASMsg = new AutoSleep( Constants.SERVER_ID, passedHostId, passedOperation, selected ); DataManager.send( theManager, anASMsg); } else if(passedOperation == AutoSleep.GET_VALUE){ //If it is the selected host if(theSessionsJFrame.isSelectedHost(passedHostId)) theSessionsJFrame.setAutoSleepCheckbox(selected); } } //=============================================================== /** * * @param passedHostId */ @Override public void clearSessionList( String passedHostId ) { //Send message to server to clear the session list ControlMessage aMsg = new ClearSessions( Constants.SERVER_ID, passedHostId); DataManager.send( theManager, aMsg); theSessionsJFrame.repaint(); } //=============================================================== /** * * @param aDate * @param newDateStr */ @Override public void replaceDate(String aDate, String newDateStr) { //Get currently selected host JList hostJList = theSessionsJFrame.getHostJList(); Object anObj = hostJList.getSelectedValue(); if( anObj != null && anObj instanceof Host ){ Host aHost = (Host)anObj; Field hostIdField = aHost.getField( Constants.HOST_ID ); String hostIdStr = hostIdField.getXmlObjectContent(); //Check if they are equal int hostId = Integer.parseInt(hostIdStr); //Send message to server to clear the session list try { CheckInTimeMsg aMsg = new CheckInTimeMsg( Constants.SERVER_ID, hostId, newDateStr, CheckInTimeMsg.REPLACE_TIME ); aMsg.addPrevCheckIn(aDate); DataManager.send( theManager, aMsg); } catch (UnsupportedEncodingException ex) { } //refresh refreshSelection(); } } //=============================================================== /** * */ @Override public void refreshSelection() { JList hostJList = theSessionsJFrame.getHostJList(); int selIndex = hostJList.getSelectedIndex(); hostJList.clearSelection(); hostJList.setSelectedIndex(selIndex); } //=============================================================== /** * */ @Override public void removeCheckInDates() { //Get currently selected host JList hostJList = theSessionsJFrame.getHostJList(); Object anObj = hostJList.getSelectedValue(); if( anObj != null && anObj instanceof Host ){ Host aHost = (Host)anObj; Field hostIdField = aHost.getField( Constants.HOST_ID ); String hostIdStr = hostIdField.getXmlObjectContent(); //Check if they are equal int hostId = Integer.parseInt(hostIdStr); //Get selected check-in time list JList checkInTimeList = theSessionsJFrame.getCheckInJList(); List<String> theDatesToRemove = new ArrayList<>(checkInTimeList.getSelectedValuesList()); //Remote the dates try { for( String aStr : theDatesToRemove ){ CheckInTimeMsg aMsg = new CheckInTimeMsg( Constants.SERVER_ID, hostId, aStr, CheckInTimeMsg.REMOVE_TIME ); DataManager.send( theManager, aMsg); } } catch (UnsupportedEncodingException ex) { } //refresh refreshSelection(); } } //=============================================================== /** * * @param countType * @param optionalHostId */ @Override public synchronized void setCount(int passedCount, int countType, int optionalHostId ) { switch( countType){ case GetCount.HOST_COUNT: theClientCount = passedCount; break; } beNotified(); } //=============================================================== /** * * @param aHost */ @Override public synchronized void addHost(Host aHost) { theHostList.add(aHost); //Decrement and see if we are done theClientCount--; if( theClientCount == 0) beNotified(); } //=============================================================== /** * * @param hostIdStr */ @Override public void hostSelected(String hostIdStr) { //Send a msg to get the sessions int hostId = Integer.parseInt(hostIdStr); ControlMessage aMsg = new GetSessions( Constants.SERVER_ID, hostId); DataManager.send( theManager, aMsg); //Send a msg to get the checkins aMsg = new GetCheckInSchedule( Constants.SERVER_ID, hostId); DataManager.send( theManager, aMsg); } //=============================================================== /** * Add the check in time * * @param hostId * @param checkInDatStr */ public void addCheckInTime(int hostId, String checkInDatStr) { if( theSessionsJFrame != null ) theSessionsJFrame.addCheckInDate(hostId, checkInDatStr); } //=============================================================== /** * Add the session * * @param hostId * @param checkInDatStr * @param checkOutDatStr */ public void addSession(int hostId, String checkInDatStr, String checkOutDatStr) { if( theSessionsJFrame != null ) theSessionsJFrame.addSession( hostId, checkInDatStr, checkOutDatStr); } //=============================================================== /** * Remove the passed host * * @param passedHost */ @Override public void removeHost(Host passedHost) { //Send a msg to remove the host int hostId = Integer.parseInt( passedHost.getField(Constants.HOST_ID).getXmlObjectContent() ); ControlMessage aMsg = new RemoveHost( Constants.SERVER_ID, hostId); DataManager.send( theManager, aMsg); } }
/* * Copyright (c) 2013-2014, Neuro4j.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.neuro4j.studio.core.diagram.navigator; import org.eclipse.core.runtime.IAdapterFactory; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.PlatformObject; import org.eclipse.ui.views.properties.tabbed.ITabbedPropertySheetPageContributor; /** * @generated */ public abstract class Neuro4jAbstractNavigatorItem extends PlatformObject { /** * @generated */ static { final Class[] supportedTypes = new Class[] { ITabbedPropertySheetPageContributor.class }; final ITabbedPropertySheetPageContributor propertySheetPageContributor = new ITabbedPropertySheetPageContributor() { public String getContributorId() { return "org.neuro4j.studio.core.diagram"; //$NON-NLS-1$ } }; Platform.getAdapterManager().registerAdapters( new IAdapterFactory() { public Object getAdapter(Object adaptableObject, Class adapterType) { if (adaptableObject instanceof org.neuro4j.studio.core.diagram.navigator.Neuro4jAbstractNavigatorItem && adapterType == ITabbedPropertySheetPageContributor.class) { return propertySheetPageContributor; } return null; } public Class[] getAdapterList() { return supportedTypes; } }, org.neuro4j.studio.core.diagram.navigator.Neuro4jAbstractNavigatorItem.class); } /** * @generated */ private Object myParent; /** * @generated */ protected Neuro4jAbstractNavigatorItem(Object parent) { myParent = parent; } /** * @generated */ public Object getParent() { return myParent; } }
package com.energytrade.app.model; import java.io.Serializable; import javax.persistence.*; import java.util.Date; /** * The persistent class for the all_dr_notifications database table. * */ @Entity @Table(name="all_dr_notifications") @NamedQuery(name="AllDrNotification.findAll", query="SELECT a FROM AllDrNotification a") public class AllDrNotification implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name="notification_id") private int notificationId; @Column(name="action_id") private int actionId; @Column(name="created_by") private String createdBy; @Temporal(TemporalType.TIMESTAMP) @Column(name="created_ts") private Date createdTs; @Column(name="updated_by") private String updatedBy; @Temporal(TemporalType.TIMESTAMP) @Column(name="updated_ts") private Date updatedTs; //bi-directional many-to-one association to NotificationTypePl @ManyToOne @JoinColumn(name="notification_type") private NotificationTypePl notificationTypePl; //bi-directional many-to-one association to NotificationStatusPl @ManyToOne @JoinColumn(name="status") private NotificationStatusPl notificationStatusPl; //bi-directional many-to-one association to AllUser @ManyToOne @JoinColumn(name="user_id") private AllUser allUser; public AllDrNotification() { } public int getNotificationId() { return this.notificationId; } public void setNotificationId(int notificationId) { this.notificationId = notificationId; } public int getActionId() { return this.actionId; } public void setActionId(int actionId) { this.actionId = actionId; } public String getCreatedBy() { return this.createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public Date getCreatedTs() { return this.createdTs; } public void setCreatedTs(Date createdTs) { this.createdTs = createdTs; } public String getUpdatedBy() { return this.updatedBy; } public void setUpdatedBy(String updatedBy) { this.updatedBy = updatedBy; } public Date getUpdatedTs() { return this.updatedTs; } public void setUpdatedTs(Date updatedTs) { this.updatedTs = updatedTs; } public NotificationTypePl getNotificationTypePl() { return this.notificationTypePl; } public void setNotificationTypePl(NotificationTypePl notificationTypePl) { this.notificationTypePl = notificationTypePl; } public NotificationStatusPl getNotificationStatusPl() { return this.notificationStatusPl; } public void setNotificationStatusPl(NotificationStatusPl notificationStatusPl) { this.notificationStatusPl = notificationStatusPl; } public AllUser getAllUser() { return this.allUser; } public void setAllUser(AllUser allUser) { this.allUser = allUser; } }
package org.ohdsi.webapi.vocabulary; import java.util.Collection; import java.util.Objects; import org.ohdsi.circe.vocabulary.Concept; import org.ohdsi.webapi.service.VocabularyService; import org.ohdsi.webapi.util.PreparedStatementRenderer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class DatabaseSearchProvider implements SearchProvider { @Autowired VocabularyService vocabService; @Override public boolean supports(VocabularySearchProviderType type) { return Objects.equals(type, VocabularySearchProviderType.DATABASE); } @Override public Collection<Concept> executeSearch(SearchProviderConfig config, String query, String rows) throws Exception { PreparedStatementRenderer psr = vocabService.prepareExecuteSearchWithQuery(query, config.getSource()); return vocabService.getSourceJdbcTemplate(config.getSource()).query(psr.getSql(), psr.getSetter(), vocabService.rowMapper); } }
package kr.co.wisenut.login.controller; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import kr.co.wisenut.login.model.User; import kr.co.wisenut.login.service.LoginService; import kr.co.wisenut.util.StringUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/login") public class LoginController { private static final Logger logger = LoggerFactory.getLogger(LoginController.class); @Autowired LoginService loginService; @RequestMapping(value = "/page") public ModelAndView displayLogin(HttpSession session, ModelAndView mav){ if(session.getAttribute("loginInfo")!=null){ mav.setViewName("editor/viewVideo"); }else{ mav.setViewName("login/login"); } return mav; } @RequestMapping(value = "/loginOk") public void executeLogin(@ModelAttribute User loginInfo, HttpSession session, HttpServletResponse response){ boolean isValidUser = false; try{ isValidUser = loginService.isValidUser(loginInfo); if(isValidUser){ session.setAttribute("loginInfo", loginInfo); } response.getWriter().print(isValidUser); }catch(Exception e){ logger.error(StringUtil.getStackTrace(e)); } } @RequestMapping(value = "/logout") public String logout(HttpSession session){ session.setAttribute("loginInfo", null); return "redirect:/login/page"; } }
package com.state.light; /** * Created by Valentine on 2018/5/10. */ public class DarkState implements LightState{ @Override public void switchs(LightManager lightManager) { System.out.println("亮灯"); lightManager.state = new BrightState(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package graphicspackage; /** * * @author Zbynda */ public class GraphicsConstants { public final int ELEMENT_SIZE = 15; public final int LINE_WIDTH = 1; public final int AGENT_SIZE = 13; public final int AGENT_OUTLINE = 1; }
package com.gsccs.sme.plat.auth.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import com.gsccs.sme.plat.auth.model.Sms; import com.gsccs.sme.plat.auth.model.SmsExample; public interface SmsMapper { int countByExample(SmsExample example); int deleteByExample(SmsExample example); int deleteByPrimaryKey(Long id); int insert(Sms record); List<Sms> selectPageByExample(SmsExample example); Sms selectByPrimaryKey(Long id); int updateByExampleSelective(@Param("record") Sms record, @Param("example") SmsExample example); int updateByExample(@Param("record") Sms record, @Param("example") SmsExample example); int updateByPrimaryKeySelective(Sms record); int updateByPrimaryKey(Sms record); }
package com.cif.accumulate.server.service; /** * @Author: liuxincai * @Description: a baseService * @Date: 2019/5/24 18:24 */ public interface BaseService { }
/* * Copyright © 2018 www.noark.xyz All Rights Reserved. * * 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 ! * 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件: * * http://www.noark.xyz/LICENSE * * 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播; * 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本; * 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利; * 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明! */ package xyz.noark.game.bt; /** * 一种固定时间执行的节点. * * @author 小流氓[176543888@qq.com] * @since 3.4 */ public class FixedTimeNode extends AbstractDecoratorNode { /** * CD时间(单位:秒) */ private final int cd; /** * 下次可执行时间 */ private long nextExecTime; public FixedTimeNode(int cd) { this.cd = cd; } @Override public NodeState update() { final long now = System.currentTimeMillis(); if (now >= nextExecTime) { this.nextExecTime = now + cd * 1000; return node.update(); } return NodeState.FAILURE; } }
/* $Id$ */ package djudge.judge.dchecker; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.log4j.Logger; import utils.FileTools; import djudge.common.JudgeDirs; import djudge.judge.ProblemDescription; import djudge.judge.checker.CheckerResult; import djudge.judge.checker.Checker; public class LocalChecker { private static final Logger log = Logger.getLogger(LocalChecker.class); public static CheckerResult check(ValidatorTask task) { return check(task, null); } public static CheckerResult check(ValidatorTask task, String workDir) { if (workDir == null) { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss-SSS"); String id = dateFormat.format(new Date()) + "_val"; workDir = JudgeDirs.getWorkDir() + id + "/"; } FileTools.saveToFile(task.programOutput, workDir + "answer.txt"); try { ProblemDescription pd = new ProblemDescription(task.contestId, task.problemId); CheckerResult res = new Checker(pd.getTestValidator(task.groupNumber, task.testNumber)).validateOutput(task.testInput.filename, workDir + "answer.txt", task.testOutput.filename); return res; } catch (Exception e) { log.error("Unknown exception", e); } // TODO: delete this? // FileWorks.deleteFile(workDir + "answer.txt"); return null; } }
package exercises.chapter4.ex5; import static net.mindview.util.Print.print; import static net.mindview.util.Print.printnb; /** * @author Volodymyr Portianko * @date.created 04.03.2016 */ public class Exercise5 { static final int i1 = 0x45; static final int i2 = 0xFE; public static void main(String[] args) { printnb("i1 = "); toBinaryString(i1); printnb("i2 = "); toBinaryString(i2); printnb("i1 & i2 = "); toBinaryString(i1 & i2); printnb("i1 | i2 = "); toBinaryString(i1 | i2); printnb("i1 ^ i2 = "); toBinaryString(i1 ^ i2); } public static void toBinaryString(int i) { char[] buffer = new char[32]; int bufferPosition = 32; do { buffer[--bufferPosition] = ((i & 0x01) != 0) ? '1' : '0'; i >>>= 1; } while (i != 0); for(int j = bufferPosition; j < 32; j++) printnb(buffer[j]); print(); } }
package com.zensar.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.zensar.entity.ProductCategory; @Repository public interface ProductCategoryRepo extends JpaRepository<ProductCategory, Integer>{ ProductCategory findByCategoryName(String catName); }
// ********************************************************** // 1. 제 목: // 2. 프로그램명: CommunityMsPrBean.java // 3. 개 요: // 4. 환 경: JDK 1.3 // 5. 버 젼: 0.1 // 6. 작 성: Administrator 2003-08-29 // 7. 수 정: // // ********************************************************** package com.ziaan.community; import java.sql.PreparedStatement; import java.util.ArrayList; import com.ziaan.library.DBConnectionManager; import com.ziaan.library.DataBox; import com.ziaan.library.ErrorManager; import com.ziaan.library.FormatDate; import com.ziaan.library.ListSet; import com.ziaan.library.RequestBox; import com.ziaan.library.StringManager; /** * @author Administrator * * To change the template for this generated type comment go to * Window > Preferences > Java > Code Generation > Code and Comments */ public class CommunityMsPrBean { // private ConfigSet config; // private static int row=10; // private String v_type = "PQ"; // private static final String FILE_TYPE = "p_file"; // 파일업로드되는 tag name // private static final int FILE_LIMIT = 1; // 페이지에 세팅된 파일첨부 갯수 public CommunityMsPrBean() { try { // config = new ConfigSet(); // row = Integer.parseInt(config.getProperty("page.bulletin.row") ); // 이 모듈의 페이지당 row 수를 셋팅한다 // row = 10; // 강제로 지정 } catch( Exception e ) { e.printStackTrace(); } } /** * 커뮤니티 홍보정보조회 * @param box receive from the form object and session * @return ArrayList 커뮤니티 홍보정보 * @throws Exception */ public ArrayList selectQuery(RequestBox box) throws Exception { DBConnectionManager connMgr = null; ListSet ls = null; ArrayList list = new ArrayList(); String sql = ""; // String sql1 = ""; // String sql2 = ""; DataBox dbox = null; // String v_static_cmuno = box.getString("p_static_cmuno"); String v_cmuno = box.getString("p_cmuno"); // String s_userid = box.getSession("userid"); // String s_name = box.getSession("name"); try { connMgr = new DBConnectionManager(); sql = "\n select cmuno, realfile, savepath, savefile, filesize" + "\n , contents , register_userid, register_dte" + "\n , modifier_userid, modifier_dte" + "\n from tz_cmuhongbo " + "\n where cmuno = '" +v_cmuno + "'" ; ls = connMgr.executeQuery(sql); while ( ls.next() ) { dbox = ls.getDataBox(); list.add(dbox); } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return list; } /** * 홍보정보 등록하기 * @param box receive from the form object and session * @return isOk 1:insert success,0:insert fail * @throws Exception */ public int insertHongbo(RequestBox box) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt = null; ListSet ls = null; String sql = ""; int isOk1 = 1; int isOk2 = 1; // int v_seq = 0; // int v_menuno = 0; // String v_static_cmuno = box.getString("p_static_cmuno"); String v_cmuno = box.getString("p_cmuno"); String v_content = StringManager.replace(box.getString("content"),"<br > ","\n"); String s_userid = box.getSession("userid"); // String s_name = box.getSession("name"); try { connMgr = new DBConnectionManager(); connMgr.setAutoCommit(false); int v_reccnt=0; sql = "\n select count(*) cnt" + "\n from tz_cmuhongbo " + "\n where cmuno = '" +v_cmuno + "'" ; ls = connMgr.executeQuery(sql); while ( ls.next() ) v_reccnt= ls.getInt("cnt"); if ( v_reccnt<1) { sql =" insert into tz_cmuhongbo ( cmuno, realfile, savepath, savefile, filesize, contents" + " , register_userid, register_dte " + " , modifier_userid, modifier_dte )" + " values (?,?,'',?,0,?" + " ,?,to_char(sysdate,'YYYYMMDDHH24MISS')" + " ,?,to_char(sysdate,'YYYYMMDDHH24MISS'))" ; pstmt = connMgr.prepareStatement(sql); pstmt.setString(1 , v_cmuno );// 커뮤니팁먼호 pstmt.setString (2 , box.getRealFileName("p_file" ));// 실제파일 pstmt.setString(3 , box.getNewFileName("p_file" ));// 저장파일 pstmt.setString(4, v_content); pstmt.setString(5, s_userid);// 게시자 pstmt.setString(6, s_userid );// 수정자 isOk1 = pstmt.executeUpdate(); if ( pstmt != null ) { pstmt.close(); } // String sql1 = "select contents from tz_cmuhongbo where cmuno = '" +v_cmuno + "'"; // connMgr.setOracleCLOB(sql1, v_content); } else { if ( box.getString("p_savefile").length() <1) { sql =" update tz_cmuhongbo set realfile=?,savefile=?,contents=?" + " , modifier_userid=?, modifier_dte=to_char(sysdate,'YYYYMMDDHH24MISS') " + "\n where cmuno = '" +v_cmuno + "'" ; pstmt = connMgr.prepareStatement(sql); pstmt.setString (1 , box.getRealFileName("p_file" ));// 실제파일 pstmt.setString(2 , box.getNewFileName("p_file" ));// 저장파일 pstmt.setString(3, v_content); pstmt.setString(4, s_userid );// 수정자 isOk1 = pstmt.executeUpdate(); } else { sql =" update tz_cmuhongbo set contents=?" + " , modifier_userid=?, modifier_dte=to_char(sysdate,'YYYYMMDDHH24MISS') " + "\n where cmuno = '" +v_cmuno + "'" ; pstmt = connMgr.prepareStatement(sql); pstmt.setString(1, v_content ); pstmt.setString(2, s_userid );// 수정자 isOk1 = pstmt.executeUpdate(); if ( pstmt != null ) { pstmt.close(); } } // String sql1 = "select contents from tz_cmuhongbo where cmuno = '" +v_cmuno + "'"; // connMgr.setOracleCLOB(sql1, v_content); } if ( isOk1 > 0 ) { if ( connMgr != null ) { try { connMgr.commit(); } catch ( Exception e10 ) { } } } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql - > " +FormatDate.getDate("yyyyMMdd") + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( pstmt != null ) { try { pstmt.close(); } catch ( Exception e1 ) { } } if ( connMgr != null ) { try { connMgr.setAutoCommit(true); } catch ( Exception e10 ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return isOk1*isOk2; } /** * 홍보정보삭제 * @param connMgr DB Connection Manager * @param box receive from the form object and session * @return * @throws Exception */ public int deleteHongbo( RequestBox box) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt = null; ListSet ls = null; String sql = ""; // String sql2 = ""; int isOk2 = 1; // String s_userid = box.getSession("userid"); String v_cmuno = box.getString("p_cmuno"); try { connMgr = new DBConnectionManager(); connMgr.setAutoCommit(false); sql =" delete from tz_cmuhongbo' " + " where cmuno = ?" ; pstmt = connMgr.prepareStatement(sql); pstmt.setString(1, v_cmuno );// 커뮤니티번호 isOk2 = pstmt.executeUpdate(); if ( pstmt != null ) { pstmt.close(); } if ( isOk2 > 0 ) { if ( connMgr != null ) { try { connMgr.commit(); } catch ( Exception e10 ) { } } } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( pstmt != null ) { try { pstmt.close(); } catch ( Exception e1 ) { } } if ( connMgr != null ) { try { connMgr.setAutoCommit(true); } catch ( Exception e10 ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return isOk2; } /** * 선택된 자료파일 DB에서 삭제 * @param connMgr DB Connection Manager * @param box receive from the form object and session * @return * @throws Exception */ public int deleteSingleFile( RequestBox box) throws Exception { DBConnectionManager connMgr = null; PreparedStatement pstmt = null; ListSet ls = null; String sql = ""; // String sql2 = ""; int isOk2 = 1; // String s_userid = box.getSession("userid"); String v_cmuno = box.getString("p_cmuno"); try { connMgr = new DBConnectionManager(); connMgr.setAutoCommit(false); sql =" update tz_cmuhongbo set realfile='',savefile='' " + " where cmuno = ?" ; pstmt = connMgr.prepareStatement(sql); pstmt.setString(1, v_cmuno );// 커뮤니티번호 isOk2 = pstmt.executeUpdate(); if ( pstmt != null ) { pstmt.close(); } if ( isOk2 > 0 ) { if ( connMgr != null ) { try { connMgr.commit(); } catch ( Exception e10 ) { } } } } catch ( Exception ex ) { ErrorManager.getErrorStackTrace(ex, box, sql); throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() ); } finally { if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } } if ( pstmt != null ) { try { pstmt.close(); } catch ( Exception e1 ) { } } if ( connMgr != null ) { try { connMgr.setAutoCommit(true); } catch ( Exception e10 ) { } } if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } } } return isOk2; } }
/*  * Copyright 2012 Brayden (headdetect) Lopez * * Dual-licensed under the Educational Community License, Version 2.0 and * the GNU General Public License Version 3 (the "Licenses"); you may * not use this file except in compliance with the Licenses. You may * obtain a copy of the Licenses at * * http://www.opensource.org/licenses/ecl2.php * http://www.gnu.org/licenses/gpl-3.0.html * * Unless required by applicable law or agreed to in writing * software distributed under the Licenses are distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the Licenses for the specific language governing * permissions and limitations under the Licenses. * */ package com.headdetect.games.superpong.Activities; import static com.headdetect.games.superpong.Constants.CAMERA_HEIGHT; import static com.headdetect.games.superpong.Constants.CAMERA_WIDTH; import static com.headdetect.games.superpong.Constants.CHECK_HEIGHT; import static com.headdetect.games.superpong.Constants.GUI_PADDING; import static com.headdetect.games.superpong.Constants.HALF_BALL_RAD; import static com.headdetect.games.superpong.Constants.HALF_CAMERA_HEIGHT; import static com.headdetect.games.superpong.Constants.HALF_CAMERA_WIDTH; import static com.headdetect.games.superpong.Constants.HALF_PLAYER_HEIGHT; import static com.headdetect.games.superpong.Constants.MAX_PLAYER_Y; import static com.headdetect.games.superpong.Constants.MIN_PLAYER_Y; import static com.headdetect.games.superpong.Constants.TEXT_DISTANCE_FROM_CENTER; import java.io.IOException; import java.io.InputStream; import org.andengine.engine.Engine.EngineLock; import org.andengine.engine.camera.Camera; import org.andengine.engine.handler.IUpdateHandler; import org.andengine.engine.handler.timer.ITimerCallback; import org.andengine.engine.handler.timer.TimerHandler; import org.andengine.engine.options.EngineOptions; import org.andengine.engine.options.EngineOptions.ScreenOrientation; import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.andengine.entity.IEntity; import org.andengine.entity.particle.SpriteParticleSystem; import org.andengine.entity.particle.emitter.CircleParticleEmitter; import org.andengine.entity.particle.initializer.AccelerationParticleInitializer; import org.andengine.entity.particle.initializer.BlendFunctionParticleInitializer; import org.andengine.entity.particle.initializer.ColorParticleInitializer; import org.andengine.entity.particle.initializer.VelocityParticleInitializer; import org.andengine.entity.particle.modifier.ExpireParticleInitializer; import org.andengine.entity.particle.modifier.ScaleParticleModifier; import org.andengine.entity.scene.IOnSceneTouchListener; import org.andengine.entity.scene.Scene; import org.andengine.entity.scene.background.SpriteBackground; import org.andengine.entity.sprite.Sprite; import org.andengine.entity.text.Text; import org.andengine.entity.util.FPSLogger; import org.andengine.extension.physics.box2d.FixedStepPhysicsWorld; import org.andengine.extension.physics.box2d.PhysicsWorld; import org.andengine.extension.physics.box2d.util.Vector2Pool; import org.andengine.input.touch.TouchEvent; import org.andengine.input.touch.controller.MultiTouch; import org.andengine.input.touch.controller.MultiTouchController; import org.andengine.opengl.texture.ITexture; import org.andengine.opengl.texture.TextureOptions; import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.andengine.opengl.texture.bitmap.BitmapTexture; import org.andengine.opengl.texture.region.ITextureRegion; import org.andengine.opengl.texture.region.TextureRegionFactory; import org.andengine.ui.activity.BaseGameActivity; import org.andengine.util.adt.io.in.IInputStreamOpener; import android.opengl.GLES20; import android.os.SystemClock; import android.view.KeyEvent; import android.widget.Toast; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.Contact; import com.badlogic.gdx.physics.box2d.ContactImpulse; import com.badlogic.gdx.physics.box2d.ContactListener; import com.badlogic.gdx.physics.box2d.Manifold; import com.headdetect.games.superpong.Editables; import com.headdetect.games.superpong.Entities.Ball; import com.headdetect.games.superpong.Entities.Letters; import com.headdetect.games.superpong.Entities.Player; import com.headdetect.games.superpong.Entities.Wall; // TODO: Auto-generated Javadoc /** * The Class SinglePlayerPongActivity. */ public class SinglePlayerPongActivity extends BaseGameActivity implements IGameInterface { // =========================================================== // Constants // =========================================================== // TODO: Use Android.r public static String pauseMessage = "Paused"; public static String winMessageTopLine = "And the winner is..."; // =========================================================== // Fields // =========================================================== // -------------- // - Components // -------------- private Scene mScene; private Scene mWinScene; private Scene mPauseScene; private PhysicsWorld mPhysics; private Editables settings; private int playerScore; private int computerScore; // --------------------- // - Textures & Regions // --------------------- private ITextureRegion mRegionParticleCircle; // ------------------- // - Sprites // ------------------- private Ball mBall; private Wall topWall; private Wall bottomWall; private Player mPlayer; private Player mComputer; private Text playerText; private Text computerText; // ------------------ // - Final Overriding Fields // ----------------- private final IUpdateHandler UpdateHandle = new IUpdateHandler() { @Override public void onUpdate(float pSecondsElapsed) { final float ballY = mBall.getY(); final float ballX = mBall.getX(); final float computerY = mComputer.getY(); final float diff = ballY - computerY; if (diff >= CHECK_HEIGHT || diff <= -CHECK_HEIGHT) { mComputer.setPath(ballY - HALF_PLAYER_HEIGHT); } mComputer.onOwnUpdate(); // TODO: dim/opaque text by calculating distance from text and ball. if (ballX < -20 || ballX > CAMERA_WIDTH + 20) { mBall.getBody().setLinearVelocity(0, 0); mBall.getBody().setTransform((CAMERA_WIDTH / 2) / 32, (CAMERA_HEIGHT / 2) / 32, 0f); if (ballX < -20) computerScore++; else playerScore++; playerText.setText(String.valueOf(playerScore)); computerText.setText(String.valueOf(computerScore)); if (computerScore == 7) { win(mComputer); return; } else if (playerScore == 7) { win(mPlayer); return; } lag(new Runnable() { @Override public void run() { Vector2 vec = Vector2.createRandom(7f, 13f, 7f, 10f); int dir = 1; if (SystemClock.uptimeMillis() % 2 == 0) dir = -1; mBall.getBody().setLinearVelocity(vec.x * dir, vec.y * dir); } }, 3); } } @Override public void reset() { mComputer.transform(mComputer.getX(), CAMERA_HEIGHT / 2 - mComputer.getHeight() / 2); } }; private final ContactListener contactListener = new ContactListener() { @Override public void beginContact(Contact contact) { final Body bodyA = contact.getFixtureA().getBody(); final Body bodyB = contact.getFixtureB().getBody(); if (bodyA.equals(mBall.getBody()) || bodyB.equals(mBall.getBody())) { if (bodyA.equals(topWall.getBody()) || bodyB.equals(topWall.getBody())) { topWall.setGlowing(); } if (bodyA.equals(bottomWall.getBody()) || bodyB.equals(bottomWall.getBody())) { bottomWall.setGlowing(); } if (bodyA.equals(mPlayer.getBody()) || bodyB.equals(mPlayer.getBody())) { mPlayer.setGlowing(true); SinglePlayerPongActivity.this.makeGlowsplosion(mBall.getX(), mBall.getY()); } if (bodyA.equals(mComputer.getBody()) || bodyB.equals(mComputer.getBody())) { mComputer.setGlowing(true); SinglePlayerPongActivity.this.makeGlowsplosion(mBall.getX(), mBall.getY()); } } } @Override public void endContact(Contact contact) { mPlayer.setGlowing(false); mComputer.setGlowing(false); } @Override public void preSolve(Contact contact, Manifold oldManifold) { // TODO Auto-generated method stub } @Override public void postSolve(Contact contact, ContactImpulse impulse) { // TODO Auto-generated method stub } }; private final IOnSceneTouchListener sceneOnTouchListener = new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(Scene pScene, TouchEvent mEvent) { final float y = mEvent.getY(); if (y - HALF_PLAYER_HEIGHT > MIN_PLAYER_Y && y + HALF_PLAYER_HEIGHT < MAX_PLAYER_Y) mPlayer.transform(mPlayer.getX(), y - HALF_PLAYER_HEIGHT); return true; } }; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public void lag(final Runnable runnable, float time) { getEngine().registerUpdateHandler(new TimerHandler(time, new ITimerCallback() { @Override public void onTimePassed(TimerHandler pTimerHandler) { runnable.run(); } })); } @Override public PhysicsWorld getPhysicsWorld() { return mPhysics; } @Override public BaseGameActivity getInstance() { return this; } @Override public void removeEntity(IEntity mSprite) { if (mSprite == null) return; final EngineLock mLock = mEngine.getEngineLock(); mLock.lock(); try { mEngine.getScene().detachChild(mSprite); mSprite.dispose(); mSprite = null; } catch (Exception e) { } mLock.unlock(); } @Override public Editables getSettings() { return settings; } @Override public EngineOptions onCreateEngineOptions() { settings = new Editables(); return new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT)); } @Override public void onCreateResources(OnCreateResourcesCallback p) throws Exception { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("other/"); Ball.prepare(this); Wall.prepare(this); Player.prepare(this); Letters.prepare(this); ITexture mTextureParticleCircle = new BitmapTexture(getTextureManager(), this.getTexture("particles/circle_glow.png")); mRegionParticleCircle = TextureRegionFactory.extractFromTexture(mTextureParticleCircle); mTextureParticleCircle.load(); p.onCreateResourcesFinished(); } @Override public void onCreateScene(OnCreateSceneCallback p) throws Exception { mEngine.registerUpdateHandler(new FPSLogger()); if (MultiTouch.isSupported(this)) { mEngine.setTouchController(new MultiTouchController()); if (!MultiTouch.isSupportedDistinct(this)) { Toast.makeText(this, "Warning!\nYour device might have problems to distinguish between separate fingers.", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this, "Sorry your device does not support MultiTouch!", Toast.LENGTH_LONG).show(); finish(); } mScene = new Scene(); mScene.setBackground(new SpriteBackground(getBackground())); mPhysics = new FixedStepPhysicsWorld(50, 2, new Vector2(0, 0), false, 8, 8); mPhysics.setContactListener(contactListener); topWall = Wall.create(false); bottomWall = Wall.create(true); mBall = Ball.create(Vector2Pool.obtain(HALF_CAMERA_WIDTH - HALF_BALL_RAD, HALF_CAMERA_HEIGHT - HALF_BALL_RAD)); mPlayer = Player.create("Player", true); mComputer = Player.create("Computer", false); playerText = Letters.getText(new Vector2(HALF_CAMERA_WIDTH - TEXT_DISTANCE_FROM_CENTER, GUI_PADDING), String.valueOf(playerScore), Letters.HORIZONTAL_ALIGN_CENTER); computerText = Letters.getText(new Vector2(HALF_CAMERA_WIDTH + TEXT_DISTANCE_FROM_CENTER, GUI_PADDING), String.valueOf(computerScore), Letters.HORIZONTAL_ALIGN_CENTER); mScene.registerUpdateHandler(mPhysics); mScene.registerUpdateHandler(UpdateHandle); mScene.setOnSceneTouchListener(sceneOnTouchListener); mScene.attachChild(mBall); mScene.attachChild(topWall); mScene.attachChild(bottomWall); mScene.attachChild(mPlayer); mScene.attachChild(mComputer); mScene.attachChild(playerText); mScene.attachChild(computerText); // ----------------------------------------- // - Pause Scene // ----------------------------------------- mPauseScene = new Scene(); org.andengine.entity.primitive.Rectangle dimShape = new org.andengine.entity.primitive.Rectangle(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT, this.getVertexBufferObjectManager()); dimShape.setColor(0f, 0f, 0f, .8f); Text pText = Letters.getText(new Vector2(HALF_CAMERA_WIDTH - Letters.measureString(pauseMessage) / 2, HALF_CAMERA_HEIGHT), pauseMessage, Letters.HORIZONTAL_ALIGN_CENTER); mPauseScene.attachChild(pText); mPauseScene.attachChild(dimShape); p.onCreateSceneFinished(mScene); } @Override public void onPopulateScene(Scene pScene, OnPopulateSceneCallback p) throws Exception { lag(new Runnable() { @Override public void run() { Vector2 vec = Vector2.createRandom(7f, 13f, 7f, 10f); int dir = 1; if (SystemClock.uptimeMillis() % 2 == 0) dir = -1; mBall.getBody().setLinearVelocity(vec.x * dir, vec.y * dir); } }, 3); p.onPopulateSceneFinished(); } @Override public void makeGlowsplosion(float x, float y) { if (!getSettings().isEnableParticles()) return; final SpriteParticleSystem particleSystem = new SpriteParticleSystem(new CircleParticleEmitter(x, y, 30f), 10, 20, 30, this.mRegionParticleCircle, this.getVertexBufferObjectManager()); particleSystem.addParticleInitializer(new BlendFunctionParticleInitializer<Sprite>(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE)); particleSystem.addParticleInitializer(new VelocityParticleInitializer<Sprite>(-200, 200, -200, 200)); particleSystem.addParticleInitializer(new AccelerationParticleInitializer<Sprite>(-1.5f)); particleSystem.addParticleInitializer(new ColorParticleInitializer<Sprite>(.8f, 1f, .8f)); particleSystem.addParticleInitializer(new ExpireParticleInitializer<Sprite>(.2f, .8f)); particleSystem.addParticleModifier(new ScaleParticleModifier<Sprite>(0, 1, 0.01f, .2f)); mEngine.getScene().attachChild(particleSystem); lag(new Runnable() { @Override public void run() { removeEntity(particleSystem); } }, 1f); } @Override public IInputStreamOpener getTexture(final String loc) { return new IInputStreamOpener() { @Override public InputStream open() throws IOException { return getAssets().open(loc); } }; } @Override public boolean onKeyDown(final int pKeyCode, final KeyEvent pEvent) { if (pKeyCode == KeyEvent.KEYCODE_MENU && pEvent.getAction() == KeyEvent.ACTION_DOWN) { pause(); return true; } return super.onKeyDown(pKeyCode, pEvent); } // =========================================================== // Methods // =========================================================== private final Sprite getBackground() { try { final ITexture mTexture = new BitmapTexture(this.getTextureManager(), getTexture("other/bg.png"), TextureOptions.BILINEAR_PREMULTIPLYALPHA); final ITextureRegion mRegion = TextureRegionFactory.extractFromTexture(mTexture); mTexture.load(); return new Sprite(-3, -3, CAMERA_WIDTH + 3, CAMERA_HEIGHT + 3, mRegion, this.getVertexBufferObjectManager()); } catch (IOException e) { return null; } } private void win(Player p) { mBall.resetPos(); // mScene.clearUpdateHandlers(); mWinScene = new Scene(); mWinScene.setBackgroundEnabled(false); Text firstLine = Letters.getText(new Vector2(HALF_CAMERA_WIDTH - Letters.measureString(winMessageTopLine) / 2, HALF_CAMERA_HEIGHT - 100), winMessageTopLine, Letters.HORIZONTAL_ALIGN_CENTER, .6f); Text secondLine = Letters.getText(new Vector2(HALF_CAMERA_WIDTH - Letters.measureString(p.getName()) / 2, HALF_CAMERA_HEIGHT), p.getName(), Letters.HORIZONTAL_ALIGN_CENTER, .6f); mWinScene.attachChild(firstLine); mWinScene.attachChild(secondLine); if (this.mEngine.isRunning()) { this.mScene.setChildScene(mWinScene); this.mEngine.stop(); } } private void pause() { if (this.mEngine.isRunning()) { this.mScene.setChildScene(mPauseScene); this.mEngine.stop(); } else { this.mScene.clearChildScene(); this.mEngine.start(); } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
/* * Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.webui.common.attributes; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import pl.edu.icm.unity.server.utils.UnityMessageSource; import pl.edu.icm.unity.types.basic.Attribute; import pl.edu.icm.unity.types.basic.AttributeType; import pl.edu.icm.unity.types.basic.AttributeVisibility; import pl.edu.icm.unity.webui.common.CompactFormLayout; import pl.edu.icm.unity.webui.common.EnumComboBox; import pl.edu.icm.unity.webui.common.FormValidationException; import pl.edu.icm.unity.webui.common.GroupComboBox; import pl.edu.icm.unity.webui.common.ListOfEmbeddedElementsStub; import pl.edu.icm.unity.webui.common.safehtml.SafePanel; import com.vaadin.data.Property.ValueChangeEvent; import com.vaadin.data.Property.ValueChangeListener; import com.vaadin.ui.Component; import com.vaadin.ui.FormLayout; import com.vaadin.ui.VerticalLayout; /** * Attribute editor allowing to choose an attribute. It can use a fixed group for returned attribute or can * allow to select it. It can allow to edit attribute visibility too. * <p> * This class is not a component on its own - it returns one. * * @author K. Benedyczak */ public class SelectableAttributeEditor extends AbstractAttributeEditor { private Collection<AttributeType> attributeTypes; private Collection<String> allowedGroups; private ListOfEmbeddedElementsStub<LabelledValue> valuesComponent; private AttributeSelectionComboBox attributeSel; private GroupComboBox groupSel; private EnumComboBox<AttributeVisibility> visibilitySel; private boolean showVisibilityWidget; private VerticalLayout main = new VerticalLayout(); private SafePanel valuesPanel = new SafePanel(); public SelectableAttributeEditor(UnityMessageSource msg, AttributeHandlerRegistry registry, Collection<AttributeType> attributeTypes, boolean showVisibilityWidget, Collection<String> allowedGroups) { super(msg, registry); this.attributeTypes = attributeTypes; this.allowedGroups = allowedGroups; this.showVisibilityWidget = showVisibilityWidget; initUI(); } public SelectableAttributeEditor(UnityMessageSource msg, AttributeHandlerRegistry registry, Collection<AttributeType> attributeTypes, boolean showVisibilityWidget, String fixedGroup) { this(msg, registry, attributeTypes, showVisibilityWidget, Collections.singleton(fixedGroup)); } public void setInitialAttribute(Attribute<?> initial) { attributeSel.setValue(initial.getName()); if (groupSel != null) groupSel.setValue(initial.getGroupPath()); if (visibilitySel != null) visibilitySel.setEnumValue(initial.getVisibility()); setNewValuesUI(); List<LabelledValue> labelledValues = new ArrayList<>(initial.getValues().size()); String baseLabel = initial.getName(); for (int i=0; i<initial.getValues().size(); i++) { String label = baseLabel + ((initial.getValues().size() > 1) ? " (" + (i+1) + "):" : ""); labelledValues.add(new LabelledValue(initial.getValues().get(i), label)); } valuesComponent.setEntries(labelledValues); } @SuppressWarnings({ "unchecked", "rawtypes" }) public Attribute<?> getAttribute() throws FormValidationException { List<?> labelledValues = valuesComponent == null ? new ArrayList<>(0) : valuesComponent.getElements(); List<Object> values = new ArrayList<>(labelledValues.size()); for (Object lv: labelledValues) values.add(((LabelledValue)lv).getValue()); AttributeType at = attributeSel.getSelectedValue(); String group; if (attributeTypes.size() > 0) group = (String) groupSel.getValue(); else group = allowedGroups.iterator().next(); AttributeVisibility visibility = showVisibilityWidget ? visibilitySel.getSelectedValue() : at.getVisibility(); return new Attribute(at.getName(), at.getValueType(), group, visibility, values); } private void initUI() { main.setSpacing(true); FormLayout top = new CompactFormLayout(); attributeSel = new AttributeSelectionComboBox(msg.getMessage("Attributes.attribute"), attributeTypes); attributeSel.addValueChangeListener(new ValueChangeListener() { @Override public void valueChange(ValueChangeEvent event) { setNewValuesUI(); } }); attributeSel.setImmediate(true); top.addComponent(attributeSel); if (allowedGroups.size() > 1) { groupSel = new GroupComboBox(msg.getMessage("Attributes.group"), allowedGroups); groupSel.setInput("/", true); top.addComponent(groupSel); } if (showVisibilityWidget) { visibilitySel = new EnumComboBox<AttributeVisibility>(msg.getMessage("Attributes.visibility"), msg, "AttributeVisibility.", AttributeVisibility.class, AttributeVisibility.full); top.addComponent(visibilitySel); } valuesPanel.setCaption(msg.getMessage("Attributes.values")); main.addComponent(top); main.addComponent(valuesPanel); if (attributeTypes.size() > 0) setNewValuesUI(); } private void setNewValuesUI() { AttributeType selected = attributeSel.getSelectedValue(); FormLayout ct = new CompactFormLayout(); ct.setMargin(true); valuesComponent = getValuesPart(selected, selected.getName(), true, true, ct); valuesPanel.setContent(ct); } public Component getComponent() { return main; } }
/* * 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.jdbc.datasource; import java.io.ByteArrayOutputStream; import java.io.PrintWriter; import java.sql.Connection; import javax.sql.DataSource; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * Tests for {@link DelegatingDataSource}. * * @author Phillip Webb */ public class DelegatingDataSourceTests { private final DataSource delegate = mock(); private DelegatingDataSource dataSource = new DelegatingDataSource(delegate); @Test public void shouldDelegateGetConnection() throws Exception { Connection connection = mock(); given(delegate.getConnection()).willReturn(connection); assertThat(dataSource.getConnection()).isEqualTo(connection); } @Test public void shouldDelegateGetConnectionWithUsernameAndPassword() throws Exception { Connection connection = mock(); String username = "username"; String password = "password"; given(delegate.getConnection(username, password)).willReturn(connection); assertThat(dataSource.getConnection(username, password)).isEqualTo(connection); } @Test public void shouldDelegateGetLogWriter() throws Exception { PrintWriter writer = new PrintWriter(new ByteArrayOutputStream()); given(delegate.getLogWriter()).willReturn(writer); assertThat(dataSource.getLogWriter()).isEqualTo(writer); } @Test public void shouldDelegateSetLogWriter() throws Exception { PrintWriter writer = new PrintWriter(new ByteArrayOutputStream()); dataSource.setLogWriter(writer); verify(delegate).setLogWriter(writer); } @Test public void shouldDelegateGetLoginTimeout() throws Exception { int timeout = 123; given(delegate.getLoginTimeout()).willReturn(timeout); assertThat(dataSource.getLoginTimeout()).isEqualTo(timeout); } @Test public void shouldDelegateSetLoginTimeoutWithSeconds() throws Exception { int timeout = 123; dataSource.setLoginTimeout(timeout); verify(delegate).setLoginTimeout(timeout); } @Test public void shouldDelegateUnwrapWithoutImplementing() throws Exception { ExampleWrapper wrapper = mock(); given(delegate.unwrap(ExampleWrapper.class)).willReturn(wrapper); assertThat(dataSource.unwrap(ExampleWrapper.class)).isEqualTo(wrapper); } @Test public void shouldDelegateUnwrapImplementing() throws Exception { dataSource = new DelegatingDataSourceWithWrapper(); assertThat(dataSource.unwrap(ExampleWrapper.class)).isSameAs(dataSource); } @Test public void shouldDelegateIsWrapperForWithoutImplementing() throws Exception { given(delegate.isWrapperFor(ExampleWrapper.class)).willReturn(true); assertThat(dataSource.isWrapperFor(ExampleWrapper.class)).isTrue(); } @Test public void shouldDelegateIsWrapperForImplementing() throws Exception { dataSource = new DelegatingDataSourceWithWrapper(); assertThat(dataSource.isWrapperFor(ExampleWrapper.class)).isTrue(); } public interface ExampleWrapper { } private static class DelegatingDataSourceWithWrapper extends DelegatingDataSource implements ExampleWrapper { } }
package YouDoIt; import javax.swing.JOptionPane; public class Eggs { public static void main(String[] args) { // TODO Auto-generated method stub int egg, eggdozen, leftover; double eggP; double totalP; double onedozeneggs; eggP = .45; onedozeneggs = 3.25; String eggsString = JOptionPane.showInputDialog(null, "enter the amount of eggs you want or cancel and enter the amount of dozens."); egg = Integer.parseInt(eggsString); eggdozen = egg/12; leftover = egg % 12; totalP = (eggP*leftover) + (onedozeneggs*eggdozen); JOptionPane.showMessageDialog(null, "That's " + eggdozen + " dozen at 3.25 perdozen and " + leftover + " at .45 for a total of " + totalP); } }
package org.foodobjects.bikerbuddy; import android.content.Context; import android.os.Handler; import android.view.KeyEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; public class GraphView extends SurfaceView implements SurfaceHolder.Callback { private PaintingThread thread = null; public GraphView(Context context) { super(context); SurfaceHolder holder = getHolder(); holder.addCallback(this); thread = new PaintingThread(holder, context, new Handler()); setFocusable(true); // need to get the key events } public PaintingThread getThread() { return thread; } public void surfaceCreated(SurfaceHolder holder) { thread.setRunning(true); thread.start(); } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } public void surfaceDestroyed(SurfaceHolder holder) { boolean retry = true; thread.setRunning(false); while (retry) { try { thread.join(); retry = false; } catch (InterruptedException e) { } } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { thread.doKeyDown(keyCode, event); return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { thread.doKeyUp(keyCode, event); return super.onKeyUp(keyCode, event); } }
package com.cs.casino; import com.cs.casino.security.CasinoCookieContent; import com.cs.casino.security.LoginAttemptsRecordingAuthenticationProvider; import com.cs.casino.security.PersistedSessionRegistryImpl; import com.cs.casino.security.PlayerLogonService; import com.cs.player.PlayerService; import com.cs.rest.RestConfig; import com.cs.session.PlayerSessionRegistryRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity; import org.springframework.security.core.session.SessionRegistry; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.header.writers.StaticHeadersWriter; import static org.springframework.http.HttpMethod.GET; import static org.springframework.http.HttpMethod.POST; /** * @author Joakim Gottzén */ @Configuration @EnableWebMvcSecurity public class CasinoWebSecurityConfig extends WebSecurityConfigurerAdapter { private static final String LOGIN_URL = "/api/players/login"; private static final String LOGIN_SUCCESSFUL_URL = "/api/players/login/success"; private static final String LOGIN_FAILURE_URL = "/api/players/login/failure"; private static final String LOGOUT_URL = "/api/players/logout"; private static final String LOGOUT_SUCCESSFUL_URL = "/api/players/logout/success"; private static final String INVALID_SESSION_URL = "/api/players/session/invalid"; private static final String SESSION_EXPIRED_URL = "/api/players/session/expired"; @Autowired private PlayerLogonService playerLogonService; @Autowired private PlayerService playerService; @Autowired private PasswordEncoder passwordEncoder; @Autowired private PlayerSessionRegistryRepository playerSessionRegistryRepository; @Override public void configure(final WebSecurity web) throws Exception { web.ignoring().antMatchers("/resources/**"); } @Override protected void configure(final HttpSecurity http) throws Exception { final String[] allowedPostUrls = {"/api/players", "/api/players/password/reset/create", "/api/players/password/reset", "/api/players/validate/email", "/api/players/validate/nickname", INVALID_SESSION_URL, SESSION_EXPIRED_URL}; final String[] allowedGetUrls = {"/api/avatars/signup", "/api/games", "/api/games/touch", "/api/games/leaderboard", "/api/games/leaderboard/**", "/api/levels", "/api/players/verify/**", LOGIN_URL, LOGIN_FAILURE_URL, LOGOUT_URL, LOGOUT_SUCCESSFUL_URL, INVALID_SESSION_URL, SESSION_EXPIRED_URL}; //@formatter:off http .csrf() .disable() // .csrfTokenRepository(csrfTokenRepository) // .and() .headers() .addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Origin", "*")) .and() .authorizeRequests() .antMatchers(GET, allowedGetUrls).permitAll() .antMatchers(POST, allowedPostUrls).permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage(LOGIN_URL) .defaultSuccessUrl(LOGIN_SUCCESSFUL_URL) .failureUrl(LOGIN_FAILURE_URL) .permitAll() .and() .logout() .logoutUrl(LOGOUT_URL) .logoutSuccessUrl(LOGOUT_SUCCESSFUL_URL) .invalidateHttpSession(true) .deleteCookies(RestConfig.JSESSIONID, CasinoCookieContent.COOKIE_NAME) .permitAll() .and() .sessionManagement() .sessionFixation() .changeSessionId() .invalidSessionUrl(INVALID_SESSION_URL) .maximumSessions(1) .expiredUrl(SESSION_EXPIRED_URL) .sessionRegistry(sessionRegistry()); //@formatter:on } @Override protected void configure(final AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(authenticationProvider()); } private LoginAttemptsRecordingAuthenticationProvider authenticationProvider() { final LoginAttemptsRecordingAuthenticationProvider authenticationProvider = new LoginAttemptsRecordingAuthenticationProvider(playerService); authenticationProvider.setUserDetailsService(playerLogonService); authenticationProvider.setPasswordEncoder(passwordEncoder); return authenticationProvider; } @Bean public SessionRegistry sessionRegistry() { return new PersistedSessionRegistryImpl(playerSessionRegistryRepository); } }
package ca.mcgill.ecse223.kingdomino.controller; import ca.mcgill.ecse223.kingdomino.KingdominoApplication; import ca.mcgill.ecse223.kingdomino.model.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /*** * *Controller Class that contains query methods for game attributes *@author Cecilia Jiang ***/ public class GameController { private static HashMap<String, Square[]> grids = new HashMap<>(); private static HashMap<String, DisjointSet> sets = new HashMap<>(); ///////////////////////////// ////// ////////////QueryMethods//// ////// /////////////////////////// ////// public static void createGivenNumberOfPlayer(Game game, int playerNum){ if(playerNum < 2 || playerNum > 4) throw new IllegalArgumentException("Player Number should be between 2 and 4"); // Create Players for(int i = 0; i< playerNum; i++) new Player(game); } public static Draft findDraftByDominoId(Game game, int id){ List<Draft> drafts = game.getAllDrafts(); for(Draft draft: drafts){ for(Domino domino: draft.getIdSortedDominos()) if(domino.getId() == id) return draft; } return null; } public static List<Domino> getAllDominobyTerrainType(String terrainString, Game game) { List<Domino> dominoList = new ArrayList<>(); TerrainType terrain = getTerrainType(terrainString); for(Domino domino: game.getAllDominos()) { if((domino.getRightTile()).equals(terrain) || (domino.getLeftTile()).equals(terrain)) dominoList.add(domino); } return dominoList; } /** * Combine current square and all adjacent square into one set * @param curIndex, current square index * @param adjacentIndexes, a list of adjacent squares' indexes * @param s, disjoint set for current player */ public static void unionCurrentSquare(int curIndex, ArrayList<Integer> adjacentIndexes, DisjointSet s){ for (int i: adjacentIndexes) s.union(curIndex, i); } public static void setSet(String playerName, DisjointSet s) { sets.put(playerName, s); } public static DisjointSet getSet(String playerName) { return sets.get(playerName); } public static void setGrid(String playerName, Square[] gridinput) { grids.put(playerName, gridinput); } public static Square[] getGrid(String playerName){ return grids.get(playerName); } public static void clearSets () { grids.clear(); } public static void clearGrids () { grids.clear(); } private static TerrainType getTerrainType(String terrain) { switch (terrain) { case "W": case "wheat": return TerrainType.WheatField; case "F": case "forest": return TerrainType.Forest; case "M": case "mountain": return TerrainType.Mountain; case "G": case "grass": return TerrainType.Grass; case "S": case "swamp": return TerrainType.Swamp; case "L": case "lake": return TerrainType.Lake; default: throw new java.lang.IllegalArgumentException("Invalid terrain type: " + terrain); } } ///////////////////////////// ////// /////////Feature Methods//// ////// /////////////////////////// ////// /** * Feature: Set Bonus Option for current game * @author Cecilia Jiang * @param mkActivated, boolean variable that specify if middleKingdom is activated * @param harmonyActivated, boolean variable that specify if harmony is activated */ public static void setBonusOptionForCurrentGame(boolean mkActivated, boolean harmonyActivated){ if(mkActivated){ Kingdomino kingdomino = KingdominoApplication.getKingdomino(); Game game = kingdomino.getCurrentGame(); game.addSelectedBonusOption(new BonusOption("middle kingdom",kingdomino)); } if(harmonyActivated){ Kingdomino kingdomino = KingdominoApplication.getKingdomino(); Game game = kingdomino.getCurrentGame(); game.addSelectedBonusOption(new BonusOption("harmony",kingdomino)); } } }
package com.kwik.repositories.client.dao; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.Query; import br.com.caelum.vraptor.ioc.Component; import com.kwik.models.Address; import com.kwik.repositories.client.AddressRespository; @Component public class AddressDao implements AddressRespository { private EntityManager entityManager; public AddressDao(EntityManager entityManager) { this.entityManager = entityManager; } @Override public Address findBy(String zipCode) { Query query = entityManager.createQuery(" FROM " + Address.class.getName() + " a WHERE a.zipCode = :zipCode "); query.setParameter("zipCode", zipCode); Address address = null; try { return (Address) query.getSingleResult(); } catch (NoResultException e) {} return address; } @Override public Address add(Address address) { Address result = address; entityManager.persist(result); return result; } }
package behavioral.command; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static org.junit.Assert.*; /** * @author Renat Kaitmazov */ @RunWith(JUnit4.class) public final class CommandTest { @Test public final void commandTest() throws Exception { final String currentOsName = System.getProperty("os.name"); System.out.println("The underlying OS is " + currentOsName); final FileSystemReceiver fileSystemReceiver; if (currentOsName.contains("Windows")) { fileSystemReceiver = new WindowsFileSystemReceiver(); } else { fileSystemReceiver = new UnixFileSystemReceiver(); } final Command openFileCommand = new OpenFileCommand(fileSystemReceiver); FileCommandInvoker fileCommandInvoker = new FileCommandInvoker(openFileCommand); fileCommandInvoker.execute(); System.out.println(); final Command writeFileCommand = new WriteFileCommand(fileSystemReceiver); fileCommandInvoker = new FileCommandInvoker(writeFileCommand); fileCommandInvoker.execute(); System.out.println(); final Command closeFileCommand = new CloseFileCommand(fileSystemReceiver); fileCommandInvoker = new FileCommandInvoker(closeFileCommand); fileCommandInvoker.execute(); } }
package HomeWork4; public class Warrior { private String name; private int age; private int health; private int damage; public Warrior(String name, int age, int health, int damage) { this.name = name; this.age = age; this.health = health; this.damage = damage; } public void fight(Warrior enemy) { double k = Math.random(); while (enemy.health > 0 && this.health > 0) { if (k > 0.5) { this.health -= enemy.damage; } else { enemy.health -= this.damage; } if (this.health <= 0) { System.out.println("Иван погиб в бою"); } else if (enemy.health <= 0) { System.out.println("Петр погиб в бою"); } } } }
package org.xitikit.examples.java.mysql.logwatch.files; /** * Indicates there was a problem specific to parsing the "access.log" * and saving the entries in a database. */ public class AccessLogException extends IllegalArgumentException{ public AccessLogException(final String message){ super(message); } public AccessLogException(){ } public AccessLogException(final String message, final Throwable cause){ super(message, cause); } public AccessLogException(final Throwable cause){ super(cause); } }
package com.detroitlabs.comicview.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import org.springframework.stereotype.Component; @JsonIgnoreProperties(ignoreUnknown = true) @Component public class Results { private String aliases; private String apiDetailsUrl; private String birth; private String CharacterEnemies; private String CharacterFriends; // private String creators; private String deck; private String description; // private String firstAppearedInIssue; private String gender; private String id; private String image; // private String issueCredits; // private String issueDiedIn; // private String movies; private String name; // private String origin; // private String powers; // private String publisher; private String realName; // private String teamEnemies; // private String teamFriends; // private String teams; public String getAliases() { return aliases; } public void setAliases(String aliases) { this.aliases = aliases; } public String getApiDetailsUrl() { return apiDetailsUrl; } public void setApiDetailsUrl(String apiDetailsUrl) { this.apiDetailsUrl = apiDetailsUrl; } public String getBirth() { return birth; } public void setBirth(String birth) { this.birth = birth; } public String getCharacterFriends() { return CharacterFriends; } public void setCharacterFriends(String characterFriends) { CharacterFriends = characterFriends; } public String getDeck() { return deck; } public void setDeck(String deck) { this.deck = deck; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } @Override public String toString() { return "Results{" + "aliases='" + aliases + '\'' + ", apiDetailsUrl='" + apiDetailsUrl + '\'' + ", birth='" + birth + '\'' + ", CharacterFriends='" + CharacterFriends + '\'' + ", deck='" + deck + '\'' + ", description='" + description + '\'' + ", gender='" + gender + '\'' + ", id='" + id + '\'' + ", name='" + name + '\'' + ", realName='" + realName + '\'' + '}'; } }
/** * @author TATTYPLAY * @date May 22, 2018 * @created 12:47:20 AM * @filename ManagerInventory.java * @project Reporter * @package com.tattyhost.reporter.Manager * @copyright 2018 */ package com.tattyhost.reporter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import net.md_5.bungee.api.ChatColor; public class InventoryE { private static List<HashMap<String, Integer>> inventorys = new ArrayList<HashMap<String, Integer>>(); private static int inventorysIDs = 0; private int inventoryID; private String name; private int slots; private Inventory inv; public InventoryE(String name, int slots, int inventoryID) { HashMap<String, Integer> input = new HashMap<>(); input.put(name, slots); inventorys.add(inventoryID, input); this.inventoryID = inventorysIDs; inventorysIDs++; this.name = ChatColor.translateAlternateColorCodes('&', name); this.slots = slots; this.inv = Bukkit.createInventory(null, slots, this.name); } public InventoryE() { } ///////////////////////////////////////////////////////////////////////////////////// // // STATIC METHODES // ///////////////////////////////////////////////////////////////////////////////////// public static HashMap<String, Integer> getInventory(int inventoryID) { return getInventorys().get(inventoryID); } public static List<HashMap<String, Integer>> getInventorys() { return inventorys; } ///////////////////////////////////////////////////////////////////////////////////// // // OPJECT METHODES // ///////////////////////////////////////////////////////////////////////////////////// public int getInventoryID() { return inventoryID; } public String getName() { return name; } public void setName(String name){ this.name = name; } public int getSlots() { return slots; } public void addItem(ItemStack itackstack, int slot) { inv.setItem(slot, itackstack); } public Inventory getInventory() { return inv; } public void setItem(int slot, ItemStack itemStack) { getInventory().setItem(slot, itemStack); } }
package br.com.guisfco.onlineshopping.controller; import br.com.guisfco.onlineshopping.domain.ProductRequest; import br.com.guisfco.onlineshopping.entity.Product; import br.com.guisfco.onlineshopping.service.product.DeleteProductService; import br.com.guisfco.onlineshopping.service.product.FindAllProductsService; import br.com.guisfco.onlineshopping.service.product.SaveProductService; import br.com.guisfco.onlineshopping.service.product.UpdateProductService; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequiredArgsConstructor public class ProductController { private final SaveProductService saveProductService; private final FindAllProductsService findAllProductsService; private final DeleteProductService deleteProductService; private final UpdateProductService updateProductService; @ApiOperation("Consulta todos os produtos") @GetMapping("/product") private ResponseEntity<List<Product>> get() { return ResponseEntity.ok(findAllProductsService.findAll()); } @ResponseStatus(HttpStatus.CREATED) @ApiOperation("Adiciona um produto") @PostMapping("/product") private ResponseEntity<Product> save(@RequestBody final ProductRequest request) { return ResponseEntity.ok(saveProductService.save(request)); } @ApiOperation("Atualiza as informações de um produto através do id") @PutMapping("/product/{id}") private ResponseEntity<Product> update(@PathVariable("id") final Long id, @RequestBody final ProductRequest request) { return ResponseEntity.ok(updateProductService.update(id, request)); } @ApiOperation("Deleta um produto através do id") @DeleteMapping("/product/{id}") private ResponseEntity<Void> deleteById(@PathVariable("id") final Long id) { deleteProductService.deleteById(id); return ResponseEntity.noContent().build(); } }
package com.sun.tools.xjc.reader.xmlschema; import com.sun.tools.xjc.model.CClassInfo; import com.sun.tools.xjc.model.CPropertyInfo; import com.sun.tools.xjc.reader.Ring; import com.sun.tools.xjc.reader.xmlschema.bindinfo.BIProperty; import com.sun.xml.xsom.XSAnnotation; import com.sun.xml.xsom.XSComponent; import com.sun.xml.xsom.XSFacet; import com.sun.xml.xsom.XSIdentityConstraint; import com.sun.xml.xsom.XSNotation; import com.sun.xml.xsom.XSSchema; import com.sun.xml.xsom.XSSimpleType; import com.sun.xml.xsom.XSXPath; import com.sun.xml.xsom.visitor.XSVisitor; /** * @author Kohsuke Kawaguchi */ abstract class ColorBinder extends BindingComponent implements XSVisitor { protected final BGMBuilder builder = Ring.get(BGMBuilder.class); protected final ClassSelector selector = getClassSelector(); protected final CClassInfo getCurrentBean() { return selector.getCurrentBean(); } protected final XSComponent getCurrentRoot() { return selector.getCurrentRoot(); } protected final void createSimpleTypeProperty(XSSimpleType type,String propName) { BIProperty prop = BIProperty.getCustomization(type); SimpleTypeBuilder stb = Ring.get(SimpleTypeBuilder.class); // since we are building the simple type here, use buildDef CPropertyInfo p = prop.createValueProperty(propName,false,type,stb.buildDef(type),BGMBuilder.getName(type)); getCurrentBean().addProperty(p); } public final void annotation(XSAnnotation xsAnnotation) { throw new IllegalStateException(); } public final void schema(XSSchema xsSchema) { throw new IllegalStateException(); } public final void facet(XSFacet xsFacet) { throw new IllegalStateException(); } public final void notation(XSNotation xsNotation) { throw new IllegalStateException(); } public final void identityConstraint(XSIdentityConstraint xsIdentityConstraint) { throw new IllegalStateException(); } public final void xpath(XSXPath xsxPath) { throw new IllegalStateException(); } }
package negocio.apresentacao; import java.util.Date; import negocio.basica.Chamado; import negocio.basica.Computador; import negocio.basica.Funcionario; import negocio.basica.Orcamento; import negocio.basica.Tipochamado; import negocio.controlador.ControladorChamado; public class ApresentacaoChamado { public static void main(String[] args) { ControladorChamado contCham = new ControladorChamado(); Chamado cham = new Chamado(); Tipochamado tipoCham = new Tipochamado(); Orcamento orc = new Orcamento(); Funcionario func = new Funcionario(); Computador computadors = new Computador(); tipoCham.setId(1); orc.setId(1); func.setId(1); computadors.setId(1); cham.setId(1); cham.setTipochamado(tipoCham); cham.setOrcamento(orc); cham.setFuncionario(func); cham.setNome("Thiago Lins"); cham.setOrigem("Finanças"); cham.setSituacao("Aberto"); cham.setDescricao("Computador apresentando problema no carregamento do sistema"); cham.setDtchamado(new Date()); cham.setObservacao("Solicito urgência no atendimento"); cham.setComputadors(null); contCham.incluir(cham); } }
package FirstProject.Playground; public class B extends A{ private int num1; private int num2; // Extends from abstract class // Do I override the method or just define it here? // Can abstract classes have instance variables? // Can they be initiated and accessed in child class? public int sumOfTwo(){ int result = num1 + num2; return result; } public int productOfTwo(){ int result = num1 * num2; return result; } public static void main(String[] args) { } // As seen below, they must be overwritten // @Override // public int sumOfTwo() { // // TODO Auto-generated method stub // return 0; // } // @Override // public int productOfTwo() { // // TODO Auto-generated method stub // return 0; // } }
package com.bupc.bupc_quiz; import com.bupc.bupc_quiz.data.models.Question; import java.util.ArrayList; import java.util.List; public class DataHolder { private List<Question> mQuestions = new ArrayList<>(); private static final DataHolder mInstance = new DataHolder(); public static synchronized DataHolder getInstance() { return mInstance; } public void addQuestion(Question question) { mQuestions.add(question); } public void addQuestions(List<Question> Questions) { mQuestions.addAll(Questions); } public void setQuestions(List<Question> Questions) { mQuestions.clear(); addQuestions(Questions); } public Question getQuestion(int index) { return mQuestions.get(index); } public List<Question> getQuestions() { return mQuestions; } public int getTotalItems() { return mQuestions.size(); } }
package com.karya.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="lead001mb") public class Lead001MB implements Serializable { private static final long serialVersionUID = -723583058586873479L; @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name ="id") private int id; @Column(name="personname") private String personname; @Column(name="organisationname") private String organisationname; @Column(name="status") private String status; @Column(name="source") private String source; @Column(name="leadowner") private String leadowner; @Column(name="nextcontactby") private String nextcontactby; @Column(name="leadtype") private String leadtype; @Column(name="marketsegment") private String marketsegment; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getPersonname() { return personname; } public void setPersonname(String personname) { this.personname = personname; } public String getOrganisationname() { return organisationname; } public void setOrganisationname(String organisationname) { this.organisationname = organisationname; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getLeadowner() { return leadowner; } public void setLeadowner(String leadowner) { this.leadowner = leadowner; } public String getNextcontactby() { return nextcontactby; } public void setNextcontactby(String nextcontactby) { this.nextcontactby = nextcontactby; } public String getLeadtype() { return leadtype; } public void setLeadtype(String leadtype) { this.leadtype = leadtype; } public String getMarketsegment() { return marketsegment; } public void setMarketsegment(String marketsegment) { this.marketsegment = marketsegment; } }
package com.transport.bo.impl; import java.util.Map; import com.transport.bo.InspectionBo; import com.transport.dao.InspectionDao; /** * * @author edwarddavid * @since 21Mar2020 */ public class InspectionBoImpl implements InspectionBo { private InspectionDao dao; public InspectionDao getInspectionDao() { return dao; } public void setInspectionDao(InspectionDao dao) { this.dao = dao; } @Override public Map<String, Object> getActiveData() throws Exception { return dao.getActiveData(); } }
package edu.uw.cwds.predictionservice.linearregression; import javax.xml.bind.annotation.*; @XmlRootElement(name="rangeParameter") @XmlAccessorType(XmlAccessType.FIELD) public class RangeRegressionParameter implements RegressionParameter { @XmlElement(name="range") private Range[] ranges; @XmlAttribute(name="defaultValue") private Double defaultValue; public Range[] getRanges() { return ranges; } public void setRanges(Range[] value) { ranges = value; } public Double getDefaultValue() { return defaultValue; } public void setDefaultValue(Double value) { defaultValue = value; } public double getTermValue(String variable) throws Exception { double val = Double.parseDouble(variable); for (Range r : ranges) { if (r.isWithinRange(val)) { return r.getValue(); } } if (defaultValue != null) { return defaultValue; } else { throw new NoMatchFoundException( "No range found for value " + val + " and there is no default return value."); } } }
package com.revature.ers.models; import java.sql.Timestamp; import com.fasterxml.jackson.annotation.JsonIgnore; public class Reimbursement { // @JsonIgnore // must be on; as in @JsonIgnore must NOT be commented out; ERROR: Can not deserialize instance of int out of START_OBJECT token private int reimbId; private int amount; // need to take this off when we need to populate the tables @JsonIgnore private Timestamp reimbSubmitted; // need to take this off when we need to populate the tables @JsonIgnore private Timestamp reimbResolved; private String reimbDescription; // authorId --> current logged in user submitting reimbursement private int authorId; /* --------------------------------------------------------------------------------------------------- resolverId --> manager typically resolves reimbursements with statusId: 1 with value of 'PENDING --------------------------------------------------------------------------------------------------- 1. managers make changes to reimbursements of employees 2. manager (mgr1) cannot make updates to reimbursements mgr1 submitted 2.1 however, mgr1 submitted reimbursements can be updated/modified by other manager (e.g. mgr2) */ private int resolverId; /* ------------------------ status of reimbursement ------------------------ 1 -> 'PENDING' 2 -> 'APPROVED' 3 -> 'DONE' 4 -> 'DENIED' */ private int statusId; /* ----------------------- types of reimbursement ----------------------- 1 -> 'LODGING' 2 -> 'TRAVEL' 3 -> 'FOOD' 4 -> 'OTHER' */ private int typeId; public Reimbursement() { super(); } public Reimbursement(int reimbId, int amount, Timestamp reimbSubmitted, Timestamp reimbResolved, String reimbDescription, int authorId, int resolverId, int statusId, int typeId) { super(); this.reimbId = reimbId; this.amount = amount; this.reimbSubmitted = reimbSubmitted; this.reimbResolved = reimbResolved; this.reimbDescription = reimbDescription; this.authorId = authorId; this.resolverId = resolverId; this.statusId = statusId; this.typeId = typeId; } public Reimbursement(int amount,String reimbDescription, int authorId, int statusId, int typeId) { super(); this.amount = amount; this.reimbDescription = reimbDescription; this.authorId = authorId; this.statusId = statusId; this.typeId = typeId; } public int getReimbId() { return reimbId; } public void setReimbId(int reimbId) { this.reimbId = reimbId; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } public Timestamp getReimbSubmitted() { return reimbSubmitted; } public void setReimbSubmitted(Timestamp reimbSubmitted) { this.reimbSubmitted = reimbSubmitted; } public Timestamp getReimbResolved() { return reimbResolved; } public void setReimbResolved(Timestamp reimbResolved) { this.reimbResolved = reimbResolved; } public String getReimbDescription() { return reimbDescription; } public void setReimbDescription(String reimbDescription) { this.reimbDescription = reimbDescription; } public int getAuthorId() { return authorId; } public void setAuthorId(int authorId) { this.authorId = authorId; } public int getResolverId() { return resolverId; } public void setResolverId(int resolverId) { this.resolverId = resolverId; } public int getStatusId() { return statusId; } public void setStatusId(int statusId) { this.statusId = statusId; } public int getTypeId() { return typeId; } public void setTypeId(int typeId) { this.typeId = typeId; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + amount; result = prime * result + authorId; result = prime * result + ((reimbDescription == null) ? 0 : reimbDescription.hashCode()); result = prime * result + reimbId; result = prime * result + ((reimbResolved == null) ? 0 : reimbResolved.hashCode()); result = prime * result + ((reimbSubmitted == null) ? 0 : reimbSubmitted.hashCode()); result = prime * result + resolverId; result = prime * result + statusId; result = prime * result + typeId; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Reimbursement other = (Reimbursement) obj; if (amount != other.amount) return false; if (authorId != other.authorId) return false; if (reimbDescription == null) { if (other.reimbDescription != null) return false; } else if (!reimbDescription.equals(other.reimbDescription)) return false; if (reimbId != other.reimbId) return false; if (reimbResolved == null) { if (other.reimbResolved != null) return false; } else if (!reimbResolved.equals(other.reimbResolved)) return false; if (reimbSubmitted == null) { if (other.reimbSubmitted != null) return false; } else if (!reimbSubmitted.equals(other.reimbSubmitted)) return false; if (resolverId != other.resolverId) return false; if (statusId != other.statusId) return false; if (typeId != other.typeId) return false; return true; } @Override public String toString() { return "Reimbursement [reimbId=" + reimbId + ", amount=" + amount + ", reimbSubmitted=" + reimbSubmitted + ", reimbResolved=" + reimbResolved + ", reimbDescription=" + reimbDescription + ", authorId=" + authorId + ", resolverId=" + resolverId + ", statusId=" + statusId + ", typeId=" + typeId + "]"; } }
/* * 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.test.web.reactive.server; import java.net.URI; import java.time.Duration; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseCookie; import org.springframework.mock.http.client.reactive.MockClientHttpRequest; import org.springframework.mock.http.client.reactive.MockClientHttpResponse; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.hamcrest.Matchers.equalTo; import static org.mockito.Mockito.mock; /** * Unit tests for {@link CookieAssertions} * @author Rossen Stoyanchev */ public class CookieAssertionTests { private final ResponseCookie cookie = ResponseCookie.from("foo", "bar") .maxAge(Duration.ofMinutes(30)) .domain("foo.com") .path("/foo") .secure(true) .httpOnly(true) .sameSite("Lax") .build(); private final CookieAssertions assertions = cookieAssertions(cookie); @Test void valueEquals() { assertions.valueEquals("foo", "bar"); assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertions.valueEquals("what?!", "bar")); assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertions.valueEquals("foo", "what?!")); } @Test void value() { assertions.value("foo", equalTo("bar")); assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertions.value("foo", equalTo("what?!"))); } @Test void exists() { assertions.exists("foo"); assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertions.exists("what?!")); } @Test void doesNotExist() { assertions.doesNotExist("what?!"); assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertions.doesNotExist("foo")); } @Test void maxAge() { assertions.maxAge("foo", Duration.ofMinutes(30)); assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertions.maxAge("foo", Duration.ofMinutes(29))); assertions.maxAge("foo", equalTo(Duration.ofMinutes(30).getSeconds())); assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> assertions.maxAge("foo", equalTo(Duration.ofMinutes(29).getSeconds()))); } @Test void domain() { assertions.domain("foo", "foo.com"); assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertions.domain("foo", "what.com")); assertions.domain("foo", equalTo("foo.com")); assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertions.domain("foo", equalTo("what.com"))); } @Test void path() { assertions.path("foo", "/foo"); assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertions.path("foo", "/what")); assertions.path("foo", equalTo("/foo")); assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertions.path("foo", equalTo("/what"))); } @Test void secure() { assertions.secure("foo", true); assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertions.secure("foo", false)); } @Test void httpOnly() { assertions.httpOnly("foo", true); assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertions.httpOnly("foo", false)); } @Test void sameSite() { assertions.sameSite("foo", "Lax"); assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> assertions.sameSite("foo", "Strict")); } private CookieAssertions cookieAssertions(ResponseCookie cookie) { MockClientHttpRequest request = new MockClientHttpRequest(HttpMethod.GET, URI.create("/")); MockClientHttpResponse response = new MockClientHttpResponse(HttpStatus.OK); response.getCookies().add(cookie.getName(), cookie); ExchangeResult result = new ExchangeResult( request, response, Mono.empty(), Mono.empty(), Duration.ZERO, null, null); return new CookieAssertions(result, mock()); } }
package codesquad.service; import codesquad.domain.User; import codesquad.domain.UserRepository; import codesquad.dto.LoginDTO; import codesquad.exception.UserVerificationException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.security.crypto.password.PasswordEncoder; import java.util.Optional; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class UserServiceTest { @Mock private UserRepository userRepository; @Mock private PasswordEncoder passwordEncoder; private User user; private LoginDTO loginDTO; @InjectMocks private UserService userService; @Before public void setUp() throws Exception { loginDTO = new LoginDTO(); user = new User(1L, "javajigi@tech.com", "12345678", "javajigi", "010-1234-5678"); } @Test(expected = UserVerificationException.class) public void isUniqueUser() { when(userRepository.findByEmail("javajigi@tech.com")).thenReturn(Optional.ofNullable(user)); userService.isUniqueUser(user.getEmail()); } @Test(expected = UserVerificationException.class) public void loginNotSignup() { when(userRepository.findByEmail(any())).thenReturn(Optional.empty()); loginDTO.setEmail(user.getEmail()); loginDTO.setPassword("123456"); userService.login(loginDTO); } @Test(expected = UserVerificationException.class) public void notMatchPassword() { when(userRepository.findByEmail(user.getEmail())).thenReturn(Optional.ofNullable(user)); when(passwordEncoder.matches("123456", user.getPassword())).thenReturn(false); loginDTO.setEmail(user.getEmail()); loginDTO.setPassword("123456"); userService.login(loginDTO); } }
/** * Sencha GXT 3.0.1 - Sencha for GWT * Copyright(c) 2007-2012, Sencha, Inc. * licensing@sencha.com * * http://www.sencha.com/products/gxt/license/ */ package com.sencha.gxt.explorer.client.chart; import java.util.Date; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.editor.client.Editor.Path; import com.google.gwt.event.logical.shared.AttachEvent; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.Widget; import com.google.gwt.user.datepicker.client.CalendarUtil; import com.sencha.gxt.chart.client.chart.Chart; import com.sencha.gxt.chart.client.chart.Chart.Position; import com.sencha.gxt.chart.client.chart.axis.NumericAxis; import com.sencha.gxt.chart.client.chart.axis.TimeAxis; import com.sencha.gxt.chart.client.chart.series.LineSeries; import com.sencha.gxt.chart.client.chart.series.Primitives; import com.sencha.gxt.chart.client.draw.RGB; import com.sencha.gxt.chart.client.draw.sprite.Sprite; import com.sencha.gxt.chart.client.draw.sprite.TextSprite; import com.sencha.gxt.core.client.ValueProvider; import com.sencha.gxt.data.shared.LabelProvider; import com.sencha.gxt.data.shared.ListStore; import com.sencha.gxt.data.shared.ModelKeyProvider; import com.sencha.gxt.data.shared.PropertyAccess; import com.sencha.gxt.examples.resources.client.model.Data; import com.sencha.gxt.examples.resources.client.model.Site; import com.sencha.gxt.explorer.client.model.Example.Detail; import com.sencha.gxt.widget.core.client.ContentPanel; import com.sencha.gxt.widget.core.client.FramedPanel; import com.sencha.gxt.widget.core.client.button.ToggleButton; import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer; import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer.VerticalLayoutData; import com.sencha.gxt.widget.core.client.toolbar.ToolBar; @Detail(name = "Live Chart", icon = "livechart", category = "Charts", classes = Data.class) public class LiveExample implements IsWidget, EntryPoint { public interface SitePropertyAccess extends PropertyAccess<Site> { ValueProvider<Site, Date> date(); @Path("date") ModelKeyProvider<Site> nameKey(); ValueProvider<Site, Double> veins(); ValueProvider<Site, Double> views(); ValueProvider<Site, Double> visits(); } private static final SitePropertyAccess siteAccess = GWT.create(SitePropertyAccess.class); private static final DateTimeFormat f = DateTimeFormat.getFormat("MMM d"); private Timer update; public Widget asWidget() { final Chart<Site> chart = new Chart<Site>(600, 400); chart.setDefaultInsets(20); final ListStore<Site> store = new ListStore<Site>(siteAccess.nameKey()); Date initial = f.parse("Feb 1"); for (int i = 0; i < 7; i++) { store.add(new Site(initial, Math.random() * 20 + 80, Math.random() * 20 + 40, Math.random() * 20)); initial = CalendarUtil.copyDate(initial); CalendarUtil.addDaysToDate(initial, 1); } chart.setStore(store); NumericAxis<Site> axis = new NumericAxis<Site>(); axis.setPosition(Position.LEFT); axis.addField(siteAccess.visits()); TextSprite title = new TextSprite("Number of Hits"); title.setFontSize(18); axis.setTitleConfig(title); axis.setDisplayGrid(true); axis.setMinimum(0); axis.setMaximum(100); chart.addAxis(axis); final TimeAxis<Site> time = new TimeAxis<Site>(); time.setField(siteAccess.date()); time.setStartDate(f.parse("Feb 1")); time.setEndDate(f.parse("Feb 7")); time.setLabelProvider(new LabelProvider<Date>() { @Override public String getLabel(Date item) { return f.format(item); } }); chart.addAxis(time); LineSeries<Site> series = new LineSeries<Site>(); series.setYAxisPosition(Position.LEFT); series.setYField(siteAccess.visits()); series.setStroke(new RGB(148, 174, 10)); series.setShowMarkers(true); series.setMarkerIndex(1); Sprite marker = Primitives.circle(0, 0, 6); marker.setFill(new RGB(148, 174, 10)); series.setMarkerConfig(marker); chart.addSeries(series); series = new LineSeries<Site>(); series.setYAxisPosition(Position.LEFT); series.setYField(siteAccess.views()); series.setStroke(new RGB(17, 95, 166)); series.setShowMarkers(true); series.setMarkerIndex(1); marker = Primitives.cross(0, 0, 6); marker.setFill(new RGB(17, 95, 166)); series.setMarkerConfig(marker); chart.addSeries(series); series = new LineSeries<Site>(); series.setYAxisPosition(Position.LEFT); series.setYField(siteAccess.veins()); series.setStroke(new RGB(166, 17, 32)); series.setShowMarkers(true); series.setMarkerIndex(1); marker = Primitives.diamond(0, 0, 6); marker.setFill(new RGB(166, 17, 32)); series.setMarkerConfig(marker); chart.addSeries(series); update = new Timer() { @Override public void run() { Date startDate = CalendarUtil.copyDate(time.getStartDate()); Date endDate = CalendarUtil.copyDate(time.getEndDate()); CalendarUtil.addDaysToDate(startDate, 1); CalendarUtil.addDaysToDate(endDate, 1); chart.getStore().add(new Site(endDate, Math.random() * 20 + 80, Math.random() * 20 + 40, Math.random() * 20)); time.setStartDate(startDate); time.setEndDate(endDate); chart.redrawChart(); } }; update.scheduleRepeating(1000); ToggleButton animation = new ToggleButton("Animate"); animation.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { chart.setAnimated(event.getValue()); } }); animation.setValue(true, true); ToolBar toolBar = new ToolBar(); toolBar.add(animation); ContentPanel panel = new FramedPanel(); panel.getElement().getStyle().setMargin(10, Unit.PX); panel.setCollapsible(true); panel.setHeadingText("Live Chart"); panel.setPixelSize(620, 500); panel.setBodyBorder(true); VerticalLayoutContainer layout = new VerticalLayoutContainer(); panel.add(layout); toolBar.setLayoutData(new VerticalLayoutData(1, -1)); layout.add(toolBar); chart.setLayoutData(new VerticalLayoutData(1, 1)); layout.add(chart); panel.addAttachHandler(new AttachEvent.Handler() { @Override public void onAttachOrDetach(AttachEvent event) { if (event.isAttached() == false) { update.cancel(); } } }); return panel; } @Override public void onModuleLoad() { RootPanel.get().add(asWidget()); } }
package tj.teacherjournal; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.design.widget.Snackbar; import android.support.v4.widget.NestedScrollView; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class AuthActivity extends AppCompatActivity implements View.OnClickListener { private final AppCompatActivity activity = AuthActivity.this; private EditText l_email, l_pass; private DBHelper dbHelper; private Button b_reg, b_log; public int arResult[]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_auth); b_reg = (Button) findViewById(R.id.b_reg); b_reg.setOnClickListener(this); b_log = (Button) findViewById(R.id.b_log); b_log.setOnClickListener(this); l_email = (EditText) findViewById(R.id.l_email); l_pass = (EditText) findViewById(R.id.l_pass); dbHelper = new DBHelper(this); } @Override public void onClick(View view) { String email = l_email.getText().toString(); String pass = l_pass.getText().toString(); SQLiteDatabase database = dbHelper.getWritableDatabase(); ContentValues contentValues = new ContentValues(); arResult = new int[50]; switch (view.getId()) { case R.id.b_reg: Intent intent_0; intent_0 = new Intent(AuthActivity.this, RegActivity.class); startActivity(intent_0); break; case R.id.b_log: // Тут всякая дичь на проверку данных с полей и запрос в БД CheckDataInBd(); break; } } /** * Этот метод предназначен для проверки входных текстовых полей и проверки учетных данных для входа в SQLite */ private void CheckDataInBd() { String email = l_email.getText().toString(); String pass = l_pass.getText().toString(); if(email.length() != 0 && pass.length() != 0) { if (dbHelper.checkUser(email.trim(), pass.trim())) { Intent accountsIntent = new Intent(activity, MainActivity.class); accountsIntent.putExtra("EMAIL", l_email.getText().toString().trim()); startActivity(accountsIntent); } else { // Выкидываем ему тостер о неправильно введеных данных Toast.makeText(this, "Неправильный логин или пароль!", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(this, "Одно или несколько полей не заполнены!", Toast.LENGTH_SHORT).show(); } } }
// // AuthServer.java // // Written by : Priyank Patel <pkpatel@cs.stanford.edu> // package Chat; // AWT/Swing import java.awt.*; import java.awt.event.*; import javax.swing.*; public class AuthServer { // Failure codes public static final int SUCCESS = 0; public static final int KEYSTORE_FILE_NOT_FOUND = 1; public static final int ERROR = 4; // The GUI AuthServerLoginPanel _panel; AuthServerActivityPanel _activityPanel; CardLayout _layout; JFrame _appFrame; AuthServerThread _thread; // Port number to listen on private int _portNum; private String asKeyStoreName; private String asKeyStorePassword; public String getAsKeyStoreName() { return asKeyStoreName; } public String getAsKeyStorePassword() { return asKeyStorePassword; } public AuthServer() throws Exception { _panel = null; _activityPanel = null; _layout = null; _appFrame = null; try { initialize(); } catch (Exception e) { System.out.println("AS error: " + e.getMessage()); e.printStackTrace(); } _layout.show(_appFrame.getContentPane(), "ASPanel"); } // AS initialization private void initialize() throws Exception { _appFrame = new JFrame("Authentication Server"); _layout = new CardLayout(); _appFrame.getContentPane().setLayout(_layout); _panel = new AuthServerLoginPanel(this); _appFrame.getContentPane().add(_panel, "ASPanel"); _activityPanel = new AuthServerActivityPanel(this); _appFrame.getContentPane().add(_activityPanel, "ActivityPanel"); _appFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { quit(); } }); } public void run() { _appFrame.pack(); _appFrame.setVisible(true); } // quit // // Called when the application is about to quit. public void quit() { try { System.out.println("quit called"); } catch (Exception err) { System.out.println("AuthServer error: " + err.getMessage()); err.printStackTrace(); } System.exit(0); } // // Start up the AS server // public int startup(String _ksFileName, char[] _privateKeyPass, int _asPort) { this._portNum = _asPort; this.asKeyStoreName = _ksFileName; this.asKeyStorePassword = String.valueOf( _privateKeyPass); _layout.show(_appFrame.getContentPane(), "ActivityPanel"); _thread = new AuthServerThread(this); _thread.start(); return AuthServer.SUCCESS; } public int getPortNumber() { return _portNum; } public JTextArea getOutputArea() { return _activityPanel.getOutputArea(); } // main // // Construct the AS panel, read in the passwords and give the // control back public static void main(String[] args) throws Exception { AuthServer as = new AuthServer(); as.run(); } }
/* ECE 5510 Final Project * Authors : Ekta Bindlish, Dave Kindel * File Description : Shared Counter Incremented by the CS for NUMA Locks */ package NUMA; public class SharedCounter { private int value; public SharedCounter(){ value = 0; } public int getAndIncrement(){ int temp = value; value = temp + 1; return temp; } }
package model; public class StuCourse { private String courseName; private String teacher; private String courseTime; private String courseNO; private String credit; public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public String getTeacher() { return teacher; } public void setTeacher(String teacher) { this.teacher = teacher; } public String getCourseTime() { return courseTime; } public void setCourseTime(String courseTime) { this.courseTime = courseTime; } public String getCourseNO() { return courseNO; } public void setCourseNO(String courseNO) { this.courseNO = courseNO; } public String getCredit() { return credit; } public void setCredit(String credit) { this.credit = credit; } }
package com.qfjy.project.meeting.bean; import lombok.Data; @Data public class Role { private Integer id; private String rname; private String remark; private Integer sortNum; private Integer status; }
package com.techboon.web.rest; import com.techboon.TechboonApp; import com.techboon.domain.Organization; import com.techboon.repository.OrganizationRepository; import com.techboon.service.OrganizationService; import com.techboon.web.rest.errors.ExceptionTranslator; import com.techboon.service.dto.OrganizationCriteria; import com.techboon.service.OrganizationQueryService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import java.util.List; import static com.techboon.web.rest.TestUtil.createFormattingConversionService; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import com.techboon.domain.enumeration.Country; /** * Test class for the OrganizationResource REST controller. * * @see OrganizationResource */ @RunWith(SpringRunner.class) @SpringBootTest(classes = TechboonApp.class) public class OrganizationResourceIntTest { private static final String DEFAULT_NAME = "AAAAAAAAAA"; private static final String UPDATED_NAME = "BBBBBBBBBB"; private static final Country DEFAULT_COUNTRY = Country.CHINA; private static final Country UPDATED_COUNTRY = Country.SWEDEN; private static final String DEFAULT_ADDRESS = "AAAAAAAAAA"; private static final String UPDATED_ADDRESS = "BBBBBBBBBB"; private static final String DEFAULT_CODE = "AAAA"; private static final String UPDATED_CODE = "BBBB"; private static final Boolean DEFAULT_ACTIVATED = false; private static final Boolean UPDATED_ACTIVATED = true; @Autowired private OrganizationRepository organizationRepository; @Autowired private OrganizationService organizationService; @Autowired private OrganizationQueryService organizationQueryService; @Autowired private MappingJackson2HttpMessageConverter jacksonMessageConverter; @Autowired private PageableHandlerMethodArgumentResolver pageableArgumentResolver; @Autowired private ExceptionTranslator exceptionTranslator; @Autowired private EntityManager em; private MockMvc restOrganizationMockMvc; private Organization organization; @Before public void setup() { MockitoAnnotations.initMocks(this); final OrganizationResource organizationResource = new OrganizationResource(organizationService, organizationQueryService); this.restOrganizationMockMvc = MockMvcBuilders.standaloneSetup(organizationResource) .setCustomArgumentResolvers(pageableArgumentResolver) .setControllerAdvice(exceptionTranslator) .setConversionService(createFormattingConversionService()) .setMessageConverters(jacksonMessageConverter).build(); } /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static Organization createEntity(EntityManager em) { Organization organization = new Organization() .name(DEFAULT_NAME) .country(DEFAULT_COUNTRY) .address(DEFAULT_ADDRESS) .code(DEFAULT_CODE) .activated(DEFAULT_ACTIVATED); return organization; } @Before public void initTest() { organization = createEntity(em); } @Test @Transactional public void createOrganization() throws Exception { int databaseSizeBeforeCreate = organizationRepository.findAll().size(); // Create the Organization restOrganizationMockMvc.perform(post("/api/organizations") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(organization))) .andExpect(status().isCreated()); // Validate the Organization in the database List<Organization> organizationList = organizationRepository.findAll(); assertThat(organizationList).hasSize(databaseSizeBeforeCreate + 1); Organization testOrganization = organizationList.get(organizationList.size() - 1); assertThat(testOrganization.getName()).isEqualTo(DEFAULT_NAME); assertThat(testOrganization.getCountry()).isEqualTo(DEFAULT_COUNTRY); assertThat(testOrganization.getAddress()).isEqualTo(DEFAULT_ADDRESS); assertThat(testOrganization.getCode()).isEqualTo(DEFAULT_CODE); assertThat(testOrganization.isActivated()).isEqualTo(DEFAULT_ACTIVATED); } @Test @Transactional public void createOrganizationWithExistingId() throws Exception { int databaseSizeBeforeCreate = organizationRepository.findAll().size(); // Create the Organization with an existing ID organization.setId(1L); // An entity with an existing ID cannot be created, so this API call must fail restOrganizationMockMvc.perform(post("/api/organizations") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(organization))) .andExpect(status().isBadRequest()); // Validate the Organization in the database List<Organization> organizationList = organizationRepository.findAll(); assertThat(organizationList).hasSize(databaseSizeBeforeCreate); } @Test @Transactional public void checkNameIsRequired() throws Exception { int databaseSizeBeforeTest = organizationRepository.findAll().size(); // set the field null organization.setName(null); // Create the Organization, which fails. restOrganizationMockMvc.perform(post("/api/organizations") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(organization))) .andExpect(status().isBadRequest()); List<Organization> organizationList = organizationRepository.findAll(); assertThat(organizationList).hasSize(databaseSizeBeforeTest); } @Test @Transactional public void checkCodeIsRequired() throws Exception { int databaseSizeBeforeTest = organizationRepository.findAll().size(); // set the field null organization.setCode(null); // Create the Organization, which fails. restOrganizationMockMvc.perform(post("/api/organizations") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(organization))) .andExpect(status().isBadRequest()); List<Organization> organizationList = organizationRepository.findAll(); assertThat(organizationList).hasSize(databaseSizeBeforeTest); } @Test @Transactional public void getAllOrganizations() throws Exception { // Initialize the database organizationRepository.saveAndFlush(organization); // Get all the organizationList restOrganizationMockMvc.perform(get("/api/organizations?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(organization.getId().intValue()))) .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME.toString()))) .andExpect(jsonPath("$.[*].country").value(hasItem(DEFAULT_COUNTRY.toString()))) .andExpect(jsonPath("$.[*].address").value(hasItem(DEFAULT_ADDRESS.toString()))) .andExpect(jsonPath("$.[*].code").value(hasItem(DEFAULT_CODE.toString()))) .andExpect(jsonPath("$.[*].activated").value(hasItem(DEFAULT_ACTIVATED.booleanValue()))); } @Test @Transactional public void getOrganization() throws Exception { // Initialize the database organizationRepository.saveAndFlush(organization); // Get the organization restOrganizationMockMvc.perform(get("/api/organizations/{id}", organization.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.id").value(organization.getId().intValue())) .andExpect(jsonPath("$.name").value(DEFAULT_NAME.toString())) .andExpect(jsonPath("$.country").value(DEFAULT_COUNTRY.toString())) .andExpect(jsonPath("$.address").value(DEFAULT_ADDRESS.toString())) .andExpect(jsonPath("$.code").value(DEFAULT_CODE.toString())) .andExpect(jsonPath("$.activated").value(DEFAULT_ACTIVATED.booleanValue())); } @Test @Transactional public void getAllOrganizationsByNameIsEqualToSomething() throws Exception { // Initialize the database organizationRepository.saveAndFlush(organization); // Get all the organizationList where name equals to DEFAULT_NAME defaultOrganizationShouldBeFound("name.equals=" + DEFAULT_NAME); // Get all the organizationList where name equals to UPDATED_NAME defaultOrganizationShouldNotBeFound("name.equals=" + UPDATED_NAME); } @Test @Transactional public void getAllOrganizationsByNameIsInShouldWork() throws Exception { // Initialize the database organizationRepository.saveAndFlush(organization); // Get all the organizationList where name in DEFAULT_NAME or UPDATED_NAME defaultOrganizationShouldBeFound("name.in=" + DEFAULT_NAME + "," + UPDATED_NAME); // Get all the organizationList where name equals to UPDATED_NAME defaultOrganizationShouldNotBeFound("name.in=" + UPDATED_NAME); } @Test @Transactional public void getAllOrganizationsByNameIsNullOrNotNull() throws Exception { // Initialize the database organizationRepository.saveAndFlush(organization); // Get all the organizationList where name is not null defaultOrganizationShouldBeFound("name.specified=true"); // Get all the organizationList where name is null defaultOrganizationShouldNotBeFound("name.specified=false"); } @Test @Transactional public void getAllOrganizationsByCountryIsEqualToSomething() throws Exception { // Initialize the database organizationRepository.saveAndFlush(organization); // Get all the organizationList where country equals to DEFAULT_COUNTRY defaultOrganizationShouldBeFound("country.equals=" + DEFAULT_COUNTRY); // Get all the organizationList where country equals to UPDATED_COUNTRY defaultOrganizationShouldNotBeFound("country.equals=" + UPDATED_COUNTRY); } @Test @Transactional public void getAllOrganizationsByCountryIsInShouldWork() throws Exception { // Initialize the database organizationRepository.saveAndFlush(organization); // Get all the organizationList where country in DEFAULT_COUNTRY or UPDATED_COUNTRY defaultOrganizationShouldBeFound("country.in=" + DEFAULT_COUNTRY + "," + UPDATED_COUNTRY); // Get all the organizationList where country equals to UPDATED_COUNTRY defaultOrganizationShouldNotBeFound("country.in=" + UPDATED_COUNTRY); } @Test @Transactional public void getAllOrganizationsByCountryIsNullOrNotNull() throws Exception { // Initialize the database organizationRepository.saveAndFlush(organization); // Get all the organizationList where country is not null defaultOrganizationShouldBeFound("country.specified=true"); // Get all the organizationList where country is null defaultOrganizationShouldNotBeFound("country.specified=false"); } @Test @Transactional public void getAllOrganizationsByAddressIsEqualToSomething() throws Exception { // Initialize the database organizationRepository.saveAndFlush(organization); // Get all the organizationList where address equals to DEFAULT_ADDRESS defaultOrganizationShouldBeFound("address.equals=" + DEFAULT_ADDRESS); // Get all the organizationList where address equals to UPDATED_ADDRESS defaultOrganizationShouldNotBeFound("address.equals=" + UPDATED_ADDRESS); } @Test @Transactional public void getAllOrganizationsByAddressIsInShouldWork() throws Exception { // Initialize the database organizationRepository.saveAndFlush(organization); // Get all the organizationList where address in DEFAULT_ADDRESS or UPDATED_ADDRESS defaultOrganizationShouldBeFound("address.in=" + DEFAULT_ADDRESS + "," + UPDATED_ADDRESS); // Get all the organizationList where address equals to UPDATED_ADDRESS defaultOrganizationShouldNotBeFound("address.in=" + UPDATED_ADDRESS); } @Test @Transactional public void getAllOrganizationsByAddressIsNullOrNotNull() throws Exception { // Initialize the database organizationRepository.saveAndFlush(organization); // Get all the organizationList where address is not null defaultOrganizationShouldBeFound("address.specified=true"); // Get all the organizationList where address is null defaultOrganizationShouldNotBeFound("address.specified=false"); } @Test @Transactional public void getAllOrganizationsByCodeIsEqualToSomething() throws Exception { // Initialize the database organizationRepository.saveAndFlush(organization); // Get all the organizationList where code equals to DEFAULT_CODE defaultOrganizationShouldBeFound("code.equals=" + DEFAULT_CODE); // Get all the organizationList where code equals to UPDATED_CODE defaultOrganizationShouldNotBeFound("code.equals=" + UPDATED_CODE); } @Test @Transactional public void getAllOrganizationsByCodeIsInShouldWork() throws Exception { // Initialize the database organizationRepository.saveAndFlush(organization); // Get all the organizationList where code in DEFAULT_CODE or UPDATED_CODE defaultOrganizationShouldBeFound("code.in=" + DEFAULT_CODE + "," + UPDATED_CODE); // Get all the organizationList where code equals to UPDATED_CODE defaultOrganizationShouldNotBeFound("code.in=" + UPDATED_CODE); } @Test @Transactional public void getAllOrganizationsByCodeIsNullOrNotNull() throws Exception { // Initialize the database organizationRepository.saveAndFlush(organization); // Get all the organizationList where code is not null defaultOrganizationShouldBeFound("code.specified=true"); // Get all the organizationList where code is null defaultOrganizationShouldNotBeFound("code.specified=false"); } @Test @Transactional public void getAllOrganizationsByActivatedIsEqualToSomething() throws Exception { // Initialize the database organizationRepository.saveAndFlush(organization); // Get all the organizationList where activated equals to DEFAULT_ACTIVATED defaultOrganizationShouldBeFound("activated.equals=" + DEFAULT_ACTIVATED); // Get all the organizationList where activated equals to UPDATED_ACTIVATED defaultOrganizationShouldNotBeFound("activated.equals=" + UPDATED_ACTIVATED); } @Test @Transactional public void getAllOrganizationsByActivatedIsInShouldWork() throws Exception { // Initialize the database organizationRepository.saveAndFlush(organization); // Get all the organizationList where activated in DEFAULT_ACTIVATED or UPDATED_ACTIVATED defaultOrganizationShouldBeFound("activated.in=" + DEFAULT_ACTIVATED + "," + UPDATED_ACTIVATED); // Get all the organizationList where activated equals to UPDATED_ACTIVATED defaultOrganizationShouldNotBeFound("activated.in=" + UPDATED_ACTIVATED); } @Test @Transactional public void getAllOrganizationsByActivatedIsNullOrNotNull() throws Exception { // Initialize the database organizationRepository.saveAndFlush(organization); // Get all the organizationList where activated is not null defaultOrganizationShouldBeFound("activated.specified=true"); // Get all the organizationList where activated is null defaultOrganizationShouldNotBeFound("activated.specified=false"); } /** * Executes the search, and checks that the default entity is returned */ private void defaultOrganizationShouldBeFound(String filter) throws Exception { restOrganizationMockMvc.perform(get("/api/organizations?sort=id,desc&" + filter)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(organization.getId().intValue()))) .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME.toString()))) .andExpect(jsonPath("$.[*].country").value(hasItem(DEFAULT_COUNTRY.toString()))) .andExpect(jsonPath("$.[*].address").value(hasItem(DEFAULT_ADDRESS.toString()))) .andExpect(jsonPath("$.[*].code").value(hasItem(DEFAULT_CODE.toString()))) .andExpect(jsonPath("$.[*].activated").value(hasItem(DEFAULT_ACTIVATED.booleanValue()))); } /** * Executes the search, and checks that the default entity is not returned */ private void defaultOrganizationShouldNotBeFound(String filter) throws Exception { restOrganizationMockMvc.perform(get("/api/organizations?sort=id,desc&" + filter)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$").isArray()) .andExpect(jsonPath("$").isEmpty()); } @Test @Transactional public void getNonExistingOrganization() throws Exception { // Get the organization restOrganizationMockMvc.perform(get("/api/organizations/{id}", Long.MAX_VALUE)) .andExpect(status().isNotFound()); } @Test @Transactional public void updateOrganization() throws Exception { // Initialize the database organizationService.save(organization); int databaseSizeBeforeUpdate = organizationRepository.findAll().size(); // Update the organization Organization updatedOrganization = organizationRepository.findOne(organization.getId()); // Disconnect from session so that the updates on updatedOrganization are not directly saved in db em.detach(updatedOrganization); updatedOrganization .name(UPDATED_NAME) .country(UPDATED_COUNTRY) .address(UPDATED_ADDRESS) .code(UPDATED_CODE) .activated(UPDATED_ACTIVATED); restOrganizationMockMvc.perform(put("/api/organizations") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(updatedOrganization))) .andExpect(status().isOk()); // Validate the Organization in the database List<Organization> organizationList = organizationRepository.findAll(); assertThat(organizationList).hasSize(databaseSizeBeforeUpdate); Organization testOrganization = organizationList.get(organizationList.size() - 1); assertThat(testOrganization.getName()).isEqualTo(UPDATED_NAME); assertThat(testOrganization.getCountry()).isEqualTo(UPDATED_COUNTRY); assertThat(testOrganization.getAddress()).isEqualTo(UPDATED_ADDRESS); assertThat(testOrganization.getCode()).isEqualTo(UPDATED_CODE); assertThat(testOrganization.isActivated()).isEqualTo(UPDATED_ACTIVATED); } @Test @Transactional public void updateNonExistingOrganization() throws Exception { int databaseSizeBeforeUpdate = organizationRepository.findAll().size(); // Create the Organization // If the entity doesn't have an ID, it will be created instead of just being updated restOrganizationMockMvc.perform(put("/api/organizations") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(organization))) .andExpect(status().isCreated()); // Validate the Organization in the database List<Organization> organizationList = organizationRepository.findAll(); assertThat(organizationList).hasSize(databaseSizeBeforeUpdate + 1); } @Test @Transactional public void deleteOrganization() throws Exception { // Initialize the database organizationService.save(organization); int databaseSizeBeforeDelete = organizationRepository.findAll().size(); // Get the organization restOrganizationMockMvc.perform(delete("/api/organizations/{id}", organization.getId()) .accept(TestUtil.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()); // Validate the database is empty List<Organization> organizationList = organizationRepository.findAll(); assertThat(organizationList).hasSize(databaseSizeBeforeDelete - 1); } @Test @Transactional public void equalsVerifier() throws Exception { TestUtil.equalsVerifier(Organization.class); Organization organization1 = new Organization(); organization1.setId(1L); Organization organization2 = new Organization(); organization2.setId(organization1.getId()); assertThat(organization1).isEqualTo(organization2); organization2.setId(2L); assertThat(organization1).isNotEqualTo(organization2); organization1.setId(null); assertThat(organization1).isNotEqualTo(organization2); } }
package com.example.selfhelpcity.bean; import lombok.AllArgsConstructor; import lombok.Data; /** * @author ljy */ @Data @AllArgsConstructor public class ChatBean { private int id; private int imageId; private String userName; private String chatContent; private String chatTime; }
import edu.princeton.cs.algs4.Bag; import edu.princeton.cs.algs4.SET; public class BoggleSolver { private final BoggleDict dict; public BoggleSolver(String[] dictionary) { // assume each word in dictionary contains only uppercase letters A through Z this.dict = new BoggleDict(dictionary); } public Iterable<String> getAllValidWords(BoggleBoard board) { int rows = board.rows(); int cols = board.cols(); // Create tiles Tile[] tiles = new Tile[rows * cols]; for (int y = 0; y < rows; y++) { for (int x = 0; x < cols; x++) { tiles[y * cols + x] = new Tile(x, y, board.getLetter(y, x)); } } // Precompute neighbor graph for (int y = 0; y < rows; y++) { for (int x = 0; x < cols; x++) { Tile tile = tiles[y * cols + x]; tile.neighbors = neighbors(x, y, tiles, rows, cols); } } return dfsRecursive(tiles, rows, cols); } private Iterable<String> dfsRecursive(Tile[] tiles, int rows, int cols) { SET<String> result = new SET<>(); for (int y = 0; y < rows; y++) { for (int x = 0; x < cols; x++) { // Run DFS for each tile on board Tile tile = tiles[y * cols + x]; dfsHelper(tile, result, new StringBuilder()); // Reset marking for start tile tile.marked = false; } } return result; } private void dfsHelper(Tile tile, SET<String> collector, StringBuilder word) { word.append(tile.letter == 'Q' ? "QU" : tile.letter); tile.marked = true; if (word.length() > 2 && this.dict.contains(word)) { // Found a match collector.add(word.toString()); } // Only continue exploring if there are words in the dict starting with the current prefix if (this.dict.hasKeyWithPrefix(word)) { // Continue search for (Tile neighbor : tile.neighbors) { if (!neighbor.marked) { dfsHelper(neighbor, collector, word); // Backtrack neighbor.marked = false; int start = neighbor.letter == 'Q' ? word.length() - 2 : word.length() - 1; word.delete(start, word.length()); } } } } private Iterable<Tile> neighbors(int x, int y, Tile[] tiles, int rows, int cols) { Bag<Tile> neighbors = new Bag<>(); for (int row = Math.max(0, y - 1); row <= Math.min(rows - 1, y + 1); row++) { for (int col = Math.max(0, x - 1); col <= Math.min(cols - 1, x + 1); col++) { if (row == y && col == x) { continue; } neighbors.add(tiles[row * cols + col]); } } return neighbors; } public int scoreOf(String word) { if (!this.dict.contains(word)) { // Word not in dictionary return 0; } int wordLength = word.length(); if (wordLength <= 2) return 0; if (wordLength <= 4) return 1; if (wordLength <= 5) return 2; if (wordLength <= 6) return 3; if (wordLength <= 7) return 5; return 11; } private class Tile { private final int x; private final int y; private final char letter; private boolean marked = false; private Iterable<Tile> neighbors; Tile(int x, int y, char letter) { this.x = x; this.y = y; this.letter = letter; } @Override public boolean equals(Object other) { if (other == this) return true; if (other == null) return false; if (other.getClass() != this.getClass()) return false; Tile that = (Tile) other; return this.x == that.x && this.y == that.y && letter == that.letter; } @Override public int hashCode() { int hashX = ((Integer) x).hashCode(); int hashY = ((Integer) y).hashCode(); int hashZ = ((Character) letter).hashCode(); return 31 * hashX + hashY + hashZ; } } }
package com.nisira.core.util; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.text.Html; import android.view.View; import android.view.WindowManager; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.nisira.core.entity.Usuario; import com.nisira.gcalderon.policesecurity.R; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.mapper.CannotResolveClassException; import com.thoughtworks.xstream.mapper.MapperWrapper; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Date; import java.util.List; /** * Created by vzavala on 08/11/2016. */ public final class Util { private static Integer confirmacion; public static boolean isOnLine(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnectedOrConnecting()) { return true; } return false; } public static void msgbox(Activity activity, String mensaje, String titulo){ AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setMessage(mensaje) .setTitle( Html.fromHtml("<font color='"+activity.getResources().getColor(R.color.colorPrimary)+"'>"+titulo+"</font>")) .setCancelable(false) .setNeutralButton("Aceptar", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } public static AlertDialog msgboxConfirmacion(Activity activity, String mensaje, String titulo){ confirmacion = 0; AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setMessage(mensaje.toString()) .setTitle( Html.fromHtml("<font color='"+activity.getResources().getColor(R.color.colorPrimary)+"'>"+titulo+"</font>")) .setCancelable(false) .setNegativeButton("NO", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }) .setPositiveButton("SI", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); final AlertDialog alert = builder.create(); alert.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); alert.show(); alert.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { confirmacion = 1; alert.dismiss(); } }); alert.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { confirmacion = -1; alert.dismiss(); } }); return alert; } /************************ AGREGADO by aburgos ***************************/ public static Object stringObject(String _class, String obj) throws ClassNotFoundException{ Class oClase = Class.forName(_class); XStream xstream= new XStream(){ protected MapperWrapper wrapMapper(MapperWrapper next) { return new MapperWrapper(next) { public boolean shouldSerializeMember(Class definedIn, String fieldName) { try { return definedIn != Object.class || realClass(fieldName) != null; } catch (CannotResolveClassException cnrce) { return false; } } }; } }; xstream.processAnnotations(oClase); Object object = (Object)xstream.fromXML(obj); return object; } public static List<? extends Object> stringListObject(String _class, String obj) throws ClassNotFoundException{ Class oClase = Class.forName(_class); XStream xstream= new XStream(){ protected MapperWrapper wrapMapper(MapperWrapper next) { return new MapperWrapper(next) { public boolean shouldSerializeMember(Class definedIn, String fieldName) { try { return definedIn != Object.class || realClass(fieldName) != null; } catch (CannotResolveClassException cnrce) { return false; } } }; } }; xstream.processAnnotations(oClase); List<? extends Object> object = (List<? extends Object>)xstream.fromXML(obj); return object; } public static Object stringGson(String _class,String obj) throws ClassNotFoundException{ Class oClase = Class.forName(_class); Gson gson = new Gson(); Object object = (Object)gson.fromJson(obj, oClase); return object; } public static List<? extends Object> stringListGson(String _class,String obj) throws ClassNotFoundException{ Class oClase = Class.forName(_class); Gson gson = new Gson(); List<? extends Object> object = (List<? extends Object>)gson.fromJson(obj, oClase); return object; } public static float convertTimeDecimal(String time){ if(time.equals("")) return Float.parseFloat(null); float timeF=0.0f; String[] parts = time.split(":"); int hora= Integer.parseInt(parts[0]); int minutos= Integer.parseInt(parts[1]); timeF=((float)hora)+((float)minutos/(float)60); return Math.round(timeF*100.0f)/100.0f; } public static String convertDecimalTime(double timeF){ String obj; int hora = (int)timeF; int minutos = (int)((timeF-(float)hora)*60); if(minutos==6) obj= hora+":"+minutos+"0"; else obj= hora+":"+minutos; return obj; } public static String objectGson(int total,Object obj){ Gson gson = new GsonBuilder().setPrettyPrinting().create(); return "{\"total\":"+total+",\"datos\":"+gson.toJson(obj)+"}"; } public static String objectGson(Object obj){ Gson gson = new GsonBuilder().setPrettyPrinting().create(); return gson.toJson(obj); } public static String objectXml(String _class,Object obj) throws ClassNotFoundException{ Class oClase = Class.forName(_class); String xml="<?xml version='1.0' encoding='ISO-8859-1'?>"; XStream xStream= new XStream(){ protected MapperWrapper wrapMapper(MapperWrapper next) { return new MapperWrapper(next) { public boolean shouldSerializeMember(Class definedIn, String fieldName) { try { return definedIn != Object.class || realClass(fieldName) != null; } catch (CannotResolveClassException cnrce) { return false; } } }; } }; xStream.processAnnotations(oClase); return xml+xStream.toXML(obj); } public static String idGeneradoTres(int id){ if(id<10) return "00"+id; else if(id<100) return "0"+id; else return String.valueOf(id); } public static Usuario session_object(Context context1){ Usuario user_session = new Usuario(); SharedPreferences prefs = context1.getSharedPreferences("USER_SESSION", context1.MODE_PRIVATE); user_session.setIdusuario(prefs.getString("IDUSUARIO", null)); user_session.setUsr_nombres(prefs.getString("USR_NOMBRES", null)); user_session.setIdclieprov(prefs.getString("IDCLIEPROV", null)); user_session.setEmail(prefs.getString("EMAIL", null)); user_session.setSincroniza(prefs.getBoolean("SINCRONIZAR",false)); return user_session; } public static float convertStringTimeFloat(final String time ){ if(time == null){ return 0.0f; }else if(time.trim().equals("")){ return 0.0f; }else if(time.trim().equals("__:__")){ return 0.0f; }else if(time.trim().equals("24:00")) return 0.0f; else if(time.trim().equals("00:00")) return 0.0f; else{ String[] horas_string = time.split(":"); if(horas_string.length==0){ return 0.0f; }else{ BigDecimal hora_decimal = new BigDecimal(horas_string[0]); BigDecimal minutos_decimal = new BigDecimal(horas_string[1]); BigDecimal fraccion = minutos_decimal.divide(new BigDecimal(60),2, BigDecimal.ROUND_HALF_UP); // fraccion=fraccion.setScale(0, RoundingMode.HALF_UP); return fraccion.add(hora_decimal).floatValue(); } } } public static String convertTimeFloatString(Float time){ if(time == null){ return ""; }else if(time.floatValue()==0.0f){ return "00:00"; }else{ BigDecimal number = new BigDecimal(time); int hora = number.intValue(); BigDecimal fraccion = number.remainder(BigDecimal.ONE).multiply(new BigDecimal(60)); fraccion=fraccion.setScale(0, RoundingMode.HALF_UP); int minutos = fraccion.intValue(); return idGeneradoDos(hora)+":"+idGeneradoDos(minutos); } } public static String idGeneradoDos(int id){ if(id<10) return "0"+id; else return String.valueOf(id); } public static String isnull(String valor, String valor2){ if (valor==null){ return valor2; } return valor; } public static String Conversionfecha(String fecha){ String result=""; String mes=""; String dia=""; String anio=""; String mesnum=""; try{ if(fecha!="") { if (fecha.length() == 11) { mes = fecha.substring(0, 3); dia = fecha.substring(4, 5); anio = fecha.substring(7, 11); } else { mes = fecha.substring(0, 3); dia = fecha.substring(4, 6); anio = fecha.substring(8, 12); } switch(mes){ case "ene": { mesnum="01"; break; } case "feb": { mesnum="02"; break; } case "mar": { mesnum="03"; break; } case "abr": { mesnum="04"; break; } case "may": { mesnum="05"; break; } case "jun": { mesnum="06"; break; } case "jul": { mesnum="07"; break; } case "ago": { mesnum="08"; break; } case "sep": { mesnum="09"; break; } case "oct": { mesnum="10"; break; } case "nov": { mesnum="11"; break; } case "dic": { mesnum="12"; break; } default: { mesnum="01"; break; } } result= anio+"-"+mesnum+"-"+dia; } else{ result=null; } }catch(Exception ex){} return result; } }
package com.zksyp.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created with Android Studio. * User:kaishen * Date:2017/5/23 * Time:上午10:02 * Desc: */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.CLASS) public @interface BindView4 { int value(); }
/* * Copyright 2002-2019 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.messaging.simp.stomp; import java.util.Arrays; import java.util.Collection; import java.util.EnumMap; import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.messaging.simp.SimpMessageType; import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller */ public class StompCommandTests { private static final Collection<StompCommand> destinationRequired = Arrays.asList(StompCommand.SEND, StompCommand.SUBSCRIBE, StompCommand.MESSAGE); private static final Collection<StompCommand> subscriptionIdRequired = Arrays.asList(StompCommand.SUBSCRIBE, StompCommand.UNSUBSCRIBE, StompCommand.MESSAGE); private static final Collection<StompCommand> contentLengthRequired = Arrays.asList(StompCommand.SEND, StompCommand.MESSAGE, StompCommand.ERROR); private static final Collection<StompCommand> bodyAllowed = Arrays.asList(StompCommand.SEND, StompCommand.MESSAGE, StompCommand.ERROR); private static final Map<StompCommand, SimpMessageType> messageTypes = new EnumMap<>(StompCommand.class); static { messageTypes.put(StompCommand.STOMP, SimpMessageType.CONNECT); messageTypes.put(StompCommand.CONNECT, SimpMessageType.CONNECT); messageTypes.put(StompCommand.DISCONNECT, SimpMessageType.DISCONNECT); messageTypes.put(StompCommand.SUBSCRIBE, SimpMessageType.SUBSCRIBE); messageTypes.put(StompCommand.UNSUBSCRIBE, SimpMessageType.UNSUBSCRIBE); messageTypes.put(StompCommand.SEND, SimpMessageType.MESSAGE); messageTypes.put(StompCommand.MESSAGE, SimpMessageType.MESSAGE); } @Test public void getMessageType() throws Exception { for (StompCommand stompCommand : StompCommand.values()) { SimpMessageType simp = messageTypes.get(stompCommand); if (simp == null) { simp = SimpMessageType.OTHER; } assertThat(stompCommand.getMessageType()).isSameAs(simp); } } @Test public void requiresDestination() throws Exception { for (StompCommand stompCommand : StompCommand.values()) { assertThat(stompCommand.requiresDestination()).isEqualTo(destinationRequired.contains(stompCommand)); } } @Test public void requiresSubscriptionId() throws Exception { for (StompCommand stompCommand : StompCommand.values()) { assertThat(stompCommand.requiresSubscriptionId()).isEqualTo(subscriptionIdRequired.contains(stompCommand)); } } @Test public void requiresContentLength() throws Exception { for (StompCommand stompCommand : StompCommand.values()) { assertThat(stompCommand.requiresContentLength()).isEqualTo(contentLengthRequired.contains(stompCommand)); } } @Test public void isBodyAllowed() throws Exception { for (StompCommand stompCommand : StompCommand.values()) { assertThat(stompCommand.isBodyAllowed()).isEqualTo(bodyAllowed.contains(stompCommand)); } } }
package br.com.filemanager.ejb.dao; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import javax.ejb.Stateless; import javax.persistence.PersistenceException; import br.com.filemanager.ejb.model.Usuario; @Stateless public class UsuarioDAO extends GenericDAO<Usuario> { public UsuarioDAO() { super(Usuario.class); } public void gravarUsuario(Usuario usuario) throws SQLException { save(usuario); } public void atualizarUsuario(Usuario usuario) throws PersistenceException { update(usuario); } public void removerUsuario(Usuario usuario) throws PersistenceException { delete(usuario); } public Usuario listarUsuario(String usuario, String senha) throws Exception { Map<String, Object> parametros = new HashMap<String, Object>(); parametros.put("usuario", usuario); parametros.put("senha", senha); try { return findOneResult("Usuario.findByUserAndPass", parametros); }catch(Exception e) { throw new Exception(e); } } }
import java.io.*; import java.util.*; public class Time { int hh,mm; int timeInMinutes = 0; public Time(){ hh=0; mm=0; } void readTime() throws IOException{ Calendar cal = new GregorianCalendar(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter Hours "); hh = Integer.parseInt(br.readLine()); System.out.println("Enter Minutes "); mm = Integer.parseInt(br.readLine()); } void displayTime(){ System.out.println("Time is "+hh+" : "+mm); } int timeToMinutes(){ timeInMinutes = hh*60; timeInMinutes = timeInMinutes+mm; return timeInMinutes; } void minutesToTime(int m){ if(m<0) m=m*(-1); hh = m/60; mm = m%60; System.out.println("Minutes : "+m); System.out.println("Hours : "+hh+" Minutes : "+mm); } static void diffTime(Time t1,Time t2){ int T1mins = t1.timeToMinutes(); int T2mins = t2.timeToMinutes(); if(T1mins<T2mins){ t1.minutesToTime(T2mins-T1mins); } else { System.out.println("Over Night Session"); t1.minutesToTime((1440-T1mins)+T2mins); } } public static void main(String[] args) throws IOException{ Time startTime = new Time(); Time endTime = new Time(); String user,pass; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter Username"); user = br.readLine(); System.out.println("Enter Password"); pass = br.readLine(); if(user.equals(pass)){ System.out.println("Login Successful"); startTime.readTime(); startTime.displayTime(); } else System.exit(1); System.out.println("Press 0 to log out"); while (true) { if (br.readLine().equals("0")) { endTime.readTime(); endTime.displayTime(); break; } } diffTime(startTime,endTime); } }
package models; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.HashMap; public class GistsDto { @AllArgsConstructor @NoArgsConstructor @Data @JsonIgnoreProperties(ignoreUnknown = true) public static class GistDetails { private String url; private String id; private HashMap<String, FileDto> files; } }
/** * Nathan West * CSMC 255 * Project 4 – Reaction Analysis * * This program displays a menu and * prompts the user to choose one of the various options. * Once the user chooses, the program will compare user input * to the movieReviews.txt file. */ import java.util.*; import java.io.*; public class ReactionAnalysis { // Main method that controls the program public static void main(String[] args) throws FileNotFoundException { // TODO Auto-generated method stub printHeading(); File movieReviews = new File("movieReviews.txt"); Scanner fileReader = new Scanner(movieReviews); Scanner scan = new Scanner(System.in); displayMenu(); String input = scan.nextLine(); while (!input.equals("5")) { runMenu(input, scan, fileReader,movieReviews); fileReader = new Scanner(movieReviews); scan = new Scanner(System.in); displayMenu(); input = scan.nextLine(); } System.out.println("Exiting the program... Thank you!"); } // Project information private static void printHeading() { System.out.println("-----------------------------"); System.out.println("Nathan West"); System.out.println("CSMC 255"); System.out.println("Programming Project 4"); System.out.println("Reaction Analysis Application"); System.out.println("-----------------------------"); } // Displays the menu for the user public static void displayMenu() { System.out.println("\nWhat would you like to do?"); System.out.println("1: Get the score of a word"); System.out.println("2: Get the average score of words in a file (one word per line)"); System.out.println("3: Find the highest/lowest scoring words in a file"); System.out.println("4: Sort words from a file into positive.txt and negative.txt"); System.out.println("5: Exit the program"); System.out.print("Enter a number 1-5: "); } // This method runs the menu for the program public static void runMenu(String in, Scanner input, Scanner fileReader, File movieReviews) throws FileNotFoundException { switch (in) { case "1": getAverageScore(input, fileReader, movieReviews); break; case "2": getAverageFileScore(input, fileReader, movieReviews); break; case "3": getMostPosNegWord(input, fileReader, movieReviews); break; case "4": sortWordsToFiles(input, fileReader, movieReviews); break; default: break; } } /* This method displays the average score for * a searched word and the number of * times the word appears throughout movieReviews.txt */ public static void getAverageScore(Scanner input, Scanner fileReader, File movieReviews) throws FileNotFoundException { System.out.print("Search for a word: "); String word = input.nextLine(); char lineNumber; double count = 0, total = 0 ,average; while (fileReader.hasNextLine()) { String line = fileReader.nextLine(); if (line.contains(word)) { count++; lineNumber = line.charAt(0); double number = Double.parseDouble(Character.toString(lineNumber)); total = total + number; } } fileReader.close(); average = (total / count); System.out.println(); System.out.println(word + " appears " + count + " times in the file."); System.out.printf("The average score of reviews contain the word " + word + " is " + "%.5f", average); System.out.println(); fileReader = new Scanner(movieReviews); } /* * This method calculates and displays the average score for a searched file */ public static void getAverageFileScore(Scanner input, Scanner fileReader, File movieReviews) throws FileNotFoundException { System.out.print("Enter the name of the file with the words you want the average score for: "); File file = new File(input.next()); while (!file.exists()) { System.out.println("Please enter a valid file:"); file = new File(input.next()); } Scanner txtScan = new Scanner(file); double count, average, total, number, wordCount = 0; double totalWordAvg = 0, fileAverage; char lineNumber; String word; while (txtScan.hasNextLine()) { word = txtScan.nextLine(); wordCount++; count = 0; total = 0; number = 0; while (fileReader.hasNextLine()) { String line = fileReader.nextLine(); if (line.contains(word)) { count++; lineNumber = line.charAt(0); number = Double.parseDouble(Character.toString(lineNumber)); total = total + number; } } average = total / count; totalWordAvg = totalWordAvg + average; fileReader = new Scanner(movieReviews); } fileReader.close(); txtScan.close(); fileAverage = (totalWordAvg / wordCount); if (fileAverage < 1.99) { System.out.println(); System.out.printf("The average score of words in " + file + " is " + "%.5f", fileAverage); System.out.println(); System.out.println("The overall sentiment of " + file + " is negative"); } else if (fileAverage > 2.01) { System.out.println(); System.out.printf("The average score of words in " + file + " is " + "%.5f", fileAverage); System.out.println(); System.out.println("The overall sentiment of " + file + " is positive"); } else { System.out.printf("The average score of words in " + file + " is " + "%.5f", fileAverage); System.out.println(); System.out.println("The overall sentiment of " + file + " is neutral"); } } /* * This method prompts the user for a file and * calculates and displays the most * positive and negative word by computing * each word's (from the searched file) average */ public static void getMostPosNegWord(Scanner input, Scanner fileReader, File movieReviews) throws FileNotFoundException { System.out.print("Enter a name of the file with words you want to score: "); File file = new File(input.next()); while (!file.exists()) { System.out.println("Please enter a valid file:"); file = new File(input.next()); } Scanner txtScan = new Scanner(file); double average, number, total = 0, count = 0; double lowestAvg = 1.99, highestAvg = 2.01; char lineNumber; String word, lowestWord = null, highestWord = null; while (txtScan.hasNextLine()) { word = txtScan.nextLine(); while (fileReader.hasNextLine()) { String line = fileReader.nextLine(); if (line.contains(word)) { count++; lineNumber = line.charAt(0); number = Double.parseDouble(Character.toString(lineNumber)); total = total + number; } } average = total / count; if (average < lowestAvg) { lowestWord = word; lowestAvg = average; } if (average > highestAvg) { highestWord = word; highestAvg = average; } fileReader = new Scanner(movieReviews); count = 0; number = 0; total = 0; } txtScan.close(); fileReader.close(); System.out.println(); System.out.printf("The most positive word, with a score of " + "%.5f" + " is " + highestWord, highestAvg); System.out.println(); System.out.printf("The most negative word, with a score of " + "%.5f" + " is " + lowestWord, lowestAvg); System.out.println(); } /* * This method prompts the user for a file and * sorts it's contents to positive and * negative text files by calculating * each word's (from the searched file) average */ public static void sortWordsToFiles(Scanner input, Scanner fileReader, File movieReviews) throws FileNotFoundException { System.out.print("Enter the name of the file with the words you want the average score for: "); File file = new File(input.next()); while (!file.exists()) { System.out.println("Please enter a valid file:"); file = new File(input.next()); } PrintWriter posWriter = new PrintWriter(new File("positive.txt")); PrintWriter negWriter = new PrintWriter(new File("negative.txt")); Scanner txtScan = new Scanner(file); double average, number, total = 0, count = 0; double lowestAvg = 1.9, highestAvg = 2.1; char lineNumber; String word, lowestWord = null, highestWord = null; while (txtScan.hasNextLine()) { word = txtScan.nextLine(); while (fileReader.hasNextLine()) { String line = fileReader.nextLine(); if (line.contains(word)) { count++; lineNumber = line.charAt(0); number = Double.parseDouble(Character.toString(lineNumber)); total = total + number; } } average = total / count; if (average < lowestAvg) { lowestWord = word; negWriter.println(lowestWord); } if (average > highestAvg) { highestWord = word; posWriter.println(highestWord); } fileReader = new Scanner(movieReviews); count = 0; number = 0; total = 0; } posWriter.close(); negWriter.close(); txtScan.close(); fileReader.close(); System.out.println(); System.out.println("Files have been created!"); } }