text
stringlengths
10
2.72M
package com.biotag.vehiclenumberscanning; import android.content.Context; public class UIUtils { public static Context getContext() { return VehiclenumberscanningApplication.getApplication(); } }
package br.com.douglastuiuiu.biometricengine.resource.handler; import br.com.douglastuiuiu.biometricengine.exception.ConflictException; import br.com.douglastuiuiu.biometricengine.exception.NotFoundException; import br.com.douglastuiuiu.biometricengine.exception.NotProcessedException; import br.com.douglastuiuiu.biometricengine.exception.ServiceException; import br.com.douglastuiuiu.biometricengine.util.ApiUtil; import br.com.douglastuiuiu.biometricengine.util.MessageLocale; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageConversionException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.*; /** * @author douglasg * @since 10/03/2017 */ @ControllerAdvice(annotations = RestController.class) public class ApiValidatorExceptionHandler { private Logger logger = LoggerFactory.getLogger(ApiValidatorExceptionHandler.class); @Autowired private MessageLocale messageLocale; /** * Erros gerados pela validação dos dados da requisição * * @param error * @return */ @ExceptionHandler(value = MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ResponseEntity<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException error) { logger.error("MethodArgumentNotValidException: " + error, error); return ApiUtil.responseErrorValidation(error); } /** * Erros relacionados a regras de negócio * * @param error * @return */ @ExceptionHandler(value = ServiceException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ResponseEntity<Object> handleServiceException(ServiceException error) { logger.error("ServiceException: " + error, error); return ApiUtil.responseError(error.getMessage(), HttpStatus.BAD_REQUEST); } /** * Validação de itens não existentes ou não encontrados * * @param error * @return */ @ExceptionHandler(value = NotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) @ResponseBody public ResponseEntity<Object> handleNotFoundException(NotFoundException error) { logger.error("notFoundException: " + error, error); return ApiUtil.responseError(error.getMessage(), HttpStatus.NOT_FOUND); } /** * Validação para quando tenta-se atualizar um registro com um status que não permite essa atualização * * @param error * @return */ @ExceptionHandler(value = ConflictException.class) @ResponseStatus(HttpStatus.CONFLICT) @ResponseBody public ResponseEntity<Object> handleConflictException(ConflictException error) { logger.error("conflictException: " + error, error); return ApiUtil.responseError(error.getMessage(), HttpStatus.CONFLICT); } /** * Validação para quando tenta-se buscar o resultado de uma análise que ainda não foi processada pelo bureau * * @param error * @return */ @ExceptionHandler(value = NotProcessedException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ResponseEntity<Object> handleNotProcessedException(NotProcessedException error) { logger.error("notProcessedException: " + error, error); return ApiUtil.responseError(error.getMessage(), HttpStatus.BAD_REQUEST); } /** * Erros relacionado ao envio de dados com formato ou tipo inválido * * @param error * @return */ @ExceptionHandler(value = HttpMessageConversionException.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ResponseBody public ResponseEntity<Object> handleException(HttpMessageConversionException error) { logger.error("HttpMessageConversionException: " + error, error); return ApiUtil.responseError(error.getLocalizedMessage(), HttpStatus.BAD_REQUEST); } /** * Pega Qualquer outro erro não tratado * * @param error * @return */ @ExceptionHandler(value = Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ResponseBody public ResponseEntity<Object> handleException(Exception error) { logger.error("Erro não tratado: " + error, error); return ApiUtil.responseError(messageLocale.getMessage("error.generic_error"), HttpStatus.BAD_REQUEST); } }
package alien4cloud.tosca.parser.mapping; import alien4cloud.tosca.parser.ParsingContextExecution; public abstract class DefaultDeferredParser<T> extends DefaultParser<T> { @Override public boolean isDeferred(ParsingContextExecution context) { return true; } }
/** * Class for Professors */ public class Professor { /* Members and Properties */ /** * This is the firstName of this professor */ private String firstName; /** * This is the surname of this professor */ private String surname; /** * This is the salary per year of this professor */ private float salary; /** * {@link Professor#firstName} */ public String getFirstName() { return this.firstName; } /** * {@link Professor#firstName} * * @param firstName the first name of the Professor to set */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * {@link Professor#surname} */ public String getSurname() { return this.surname; } /** * {@link Professor#surname} * * @param surname the first name of the Professor to set */ public void setSurname(String surname) { this.surname = surname; } /** * {@link Professor#salary} */ public float getSalary() { return this.salary; } /** * {@link Professor#salary} * * @param salary the salary per year of this professor */ public void setSalary(float salary) { this.salary = salary; } /* Constructor */ /** * Creates a nameless professor, without a salary * Poor lad :( * * @return returns a professor instance */ public Professor() { //stuff } /** * Creates a professor with the given params * * @param surname yes, guess what * @param firstName okay, I admit, this is harder to guess * @param salary, how much this guy is earning a year * @return returns a professor instance */ public Professor(String surname, String firstName, float salary) { //stuff, but with params } /* Methods */ /** * Prints the name of this professor * * @return Nothing, but it does print something somewhere */ public void printName() { //check if we know the name of the professor if(this.firstName == null || this.surname == null || this.firstName.isEmpty() || this.surname.isEmpty()) { //We haven't learned exception throwing yet, so let's just output something and return :'( System.out.println("Error: This Professor is nameless, I'm sorry :("); return; } System.out.println(String.format("", this.firstName, this.surname)); } /** * Calculates the salary for a given month * * @param month enter a number for the month (Jan = 1, Feb = 2, ...) * @return returns the salary for the given month (hopefully) */ public float calculateSalary(int month) { float calculatedSalary = this.salary / 14.0f; switch(month) { case 3: case 6: case 9: case 12: //what a lucky boy (or girl) this professor is calculatedSalary *= 1.5; break; default: //I have no idea whether java accepts switch case without the default, //so better be safe and just put it here. break; } return calculatedSalary; } }
package Project3.Project3Solutions; public class ThreeEvenOdd { /* Given an int array as a parameter return true if the array contains either 3 even or 3 odd values . for Example: intArray([2, 1, 3, 5]) result should be true intArray([2, 1, 2, 5]) result should be false intArray([2, 4, 2, 5]) result should be true */ public boolean threeEvenOrOdd(int[] intArr){ int evenCounter = 0 ; int oddCounter = 0 ; for(int i = 0 ; i< intArr.length ; i++){ if(intArr[i]%2==0){ evenCounter++; }else{ oddCounter++; } } boolean result = false; if(evenCounter==3 || oddCounter==3){ result= true; } return result; } }
package Service; import Dao.dao.HotGoodsMapper; import Dao.dao.SaleGoodsClickNumberMapper; import Dao.dao.SaleGoodsMapper; import Dao.model.HotGoods; import Dao.model.SaleGoods; import Dao.model.SaleGoodsClickNumber; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2014/9/13 0013. */ @Service public class HotGoodsService { @Autowired(required = false) private SaleGoodsClickNumberMapper saleGoodsClickNumberMapper; @Autowired(required = false) private SaleGoodsMapper saleGoodsMapper; @Autowired(required = false) private HotGoodsMapper hotGoodsMapper; @Autowired private GoodsImagesService goodsImagesService; private static Logger logger = LoggerFactory.getLogger(HotGoodsService.class); @Scheduled(cron = "0 0 3 * * ?") public void getHotGoods(){ try { hotGoodsMapper.deleteAll(); List<SaleGoodsClickNumber> list = saleGoodsClickNumberMapper.selectAll(); //System.out.println(list.get(0).getSalegoodsid()); List<SaleGoods> goodsList = new ArrayList<SaleGoods>(); System.out.println(goodsList.size()); for (int i = 0; i < 6; i++) { SaleGoods saleGoods = saleGoodsMapper.selectByPrimaryKey(list.get(i).getSalegoodsid()); goodsList.add(saleGoods); } //get hot goods list //System.out.println(goodsList.get(0).getHeadline()); HotGoods hotGoods = new HotGoods(); for (int i = 0; i < goodsList.size(); i++){ int goodsId = goodsList.get(i).getSalegoodsid(); hotGoods.setSalegoodsid(goodsId); List<String> strings = goodsImagesService.findImageBySaleGoodsId(goodsId); String imageUrl = strings.get(0); hotGoods.setHotgoodsimage(imageUrl); hotGoods.setHotgoodsid(i + 1); hotGoodsMapper.insert(hotGoods); } } catch (Exception ex){ logger.error("exception in ShowHotGoodsService.getHotGoods",ex); //return null; } } public List<HotGoods> showGotHoods(){ return hotGoodsMapper.selectAll(); } }
package io.github.cottonmc.libcd.impl; import java.util.Map; import net.minecraft.class_2960; import net.minecraft.class_4567; import net.minecraft.class_52; public interface LootTableMapAccessor { Map<class_2960, class_52> libcd$getLootTableMap(); void libcd$setLootTableMap(Map<class_2960, class_52> map); class_4567 libcd$getConditionManager(); }
package Lector19.Store; import java.util.ArrayList; import java.util.List; public class ReceiptArchive { private static List<Receipt> archive = new ArrayList<>(); private final static Object lock = new Object(); static void add(Receipt receipt) { synchronized (lock) { archive.add(receipt); } } static int size() { synchronized (lock) { return archive.size(); } } }
package com.lsjr.zizi.chat.broad; import android.content.Context; import android.content.Intent; import com.ymz.baselibrary.utils.UIUtils; /** * 用于聊天消息的广播,更新MainActivity Tab栏显示的未读数量 和 消息界面数据的更新 * */ public class MsgBroadcast { public static final String ACTION_MSG_UI_UPDATE = UIUtils.getPackageName() + ".action.msg_ui_update";// 界面的更新 public static final String ACTION_MSG_NUM_UPDATE = UIUtils.getPackageName() + ".intent.action.msg_num_update";// 未读数量的更新 public static final String ACTION_MSG_NUM_RESET = UIUtils.getPackageName() + ".action.msg_num_reset";// 未读数量需要重置,即从数据库重新查 public static final String EXTRA_NUM_COUNT = "count"; public static final String EXTRA_NUM_OPERATION = "operation"; public static final int NUM_ADD = 0;// 消息加 public static final int NUM_REDUCE = 1;// 消息减 /** * 更新消息Fragment的广播 * * @return */ public static void broadcastMsgUiUpdate(Context context) { context.sendBroadcast(new Intent(ACTION_MSG_UI_UPDATE)); } public static void broadcastMsgNumReset(Context context) { context.sendBroadcast(new Intent(ACTION_MSG_NUM_RESET)); } public static void broadcastMsgNumUpdate(Context context, boolean add, int count) { Intent intent = new Intent(ACTION_MSG_NUM_UPDATE); intent.putExtra(EXTRA_NUM_COUNT, count); if (add) { intent.putExtra(EXTRA_NUM_OPERATION, NUM_ADD); } else { intent.putExtra(EXTRA_NUM_OPERATION, NUM_REDUCE); } context.sendBroadcast(intent); } }
package me.dags.DeathHockey.Game.Utilities; import me.dags.DeathHockey.DeathHockey; import org.bukkit.*; import org.bukkit.entity.Firework; import org.bukkit.entity.Player; import org.bukkit.inventory.meta.FireworkMeta; import java.lang.reflect.Field; /** * @author dags_ <dags@dags.me> */ public class FireworkUtils { public static void scoreFireworks(String col) { FireworkEffect.Builder builder = FireworkEffect.builder(); FireworkEffect ffx = null; if (col.equals("red")) { builder.withColor(Color.RED); builder.withTrail(); builder.withFlicker(); builder.with(FireworkEffect.Type.CREEPER); } if (col.equals("blue")) { builder.withColor(Color.BLUE); builder.withTrail(); builder.withFlicker(); builder.with(FireworkEffect.Type.STAR); } ffx = builder.build(); Player p = Bukkit.getPlayer(DeathHockey.game.getPuck().getName()); Location l = p.getLocation(); World w = p.getWorld(); Firework fw = w.spawn(l, Firework.class); FireworkMeta fwm = fw.getFireworkMeta(); fwm.clearEffects(); fwm.addEffects(ffx); Field f; try { f = fwm.getClass().getDeclaredField("power"); f.setAccessible(true); f.set(fwm, -2); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } fw.setFireworkMeta(fwm); } }
package edu.mit.needlstk; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTree; import java.util.List; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.HashMap; /// A class for augmentable predicates, which predicates are mostly constructed from predicates /// within aggregation function bodies. The class structure mirrors the structure of predicates in /// the language grammar. /// This code is unfortunate boilerplate resulting from an implicit design choice of ANTLR in /// considering all ASTs as parse trees, i.e., ones generated from parsing. It appears they don't /// consider usecases where ASTs are constructed and augmented in the code itself. There are other /// custom mechanisms, like context-independent rewriting (using the => within the .g4 grammar /// file), but this seems to tie the grammar to specific manipulations in the compiler application. public class AugPred { /// Enum that defines types of predicates available public enum AugPredType { PRED_TRUE, // True PRED_FALSE, // False PRED_ID, // `identifier`, which is a pre-assigned predicate. PRED_EQ, // expr == expr PRED_NE, // expr != expr PRED_GT, // expr > expr PRED_LT, // expr < expr PRED_AND, // pred && pred PRED_OR, // pred || pred PRED_NOT // ! pred }; /// Type enum identifying the structure of the tree public AugPredType type; /// If this is a compound predicate (predAnd, etc.), this contains the child predicates. According /// to the grammar, it's enough to have at most two children, so this declaration allows for more /// general predicate trees than the grammar. public List<AugPred> childPreds; /// If this is a simple predicate (exprEq, etc.), this contains the child expressions. public List<AugExpr> childExprs; /// If this is an "identifier" predicate, store the identifier. public String predId; /// Default constructor with an input PredicateContext ctx public AugPred(PerfQueryParser.PredicateContext ctx) { if(ctx instanceof PerfQueryParser.TruePredContext) { this.type = AugPredType.PRED_TRUE; } else if(ctx instanceof PerfQueryParser.FalsePredContext) { this.type = AugPredType.PRED_FALSE; } else if(ctx instanceof PerfQueryParser.ExprEqContext) { this.type = AugPredType.PRED_EQ; PerfQueryParser.ExprEqContext newCtx = (PerfQueryParser.ExprEqContext)ctx; this.childExprs = makeExprChildren(new AugExpr(newCtx.expr(0)), new AugExpr(newCtx.expr(1))); } else if(ctx instanceof PerfQueryParser.ExprGtContext) { this.type = AugPredType.PRED_GT; PerfQueryParser.ExprGtContext newCtx = (PerfQueryParser.ExprGtContext)ctx; this.childExprs = makeExprChildren(new AugExpr(newCtx.expr(0)), new AugExpr(newCtx.expr(1))); } else if(ctx instanceof PerfQueryParser.ExprLtContext) { this.type = AugPredType.PRED_LT; PerfQueryParser.ExprLtContext newCtx = (PerfQueryParser.ExprLtContext)ctx; this.childExprs = makeExprChildren(new AugExpr(newCtx.expr(0)), new AugExpr(newCtx.expr(1))); } else if(ctx instanceof PerfQueryParser.ExprNeContext) { this.type = AugPredType.PRED_NE; PerfQueryParser.ExprNeContext newCtx = (PerfQueryParser.ExprNeContext)ctx; this.childExprs = makeExprChildren(new AugExpr(newCtx.expr(0)), new AugExpr(newCtx.expr(1))); } else if(ctx instanceof PerfQueryParser.PredAndContext) { this.type = AugPredType.PRED_AND; PerfQueryParser.PredAndContext newCtx = (PerfQueryParser.PredAndContext)ctx; this.childPreds = makePredChildren(new AugPred(newCtx.predicate(0)), new AugPred(newCtx.predicate(1))); } else if(ctx instanceof PerfQueryParser.PredOrContext) { this.type = AugPredType.PRED_OR; PerfQueryParser.PredOrContext newCtx = (PerfQueryParser.PredOrContext)ctx; this.childPreds = makePredChildren(new AugPred(newCtx.predicate(0)), new AugPred(newCtx.predicate(1))); } else if(ctx instanceof PerfQueryParser.PredNotContext) { this.type = AugPredType.PRED_NOT; PerfQueryParser.PredNotContext newCtx = (PerfQueryParser.PredNotContext)ctx; this.childPreds = new ArrayList<>(Arrays.asList(new AugPred(newCtx.predicate()))); } else if(ctx instanceof PerfQueryParser.PredParenContext) { /// TODO: Ideally, this could use something like a factory method. But using something like a /// copy constructor for now. PerfQueryParser.PredParenContext newCtx = (PerfQueryParser.PredParenContext)ctx; copy(new AugPred(newCtx.predicate())); } else { assert(false); // Logic error. Expecting a different kind of predicate? } } /// Constructors to get AugPreds from existing AugPreds, enabling trees of AugPreds. public <T> AugPred(AugPredType type, List<T> children) { if(type == AugPredType.PRED_AND || type == AugPredType.PRED_OR || type == AugPredType.PRED_NOT) { this.childPreds = new ArrayList<AugPred>(); for (T child: children) { this.childPreds.add((AugPred)child); } } else if(type == AugPredType.PRED_EQ || type == AugPredType.PRED_NE || type == AugPredType.PRED_GT || type == AugPredType.PRED_LT) { this.childExprs = new ArrayList<AugExpr>(); for (T child: children) { this.childExprs.add((AugExpr)child); } } else { assert(false); // Logic error. Not expecting other types here. } this.type = type; } /// Constructor to get AugPred from an identifier public AugPred(String preAssignedId) { this.type = AugPredType.PRED_ID; this.predId = preAssignedId; } /// Something like a copy constructor private void copy(AugPred copySrc) { this.type = copySrc.type; this.childPreds = copySrc.childPreds; this.childExprs = copySrc.childExprs; this.predId = copySrc.predId; } public AugPred(boolean isTrue) { this.type = isTrue ? AugPredType.PRED_TRUE : AugPredType.PRED_FALSE; } /// Structural checks to simplify predicate construction public boolean isIdenticallyTrue() { return this.type == AugPredType.PRED_TRUE; } public boolean isIdenticallyFalse() { return this.type == AugPredType.PRED_FALSE; } /// Predicate combinators on existing AugPreds, resulting in new AugPreds. public AugPred and(AugPred other) { if (this.isIdenticallyTrue()) { return other; } else if (other.isIdenticallyTrue()) { return this; } else if (this.isIdenticallyFalse() || other.isIdenticallyFalse()) { return new AugPred(false); } else { return new AugPred(AugPredType.PRED_AND, makePredChildren(this, other)); } } public AugPred or(AugPred other) { if (this.isIdenticallyFalse()) { return other; } else if (other.isIdenticallyFalse()) { return this; } else if (this.isIdenticallyTrue() || other.isIdenticallyTrue()) { return new AugPred(true); } else { return new AugPred(AugPredType.PRED_OR, makePredChildren(this, other)); } } public AugPred not() { if (this.isIdenticallyTrue()) { return new AugPred(false); } else if (this.isIdenticallyFalse()) { return new AugPred(true); } else { return new AugPred(AugPredType.PRED_NOT, new ArrayList<>(Arrays.asList(this))); } } /// Helper for constructing lists of child predicates from two inputs private List<AugPred> makePredChildren(AugPred childLeft, AugPred childRight) { List<AugPred> childList = new ArrayList<AugPred>(); childList.add(childLeft); childList.add(childRight); return childList; } /// Helper for constructing lists of child expressions from two inputs private List<AugExpr> makeExprChildren(AugExpr childLeft, AugExpr childRight) { List<AugExpr> childList = new ArrayList<AugExpr>(); childList.add(childLeft); childList.add(childRight); return childList; } /// Helper to extract expression for expression child i private String getExprStr(int i) { return childExprs.get(i).print(); } /// Helper to extract expression for predicate child i private String getPredStr(int i) { return childPreds.get(i).print(); } public HashSet<String> getUsedVars() { HashSet<String> usedVars; switch(type) { case PRED_TRUE: case PRED_FALSE: return new HashSet<>(); case PRED_ID: return new HashSet<>(Arrays.asList(predId)); case PRED_EQ: case PRED_NE: case PRED_GT: case PRED_LT: usedVars = childExprs.get(0).getUsedVars(); usedVars.addAll(childExprs.get(1).getUsedVars()); return usedVars; case PRED_AND: case PRED_OR: usedVars = childPreds.get(0).getUsedVars(); usedVars.addAll(childPreds.get(1).getUsedVars()); return usedVars; case PRED_NOT: return childPreds.get(0).getUsedVars(); default: assert(false); // Logic error. Expecting a new predicate type? return null; } } /// Printing for inspection on console public String print() { if(type == AugPredType.PRED_TRUE) { return "true"; } else if(type == AugPredType.PRED_FALSE) { return "false"; } else if(type == AugPredType.PRED_ID) { return predId; } else if(type == AugPredType.PRED_EQ) { return "(" + getExprStr(0) + ") == (" + getExprStr(1) + ")"; } else if(type == AugPredType.PRED_NE) { return "(" + getExprStr(0) + ") != (" + getExprStr(1) + ")"; } else if(type == AugPredType.PRED_GT) { return "(" + getExprStr(0) + ") > (" + getExprStr(1) + ")"; } else if(type == AugPredType.PRED_LT) { return "(" + getExprStr(0) + ") < (" + getExprStr(1) + ")"; } else if(type == AugPredType.PRED_AND) { return "(" + getPredStr(0) + ") && (" + getPredStr(1) + ")"; } else if(type == AugPredType.PRED_OR) { return "(" + getPredStr(0) + ") || (" + getPredStr(1) + ")"; } else if(type == AugPredType.PRED_NOT) { return "! (" + getPredStr(0) + ")"; } else { assert (false); // Logic error. Must be one of predetermined pred types return null; } } @Override public String toString() { return this.print(); } /// Helper to extract P4 output for expression child i private String getExprP4(int i, HashMap<String, AggFunVarType> symTab) { return childExprs.get(i).getP4(symTab); } private String getExprDomino(int i, HashMap<String, AggFunVarType> symTab) { return childExprs.get(i).getDomino(symTab); } /// Helper to extract P4 output from predicate child i private String getPredP4(int i, HashMap<String, AggFunVarType> symTab) { return childPreds.get(i).getP4(symTab); } private String getPredDomino(int i, HashMap<String, AggFunVarType> symTab) { return childPreds.get(i).getDomino(symTab); } /// Print P4 code public String getP4(HashMap<String, AggFunVarType> symTab) { if(type == AugPredType.PRED_TRUE) { return P4Printer.P4_TRUE; } else if(type == AugPredType.PRED_FALSE) { return P4Printer.P4_FALSE; } else if(type == AugPredType.PRED_ID) { if (! symTab.containsKey(predId)) { System.out.println("Missing symbol table entry for " + predId); } assert (symTab.containsKey(predId)); // ensure id exists in symbol table! return P4Printer.p4Ident(predId, symTab.get(predId)); } else if(type == AugPredType.PRED_EQ) { return "(" + getExprP4(0, symTab) + ") == (" + getExprP4(1, symTab) + ")"; } else if(type == AugPredType.PRED_NE) { return "(" + getExprP4(0, symTab) + ") != (" + getExprP4(1, symTab) + ")"; } else if(type == AugPredType.PRED_GT) { return "(" + getExprP4(0, symTab) + ") > (" + getExprP4(1, symTab) + ")"; } else if(type == AugPredType.PRED_LT) { return "(" + getExprP4(0, symTab) + ") < (" + getExprP4(1, symTab) + ")"; } else if(type == AugPredType.PRED_AND) { return "(" + getPredP4(0, symTab) + ") && (" + getPredP4(1, symTab) + ")"; } else if(type == AugPredType.PRED_OR) { return "(" + getPredP4(0, symTab) + ") || (" + getPredP4(1, symTab) + ")"; } else if(type == AugPredType.PRED_NOT) { return "! (" + getPredP4(0, symTab) + ")"; } else { assert (false); return null; } } /// Print domino code public String getDomino(HashMap<String, AggFunVarType> symTab) { if(type == AugPredType.PRED_TRUE) { return DominoPrinter.DOMINO_TRUE; } else if(type == AugPredType.PRED_FALSE) { return DominoPrinter.DOMINO_FALSE; } else if(type == AugPredType.PRED_ID) { if (! symTab.containsKey(predId)) { System.out.println("Missing symbol table entry for " + predId); } assert (symTab.containsKey(predId)); // ensure id exists in symbol table! return DominoPrinter.dominoIdent(predId, symTab.get(predId)); } else if(type == AugPredType.PRED_EQ) { return "(" + getExprDomino(0, symTab) + ") == (" + getExprDomino(1, symTab) + ")"; } else if(type == AugPredType.PRED_NE) { return "(" + getExprDomino(0, symTab) + ") != (" + getExprDomino(1, symTab) + ")"; } else if(type == AugPredType.PRED_GT) { return "(" + getExprDomino(0, symTab) + ") > (" + getExprDomino(1, symTab) + ")"; } else if(type == AugPredType.PRED_LT) { return "(" + getExprDomino(0, symTab) + ") < (" + getExprDomino(1, symTab) + ")"; } else if(type == AugPredType.PRED_AND) { return "(" + getPredDomino(0, symTab) + ") && (" + getPredDomino(1, symTab) + ")"; } else if(type == AugPredType.PRED_OR) { return "(" + getPredDomino(0, symTab) + ") || (" + getPredDomino(1, symTab) + ")"; } else if(type == AugPredType.PRED_NOT) { return "! (" + getPredDomino(0, symTab) + ")"; } else { assert (false); return null; } } /// Get all internally used expressions. public ArrayList<AugExpr> getUsedExprs() { ArrayList<AugExpr> exprs = new ArrayList<>(); if (type == AugPredType.PRED_TRUE || type == AugPredType.PRED_FALSE || type == AugPredType.PRED_ID) { return exprs; } else if (type == AugPredType.PRED_EQ || type == AugPredType.PRED_NE || type == AugPredType.PRED_GT || type == AugPredType.PRED_LT) { return new ArrayList<AugExpr>(this.childExprs); } else if (type == AugPredType.PRED_AND || type == AugPredType.PRED_OR) { exprs.addAll(this.childPreds.get(0).getUsedExprs()); exprs.addAll(this.childPreds.get(1).getUsedExprs()); return exprs; } else if (type == AugPredType.PRED_NOT) { return this.childPreds.get(0).getUsedExprs(); } else { assert (false); // Expecting one of the above predicate types. return null; } } }
package kr.or.ddit.project.controller; import java.net.URLEncoder; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import kr.or.ddit.member.service.IMemberService; import kr.or.ddit.profile_file.service.IProfileFileService; import kr.or.ddit.project.service.IProjectService; import kr.or.ddit.task.service.ITaskService; import kr.or.ddit.timeline.service.ITimelineService; import kr.or.ddit.vo.MemberVO; import kr.or.ddit.vo.ProfileFileVO; import kr.or.ddit.vo.ProjectVO; import kr.or.ddit.vo.Project_ProjectParticipantsVO; import kr.or.ddit.vo.newsboardVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.ibatis.sqlmap.engine.mapping.result.ResultMap; import com.lowagie.text.pdf.AcroFields.Item; @Controller @RequestMapping("/user/project/") public class ProjectController { @Autowired private IProjectService projectService; @Autowired private ITimelineService timelineService; @Autowired private ITaskService taskService; @Autowired private IMemberService memberService; @Autowired private IProfileFileService profileFileService; @RequestMapping("project") public ModelAndView project(ModelAndView modelAndView, String mem_id, HttpServletRequest request) throws Exception { // breadcrumb modelAndView.addObject("breadcrumb_title", "프로젝트"); modelAndView.addObject("breadcrumb_first", "프로젝트 관리"); modelAndView.addObject("breadcrumb_first_url", request.getContextPath() + "/user/project/project.do?mem_id=" + mem_id); modelAndView.addObject("breadcrumb_second", "프로젝트"); Map<String, String> params = new HashMap<String, String>(); params.put("mem_id", mem_id); List<Map<String, String>> notProjectList = projectService.selectNotProjectListById(params); for (Map<String, String> item : notProjectList) { String project_no = String.valueOf(item.get("PROJECT_NO")); Map<String, String> sendDataMap = new HashMap<String, String>(); sendDataMap.put("project_no", project_no); Map<String, String> resultDataMap = taskService.selectAverage(sendDataMap); if (item.get("PL") != null) { sendDataMap.put("mem_id", String.valueOf(item.get("PL"))); ProfileFileVO profileInfo = profileFileService.selectProfileFileInfo(sendDataMap); item.put("PL_PIC_SAVENAME", profileInfo.getProfile_savename()); } if (item.get("TA") != null) { sendDataMap.put("mem_id", String.valueOf(item.get("TA"))); ProfileFileVO profileInfo = profileFileService.selectProfileFileInfo(sendDataMap); item.put("TA_PIC_SAVENAME", profileInfo.getProfile_savename()); } if (item.get("DA") != null) { sendDataMap.put("mem_id", String.valueOf(item.get("DA"))); ProfileFileVO profileInfo = profileFileService.selectProfileFileInfo(sendDataMap); item.put("DA_PIC_SAVENAME", profileInfo.getProfile_savename()); } if (item.get("UA") != null) { sendDataMap.put("mem_id", String.valueOf(item.get("UA"))); ProfileFileVO profileInfo = profileFileService.selectProfileFileInfo(sendDataMap); item.put("UA_PIC_SAVENAME", profileInfo.getProfile_savename()); } if (item.get("AA") != null) { sendDataMap.put("mem_id", String.valueOf(item.get("AA"))); ProfileFileVO profileInfo = profileFileService.selectProfileFileInfo(sendDataMap); item.put("AA_PIC_SAVENAME", profileInfo.getProfile_savename()); } try { String average = String.valueOf(resultDataMap.get("AVERAGE")); item.put("AVERAGE", average); } catch (Exception e) { item.put("AVERAGE", "0"); } } List<Map<String, String>> finishProjectList = projectService.selectFinishProjectListById(params); for (Map<String, String> item : finishProjectList) { String project_no = String.valueOf(item.get("PROJECT_NO")); Map<String, String> sendDataMap = new HashMap<String, String>(); sendDataMap.put("project_no", project_no); Map<String, String> resultDataMap = taskService.selectAverage(sendDataMap); if (item.get("PL") != null) { sendDataMap.put("mem_id", String.valueOf(item.get("PL"))); ProfileFileVO profileInfo = profileFileService.selectProfileFileInfo(sendDataMap); item.put("PL_PIC_SAVENAME", profileInfo.getProfile_savename()); } if (item.get("TA") != null) { sendDataMap.put("mem_id", String.valueOf(item.get("TA"))); ProfileFileVO profileInfo = profileFileService.selectProfileFileInfo(sendDataMap); item.put("TA_PIC_SAVENAME", profileInfo.getProfile_savename()); } if (item.get("DA") != null) { sendDataMap.put("mem_id", String.valueOf(item.get("DA"))); ProfileFileVO profileInfo = profileFileService.selectProfileFileInfo(sendDataMap); item.put("DA_PIC_SAVENAME", profileInfo.getProfile_savename()); } if (item.get("UA") != null) { sendDataMap.put("mem_id", String.valueOf(item.get("UA"))); ProfileFileVO profileInfo = profileFileService.selectProfileFileInfo(sendDataMap); item.put("UA_PIC_SAVENAME", profileInfo.getProfile_savename()); } if (item.get("AA") != null) { sendDataMap.put("mem_id", String.valueOf(item.get("AA"))); ProfileFileVO profileInfo = profileFileService.selectProfileFileInfo(sendDataMap); item.put("AA_PIC_SAVENAME", profileInfo.getProfile_savename()); } try { String average = String.valueOf(resultDataMap.get("AVERAGE")); item.put("AVERAGE", average); } catch (Exception e) { item.put("AVERAGE", "0"); } } modelAndView.addObject("notProjectList", notProjectList); modelAndView.addObject("finishProjectList", finishProjectList); modelAndView.setViewName("user/project/project"); return modelAndView; } @RequestMapping("project_timeline") public ModelAndView project_timeline(ModelAndView modelAndView, String mem_id, HttpServletRequest request) throws Exception { // breadcrumb modelAndView.addObject("breadcrumb_title", "프로젝트"); modelAndView.addObject("breadcrumb_first", "프로젝트 관리"); modelAndView.addObject("breadcrumb_first_url", request.getContextPath() + "/user/project/project_timeline.do?mem_id=" + mem_id); modelAndView.addObject("breadcrumb_second", "작업 내역"); Map<String, String> params = new HashMap<String, String>(); params.put("mem_id", mem_id); List<Map<String, String>> projectList = projectService.selectProjectList(params); modelAndView.addObject("projectList", projectList); modelAndView.setViewName("user/project/project_timeline"); return modelAndView; } @RequestMapping("selectTodo") public ModelAndView selectTodo(String project_no, String mem_id) throws Exception { Map<String, String> params = new HashMap<String, String>(); params.put("project_no", project_no); params.put("mem_id", mem_id); List<Map<String, String>> todoList = projectService.selectTodo(params); ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("todoList", todoList); modelAndView.setViewName("jsonConvertView"); return modelAndView; } @RequestMapping("insertTodo") public ModelAndView insertTodo(String project_no, String mem_id, String todo_title, String todo_category) throws Exception { Map<String, String> params = new HashMap<String, String>(); params.put("project_no", project_no); params.put("mem_id", mem_id); params.put("todo_title", todo_title); params.put("todo_category", todo_category); String chk = projectService.insertTODO(params); ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("result", chk); modelAndView.setViewName("jsonConvertView"); return modelAndView; } @RequestMapping("deleteTodo") public ModelAndView deleteTodo(String todo_seq) throws Exception { Map<String, String> params = new HashMap<String, String>(); params.put("todo_seq", todo_seq); int chk = projectService.deleteTodo(params); ModelAndView modelAndView = new ModelAndView(); if (chk > 0) { modelAndView.addObject("result", "Y"); } else { modelAndView.addObject("result", "N"); } modelAndView.setViewName("jsonConvertView"); return modelAndView; } @RequestMapping("selectTimeline") public ModelAndView selectTimeline(String mem_id, String project_no) throws Exception { Map<String, String> params = new HashMap<String, String>(); params.put("mem_id", mem_id); params.put("project_no", project_no); List<Map<String, String>> timelineList = timelineService.selectTimelineList(params); ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("timelineList", timelineList); modelAndView.setViewName("jsonConvertView"); return modelAndView; } @RequestMapping("projectView") public ModelAndView projectView(ModelAndView modelAndView, String mem_id, String project_no, HttpServletRequest request) throws Exception { // breadcrumb modelAndView.addObject("breadcrumb_title", "프로젝트"); modelAndView.addObject("breadcrumb_first", "프로젝트"); modelAndView.addObject("breadcrumb_first_url", request.getContextPath() + "/user/project/project.do?mem_id=" + mem_id); modelAndView.addObject("breadcrumb_second", "프로젝트 상세"); Map<String, String> params = new HashMap<String, String>(); params.put("project_no", project_no); Map<String, String> projectInfo = projectService.selectProjectInfo(params); // 프로젝트 파트너스 이름 if (projectInfo.get("MEM_ID") != null) { params.put("mem_id", String.valueOf(projectInfo.get("MEM_ID"))); Map<String, String> memberInfo = memberService.selectMemberInfo(params); projectInfo.put("PARTNERS_NAME", String.valueOf(memberInfo.get("MEM_NAME"))); projectInfo.put("PARTNERS_ID", String.valueOf(memberInfo.get("MEM_ID"))); } // 프로젝트 PL 이름 if (projectInfo.get("PL") != null) { params.put("mem_id", String.valueOf(projectInfo.get("PL"))); ProfileFileVO profileInfo = profileFileService.selectProfileFileInfo(params); projectInfo.put("PL_PIC_SAVENAME", profileInfo.getProfile_savename()); Map<String, String> memberInfo = memberService.selectMemberInfo(params); Map<String, String> personAvg = taskService.selectPersonAverage(params); projectInfo.put("PL_NAME", String.valueOf(memberInfo.get("MEM_NAME"))); projectInfo.put("PL_ID", String.valueOf(memberInfo.get("MEM_ID"))); projectInfo.put("PL_WORKSTATUS", String.valueOf(memberInfo.get("MEM_WORKSTATUS"))); if (personAvg != null) { projectInfo.put("PL_AVG", String.valueOf(personAvg.get("AVERAGE"))); } } // 프로젝트 TA 이름 if (projectInfo.get("TA") != null) { params.put("mem_id", String.valueOf(projectInfo.get("TA"))); ProfileFileVO profileInfo = profileFileService.selectProfileFileInfo(params); projectInfo.put("TA_PIC_SAVENAME", profileInfo.getProfile_savename()); Map<String, String> memberInfo = memberService.selectMemberInfo(params); Map<String, String> personAvg = taskService.selectPersonAverage(params); projectInfo.put("TA_NAME", String.valueOf(memberInfo.get("MEM_NAME"))); projectInfo.put("TA_WORKSTATUS", String.valueOf(memberInfo.get("MEM_WORKSTATUS"))); if (personAvg != null) { projectInfo.put("TA_AVG", String.valueOf(personAvg.get("AVERAGE"))); } } // 프로젝트 DA 이름 if (projectInfo.get("DA") != null) { params.put("mem_id", String.valueOf(projectInfo.get("DA"))); ProfileFileVO profileInfo = profileFileService.selectProfileFileInfo(params); projectInfo.put("DA_PIC_SAVENAME", profileInfo.getProfile_savename()); Map<String, String> memberInfo = memberService.selectMemberInfo(params); Map<String, String> personAvg = taskService.selectPersonAverage(params); projectInfo.put("DA_NAME", String.valueOf(memberInfo.get("MEM_NAME"))); projectInfo.put("DA_WORKSTATUS", String.valueOf(memberInfo.get("MEM_WORKSTATUS"))); if (personAvg != null) { projectInfo.put("DA_AVG", String.valueOf(personAvg.get("AVERAGE"))); } } // 프로젝트 UA 이름 if (projectInfo.get("UA") != null) { params.put("mem_id", String.valueOf(projectInfo.get("UA"))); ProfileFileVO profileInfo = profileFileService.selectProfileFileInfo(params); projectInfo.put("UA_PIC_SAVENAME", profileInfo.getProfile_savename()); Map<String, String> memberInfo = memberService.selectMemberInfo(params); Map<String, String> personAvg = taskService.selectPersonAverage(params); projectInfo.put("UA_NAME", String.valueOf(memberInfo.get("MEM_NAME"))); projectInfo.put("UA_WORKSTATUS", String.valueOf(memberInfo.get("MEM_WORKSTATUS"))); if (personAvg != null) { projectInfo.put("UA_AVG", String.valueOf(personAvg.get("AVERAGE"))); } } // 프로젝트 AA 이름 if (projectInfo.get("AA") != null) { params.put("mem_id", String.valueOf(projectInfo.get("AA"))); ProfileFileVO profileInfo = profileFileService.selectProfileFileInfo(params); projectInfo.put("AA_PIC_SAVENAME", profileInfo.getProfile_savename()); Map<String, String> memberInfo = memberService.selectMemberInfo(params); Map<String, String> personAvg = taskService.selectPersonAverage(params); projectInfo.put("AA_NAME", String.valueOf(memberInfo.get("MEM_NAME"))); projectInfo.put("AA_WORKSTATUS", String.valueOf(memberInfo.get("MEM_WORKSTATUS"))); if (personAvg != null) { projectInfo.put("AA_AVG", String.valueOf(personAvg.get("AVERAGE"))); } } // breadcrumb modelAndView.addObject("breadcrumb_title", "프로젝트"); modelAndView.addObject("breadcrumb_first", "프로젝트"); modelAndView.addObject("breadcrumb_first_url", request.getContextPath() + "/user/project/project.do?mem_id=" + mem_id); modelAndView.addObject("breadcrumb_second", "프로젝트 상세 보기"); modelAndView.addObject("projectInfo", projectInfo); modelAndView.setViewName("user/project/project_view"); return modelAndView; } @RequestMapping("selectProjectPartnersInfoJSON") @ResponseBody public Map<String, String> selectProjectPartnersInfoJSON(String project_no) throws Exception { Map<String, String> params = new HashMap<String, String>(); params.put("project_no", project_no); Map<String, String> projectInfo = projectService.selectProjectInfo(params); params.put("mem_id", String.valueOf(projectInfo.get("MEM_ID"))); return memberService.selectMemberInfo(params); } @RequestMapping("projectEnd") public String projectEnd(String mem_id, String project_no) throws Exception { Map<String, String> params = new HashMap<String, String>(); params.put("project_no", project_no); int chk = projectService.projectEnd(params); return "redirect:/user/project/project.do?mem_id=" + mem_id; } @RequestMapping("endHire") public String endHire(String mem_id, String project_no) throws Exception { Map<String, String> params = new HashMap<String, String>(); params.put("project_no", project_no); int chk = projectService.endHire(params); return "redirect:/user/project/project.do?mem_id=" + mem_id; } }
/* package com.stk123.task.schedule; import com.stk123.common.CommonConstant; import com.stk123.common.db.util.DBUtil; import com.stk123.common.util.EmailUtils; import com.stk123.common.util.HtmlUtils; import com.stk123.common.util.JdbcUtils; import com.stk123.entity.StkDictionaryEntity; import com.stk123.entity.StkNewsEntity; import com.stk123.model.Index; import com.stk123.model.Industry; import com.stk123.model.News; import com.stk123.model.bo.*; import com.stk123.model.bo.cust.StkFnDataCust; import com.stk123.model.core.Stock; import com.stk123.model.enumeration.EnumCate; import com.stk123.model.enumeration.EnumMarket; import com.stk123.model.projection.StockBasicProjection; import com.stk123.repository.StkNewsRepository; import com.stk123.repository.StkRepository; import com.stk123.service.core.DictService; import com.stk123.service.core.StockService; import com.stk123.util.HttpUtils; import com.stk123.util.ServiceUtils; import lombok.extern.apachecommons.CommonsLog; import org.apache.commons.lang.StringUtils; import org.htmlparser.Node; import org.htmlparser.tags.Span; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.io.PrintWriter; import java.io.StringWriter; import java.sql.Connection; import java.sql.Timestamp; import java.util.*; @Component @CommonsLog public class NewsTask extends AbstractTask { private static int InitialDate = -7; @Autowired private StkRepository stkRepository; @Autowired private StockService stockService; @Autowired private DictService dictService; @Autowired private StkNewsRepository stkNewsRepository; @Override public void register() { super.runByName("runCN", this::runCN); super.runByName("runHK", this::runHK); } public static void main(String[] args) throws Exception { NewsTask newsRobot = new NewsTask(); newsRobot.run(); } public static void runHK() throws Exception { Date date = ServiceUtils.addDay(new Date(), -7); Connection conn = null; try { conn = DBUtil.getConnection(); List<Stk> stks = JdbcUtils.list(conn, "select code,name from stk_hk order by code", Stk.class); //List<Stk> stks = JdbcUtils.list(conn, "select code,name from stk_hk where code='00853' order by code", Stk.class); for(Stk stk : stks){ log.info(stk.getCode()); Index index = new Index(conn,stk.getCode(),stk.getName()); List<Map> news = parseNewsFromSinaHK(index, date); insert(conn, index, news); } } finally { if (conn != null) conn.close(); } } public void runCN() { Date date = ServiceUtils.addDay(new Date(), -7); List<StockBasicProjection> list = stkRepository.findAllByMarketAndCateOrderByCode(EnumMarket.CN, EnumCate.STOCK); List<Stock> stocks = stockService.buildStocksWithProjection(list); try { for(Stock stk : stocks){ log.info(stk.getCode()); List<Map> news = parseNewsFromSina(stk, date); insert(stk, news); } }catch (Exception e){ e.printStackTrace(); } } public void insert(Stock stock, List<Map> news) throws Exception { Collection<StkDictionaryEntity> types = dictService.getDictionary(2000); Collections.reverse(news); for(Map map : news){ String title = (String)map.get("title"); for(StkDictionaryEntity type : types){ boolean match = false; String[] patterns = type.getParam().split(CommonConstant.MARK_SEMICOLON); for(String pattern : patterns){ if(ServiceUtils.getMatchString(title, pattern) != null){ if(type.getParam2() != null && ServiceUtils.getMatchString(title, type.getParam2().split(CommonConstant.MARK_SEMICOLON)) != null){ continue; } match = true; break; } } if(match){ List<StkNewsEntity> infos = stkNewsRepository.findAllByCodeAndTypeAndInfoCreateTimeBetweenOrderByInsertTimeDesc(stock.getCode(), Integer.parseInt(type.getKey()), ServiceUtils.addDay(((Date)map.get("date")),-2), ServiceUtils.addDay(((Date)map.get("date")),-1)); if(infos.size() == 0){ StkNewsEntity stkNewsEntity = new StkNewsEntity(); stkNewsEntity.setCode(stock.getCode()); stkNewsEntity.setType(Integer.valueOf(type.getKey())); stkNewsEntity.setTitle((String)map.get("title")); stkNewsEntity.setUrlSource((String)map.get("url")); stkNewsEntity.setUrlTarget((String)map.get("target")); stkNewsEntity.setInsertTime(new Date()); stkNewsEntity.setInfoCreateTime(new Timestamp(((Date)map.get("date")).getTime())); stkNewsRepository.save(stkNewsEntity); //对合同、订单处理 if("200".equals(type.getKey())){ boolean flag = checkContactSumGreaterThanMainIncome(stock, title, (Date)map.get("date")); */ /* TODO Industry ind = stock.getIndustryDefault(); if(ind != null){ if(ind.getType().getName().contains("房地产")){ flag = false; } }*//* if(flag){ params.clear(); params.add(stock.getCode()); params.add(News.TYPE_1); double percent = ServiceUtils.numberFormat(stock.changePercent * 100, 2); params.add("["+type.getText()+"] 半年来总额是主营收入(TTM)的 "+ percent +"%"); JdbcUtils.insert(conn, "insert into stk_import_info(id,code,type,insert_time,info) values (s_import_info_id.nextval,?,?,sysdate,?)", params); if(percent >= 300){ //EmailUtils.send("【订单总额】半年来订单总额是主营收入3倍以上: "+ index.getName() + " - "+ percent +"%","经典案例:东方园林(SZ:002310)<br><br>"+ StkUtils.wrapCodeAndNameAsHtml(index)+ " - "+ percent +"%"); } } } //对定增、非公处理 if("150".equals(type.getKey())){ boolean flag = checkContactGreaterThanTotalMarketValue(stock, title, 0.1); if(flag){ params.clear(); params.add(stock.getCode()); params.add(News.TYPE_4); params.add("["+type.getText()+"] 金额是总市值["+ServiceUtils.number2String(stock.getTotalMarketValue(),2)+"亿]的 "+ServiceUtils.numberFormat(stock.changePercent * 100, 2)+"%. - " + title); JdbcUtils.insert(conn, "insert into stk_import_info(id,code,type,insert_time,info) values (s_import_info_id.nextval,?,?,sysdate,?)", params); } } //非公开发行、员工持股,股权激励 监控 if("120".equals(type.getKey()) || "150".equals(type.getKey()) || "130".equals(type.getKey())){ //NoticeRobot.updateNotice(conn, index); } } break; } } } } public static boolean checkContactGreaterThanTotalMarketValue(Index index, String title, double percent) throws Exception{ String amount = ServiceUtils.getMatchString(title, ServiceUtils.PATTERN_1); if(amount != null){ double total = 0; if(amount.contains("万")){ total += Double.parseDouble(StringUtils.replace(amount, "万", "")) / 10000; } if(amount.contains("亿")){ total += Double.parseDouble(StringUtils.replace(amount, "亿", "")); } double mv = index.getTotalMarketValue(); if(mv > 0 && total >= mv * percent){ index.changePercent = total/mv; return true; } } return false; } public boolean checkContactSumGreaterThanMainIncome(Stock stock, String title, Date newsCreateDate) throws Exception{ String amount = ServiceUtils.getMatchString(title, ServiceUtils.PATTERN_1); if(amount != null){ List<StkNewsEntity> infos = stkNewsRepository.findAllByCodeAndTypeAndInfoCreateTimeBetweenOrderByInsertTimeDesc(stock.getCode(), 200, new Timestamp(ServiceUtils.addDay(newsCreateDate,-180).getTime()), newsCreateDate); double total = 0.0; for(StkNewsEntity info : infos){ String t = info.getTitle(); if(t.contains("同比") || t.contains("环比"))continue; amount = ServiceUtils.getMatchString(t, ServiceUtils.PATTERN_1); if(amount != null){ if(amount.contains("万")){ total += Double.parseDouble(StringUtils.replace(amount, "万", "")) / 10000; } if(amount.contains("亿")){ total += Double.parseDouble(StringUtils.replace(amount, "亿", "")); } } } */ /* TODO StkFnDataCust fnData = stock.getFnDataLastestByType(stock.FN_ZYSR); if(fnData != null){ Double d = fnData.getFnDataByTTM(); if(d != null){ double zysr = d.doubleValue(); if(zysr > 0 && total >= zysr * 0.4){ stock.changePercent = total/zysr; System.out.print("total="+total+",zysr="+zysr+","); return true; } } }*//* } return false; } //https://vip.stock.finance.sina.com.cn/corp/view/vCB_AllNewsStock.php?symbol=sh600600&Page=1 public static List<Map> parseNewsFromSina(Stock stock, Date dateBefore) throws Exception { int pageId = 1; List<Map> news = new ArrayList<Map>(); while(true){ //https://vip.stock.finance.sina.com.cn/corp/view/vCB_AllNewsStock.php?symbol=sh600600&Page=1 String url = "https://vip.stock.finance.sina.com.cn/corp/view/vCB_AllNewsStock.php?symbol="+stock.getCodeWithPlace().toLowerCase()+"&Page="+pageId; String page = HttpUtils.get(url,null,"GBK"); Node node = HtmlUtils.getNodeByAttribute(page,"","class","datelist"); boolean stop = false; if(node != null){ List<Node> as = HtmlUtils.getNodeListByTagName(node, "a"); for(Node a : as){ String href = HtmlUtils.getAttribute(a, "href"); String title = a.toPlainTextString(); Node dateNode = a.getPreviousSibling(); String date = ServiceUtils.getMatchString(dateNode.toPlainTextString(), ServiceUtils.PATTERN_YYYY_MM_DD); //System.out.println(href+","+title+","+date); Date d = ServiceUtils.sf_ymd.parse(date); if(d.before(dateBefore)){ stop = true; break; } if(stock.getName() == null){ continue; } if(!title.contains(stock.getName()) && !title.contains(StringUtils.replace(stock.getName(), " ", "")) && !title.contains(StringUtils.replace(stock.getName(), " ", "").replace("ST", "")) && !title.contains(StringUtils.replace(stock.getName(), " ", "").replace("*ST", "")) ){ continue; } Map map = new HashMap(); map.put("date", d); map.put("title", title); map.put("target", href); map.put("url", url); news.add(map); } }else{ break; } if(stop)break; pageId ++; } return news; } //http://stock.finance.sina.com.cn/hkstock/go.php/CompanyNews/page/1/code/01610/.phtml public static List<Map> parseNewsFromSinaHK(Index index, Date dateBefore) throws Exception { String loc = index.getLocationAsString().toLowerCase(); int pageId = 1; List<Map> news = new ArrayList<Map>(); while(true){ String url = "http://stock.finance.sina.com.cn/hkstock/go.php/CompanyNews/page/"+pageId+"/code/"+index.getCode()+"/.phtml"; String page = HttpUtils.get(url,null,"GBK"); Node node = HtmlUtils.getNodeByAttribute(page,"","id","js_ggzx"); boolean stop = false; if(node != null){ List<Node> lis = HtmlUtils.getNodeListByTagName(node, "li"); for(Node li : lis){ Node a = HtmlUtils.getNodeByTagName(li, "a"); if(a == null)continue; String href = HtmlUtils.getAttribute(a, "href"); String title = a.toPlainTextString(); Node dateNode = HtmlUtils.getNodeByTagName(li, "span"); String date = ServiceUtils.getMatchString(dateNode.toPlainTextString(), ServiceUtils.PATTERN_YYYY_MM_DD); //System.out.println(href+","+title+","+date); Date d = ServiceUtils.sf_ymd.parse(date); if(d.before(dateBefore)){ stop = true; break; } if(!title.contains(index.getName()) && !title.contains(StringUtils.replace(index.getName(), " ", "")) && !title.contains(StringUtils.replace(index.getName(), " ", "").replace("ST", "")) && !title.contains(StringUtils.replace(index.getName(), " ", "").replace("*ST", "")) ){ continue; } Map map = new HashMap(); map.put("date", d); map.put("title", title); map.put("target", href); map.put("url", url); news.add(map); } }else{ break; } if(stop)break; pageId ++; } return news; } public static List<Map> parseNews(Index index,Date DateBefore) throws Exception { String loc = index.getLocationAsString(); int pid = 1; List<Map> news = new ArrayList<Map>(); while(true){ //wind公司新闻 String url = "http://www.windin.com/Tools/NewsDetail.aspx?windcode="+index.getCode()+"."+loc+"&start=&end=&pid="+pid+"&ajax="; String page = HttpUtils.get(url,null,"GBK"); Node node = HtmlUtils.getNodeByAttribute(HtmlUtils.unescape(page),"","id","lblData"); boolean stop = false; if(node != null){ Span span = (Span)node; String data = StringUtils.substringBetween(span.getStringText(), ":[", "],"); if(data != null){ if(data.length() == 0){ stop = true; break; } String[] infos = data.split(",\\u007B"); for(String info:infos){ if(info == null || info.length() == 0){ continue; } String date = StringUtils.substringBetween(info, "\"newsdate\":\"", "\",\"caption"); Date d = ServiceUtils.sf_ymd.parse(date); if(d.before(DateBefore)){ stop = true; break; } String title = StringUtils.substringBetween(info, "\"caption\":\"", "\",\"source\""); if(!title.contains(index.getName()) && !title.contains(StringUtils.replace(index.getName(), " ", "")) && !title.contains(StringUtils.replace(index.getName(), " ", "").replace("ST", "")) && !title.contains(StringUtils.replace(index.getName(), " ", "").replace("*ST", "")) ){ continue; } String target = StringUtils.substringBetween(info, "\"target\":\"", "\""); //System.out.println("date="+date+",title="+title); Map map = new HashMap(); map.put("date", d); map.put("title", title); map.put("target", target); map.put("url", url); news.add(map); } } } if(stop)break; pid ++; } return news; } public static void remove() throws Exception { Connection conn = null; try { conn = DBUtil.getConnection(); List<Stk> stks = JdbcUtils.list(conn, "select code,name from stk_cn order by code", Stk.class); for(Stk stk : stks){ System.out.println(stk.getCode()); //Index index = new Index(conn,stk.getCode(),stk.getName()); List params = new ArrayList(); params.add(stk.getCode()); List<StkImportInfo> infos = JdbcUtils.list(conn, "select * from stk_import_info where type>100 and code=?", params, StkImportInfo.class); for(StkImportInfo info : infos){ StkImportInfoType type = News.getType(info.getType()); if(type.getNotMatchPattern() != null && ServiceUtils.getMatchString(info.getTitle(), type.getNotMatchPattern().split(",")) != null){ System.out.println(info.getTitle()); params.clear(); params.add(info.getId()); JdbcUtils.delete(conn, "delete from stk_import_info where id=?", params); } } //break; } } finally { if (conn != null) conn.close(); } } } */
package AsyncTasks; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import com.example.fuemi.eisbaer.Activitys.MainActivity; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.util.ArrayList; import Interfaces.AsyncResponse; import Items.Order; public class GetNewsFromInternetTask extends AsyncTask<String,Integer,String> { ArrayList<Order> orderOfMerrit = new ArrayList<>(); Context context; private AsyncResponse asyncResponse; int percentAfterLoadRanking = 10; public GetNewsFromInternetTask(Context context, AsyncResponse asyncResponse){ this.context = context.getApplicationContext(); this.asyncResponse = asyncResponse; } /* läuft im Hintergrund ab, startet durch .execute aufruf in der Activity */ @Override protected String doInBackground(String... strings) { //getInternetConnection if(checkingForInternetAccess()){ getOrderOfMeritFromInternet(); }else{ //fehlermeldung,kein internetzugriff System.out.println("Kein Internetzugriff"); publishProgress(5, 0); } return null; } /* wird durch pubishProgress aufgerufen übergibt Fortschritt über das Interface AsyncResponse an die Activity */ @Override protected void onProgressUpdate(Integer... values) { asyncResponse.onUpdateProgress(values[0], values[1]); } /* sendet einen Ping aufruf an eine netzadresse überprüft so, ob zugriff aufs internet hergestellt werden kann ist ausm internet xD */ // TCP/HTTP/DNS (depending on the port, 53=DNS, 80=HTTP, etc.) private boolean checkingForInternetAccess() { publishProgress(5,1); try { int timeoutMs = 1500; Socket sock = new Socket(); SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 53); sock.connect(sockaddr, timeoutMs); sock.close(); return true; } catch (IOException e) { return false; } } //greift auf die Dart1.de webseite zu //liest die HTML aus //bestimmt die Daten der Order of Merrit //Gibt diese als ArrayList<Order> zurück private void getOrderOfMeritFromInternet() { publishProgress(10,1); try { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("https://www.darts1.de/ranglisten/PDC-Order-of-Merit.php"); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); InputStream input = httpEntity.getContent(); StringBuffer buffer = new StringBuffer(); String newLine; BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input, "ISO-8859-1")); boolean getData = false; while((newLine = bufferedReader.readLine()) != null){ System.out.println(newLine); //Tabelle Startet if(newLine.contains("Stand")){ getData = true; } if(newLine.contains("ranglisten")){ getData = false; } //zwischenzeitlich war die Internetseite anders aufgebaut // der jetzt auskommentierte Teil hat für das zwischenzeitlich andere html funktioniert /*for(int i = 0; i <= 100;i++){ if(newLine.equals("<td>"+i+"</td>")){ //platz String position = newLine.replaceAll("<td>",""); position = position.replaceAll("</td>",""); //Name newLine = bufferedReader.readLine(); String name = newLine.replaceAll("<td>",""); name = name.replaceAll("</td>",""); //Pfund newLine = bufferedReader.readLine(); String pfund = newLine.replaceAll("<td>",""); pfund = pfund.replaceAll("</td>",""); pfund = pfund.replaceAll("&pound;", "£"); orderOfMerrit.add(new Order(position,name,pfund)); } }*/ if(getData & newLine.contains("<tr><td>")){ //split data# System.out.println("inHere"); System.out.println(newLine); String[] seperated = newLine.split("</td><td>"); //entfernen der tabellenzeichen //entfernen der leerzeichen for(int i = 0; i < seperated.length;i++){ seperated[i] = seperated[i].replaceAll("<tr>",""); seperated[i] = seperated[i].replaceAll("<td>",""); seperated[i] = seperated[i].replaceAll("</tr>",""); seperated[i] = seperated[i].replaceAll("</td>",""); // wenn Namensstring noch <img... enthält, wird der String bei < getrennt & alles vor < behalten if(seperated[i].contains("<")){ String[] cutEnd = seperated[i].split("<"); seperated[i] = cutEnd[0]; } seperated[i] = seperated[i].trim(); } //entfernen der leerzeichen orderOfMerrit.add(new Order(seperated)); buffer.append(seperated[0]); buffer.append(seperated[1]); buffer.append(seperated[2]); buffer.append("\n"); } } input.close(); } catch (IOException e) { e.printStackTrace(); publishProgress(10,0); } } /* wird ausgeführt, nachdem doInBackground abgeschlossen ist startet neue Activity, wenn die ArrayList orderOfMerrit mindestens 1 Element enthält finish funktioniert noch nicht! */ @Override protected void onPostExecute(String result) { // execution of result of Long time consuming operation if(orderOfMerrit.size() >= 1){ System.out.println("orderOf Merrit >= 1"); //loadProgessBarToHundred, before starting /*while(percentAfterLoadRanking != 100){ percentAfterLoadRanking++; try { // Sleep for 200 milliseconds. Thread.sleep(200); asyncResponse.onUpdateProgress(percentAfterLoadRanking,1); } catch (InterruptedException e) { e.printStackTrace(); } }*/ Intent i = new Intent(context, MainActivity.class); Bundle b = new Bundle(); b.putSerializable("OrderOfMerrit",orderOfMerrit); i.putExtra("OrderOfMerrit", b); context.startActivity(i); } //((Activity) context).finish(); } @Override protected void onPreExecute() { } }
/* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://jwsdp.dev.java.net/CDDLv1.0.html * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable, * add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your * own identifying information: Portions Copyright [yyyy] * [name of copyright owner] */ package com.sun.xml.bind.v2.schemagen; /** * TODO: JAX-WS dependes on this class - consider moving it somewhere more stable, Notify JAX-WS before modifying anything... * * Other miscellaneous utility methods. * * @author * Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) */ public final class Util { private Util() {} // no instanciation please /** * Escape any characters that would cause the single arg constructor * of java.net.URI to complain about illegal chars. * * @param s source string to be escaped */ public static String escapeURI(String s) { StringBuilder sb = new StringBuilder(); for( int i = 0; i < s.length(); i++ ) { char c = s.charAt(i); if(Character.isSpaceChar(c)) { sb.append("%20"); } else { sb.append(c); } } return sb.toString(); } /** * Calculate the parent URI path of the given URI path. * * @param uriPath the uriPath (as returned by java.net.URI#getPath() * @return the parent URI path of the given URI path */ public static String getParentUriPath(String uriPath) { int idx = uriPath.lastIndexOf('/'); if (uriPath.endsWith("/")) { uriPath = uriPath.substring(0,idx); // trim trailing slash idx = uriPath.lastIndexOf('/'); // move idx to parent context } return uriPath.substring(0, idx)+"/"; } /** * Calculate the normalized form of the given uriPath. * * For example: * /a/b/c/ -> /a/b/c/ * /a/b/c -> /a/b/ * /a/ -> /a/ * /a -> / * * @param uriPath path of a URI (as returned by java.net.URI#getPath() * @return the normalized uri path */ public static String normalizeUriPath(String uriPath) { if (uriPath.endsWith("/")) return uriPath; // the uri path should always have at least a leading slash, // so no need to make sure that ( idx == -1 ) int idx = uriPath.lastIndexOf('/'); return uriPath.substring(0, idx+1); } /** * determine if two Strings are equal ignoring case allowing null values * * @param s string 1 * @param t string 2 * @return true iff the given strings are equal ignoring case, false if they aren't * equal or either of them are null. */ public static boolean equalsIgnoreCase(String s, String t) { if (s == t) return true; if ((s != null) && (t != null)) { return s.equalsIgnoreCase(t); } return false; } /** * determine if two Strings are iqual allowing null values * * @param s string 1 * @param t string 2 * @return true iff the strings are equal, false if they aren't equal or either of * them are null. */ public static boolean equal(String s, String t) { if (s == t) return true; if ((s != null) && (t != null)) { return s.equals(t); } return false; } }
package com.github.tobby48.java.scene1; /** * <pre> * com.github.tobby48.java.scene1 * WhileForContinueBreak.java * * 설명 : 반복문 continue, break 테스트 * </pre> * * @since : 2017. 6. 28. * @author : tobby48 * @version : v1.0 */ public class WhileForContinueBreak { public static void main(String[] args) { int input = 0; while(true){ input++; if(input % 2 == 0) continue; if(input > 10) break; System.out.println(input); } input = 0; for(int index = 0; index < 10; index++){ input++; if(input % 2 == 0) continue; System.out.println(input); } } }
package assign6; //public class MyThread extends Thread { public class MyThread implements Runnable{ public static int count; String a; @Override public void run() { count++; System.out.println("Thread Created : "+count); System.out.println("Name is : "+a); } public MyThread(String a) { super(); this.a = a; } public MyThread() {} }
package tech.liujin.drawable.progress.text; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint.Style; import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffXfermode; import android.graphics.RadialGradient; import android.graphics.Rect; import android.graphics.Shader.TileMode; import android.support.annotation.NonNull; /** * @author Liujin 2019/5/17:11:55:36 */ public class HaloTextProgressDrawable extends TextCenterProgressDrawable { /** * 光晕 */ private RadialGradient mRadialGradient; /** * 挖空 */ private PorterDuffXfermode mXfermode = new PorterDuffXfermode( Mode.DST_OUT ); /** * 光晕半径 */ private int mRadius; /** * 光晕动画进度 */ private float mHaloProcess; /** * 动画速度 */ private float mRate = 0.02f; /** * 动画方向 */ private int mOri = 1; /** * 主颜色 */ private int mColor = Color.WHITE; /** * %80 alpha 主颜色 */ private int mCCColor = Color.parseColor( "#CCFFFFFF" ); /** * %40 alpha 主颜色 */ private int m66Color = Color.parseColor( "#66FFFFFF" ); public HaloTextProgressDrawable ( ) { mPaint.setStyle( Style.FILL ); mTextPaint.setColor( mColor ); } @Override public void setColor ( int color ) { mColor = ( 0xFFFFFF ) & color; mCCColor = mColor | 0xCC000000; m66Color = mColor | 0x66000000; mTextPaint.setColor( color ); } @Override protected void onBoundsChange ( Rect bounds ) { int width = bounds.width(); int height = bounds.height(); int size = Math.min( width, height ); mRadius = ( size >> 1 ) - 2; mRadialGradient = new RadialGradient( width >> 1, height >> 1, mRadius, new int[]{ Color.TRANSPARENT, mCCColor, m66Color, Color.TRANSPARENT }, new float[]{ 0, 0.8f, 0.9f, 1f }, TileMode.MIRROR ); super.onBoundsChange( bounds ); } @Override public void draw ( @NonNull Canvas canvas ) { Rect bounds = getBounds(); int width = bounds.width(); int height = bounds.height(); int i = canvas.saveLayer( bounds.left, bounds.top, bounds.right, bounds.bottom, mPaint, Canvas.ALL_SAVE_FLAG ); /* 绘制光晕 */ float haloRadius = mRadius * 0.8f + mRadius * 0.2f * mHaloProcess; mPaint.setShader( mRadialGradient ); canvas.drawCircle( width >> 1, height >> 1, haloRadius, mPaint ); mPaint.setShader( null ); /* 挖空中间 */ mPaint.setXfermode( mXfermode ); canvas.drawCircle( width >> 1, height >> 1, mRadius * 0.8f, mPaint ); mPaint.setXfermode( null ); /* 解决中间黑洞 */ canvas.restoreToCount( i ); /* 绘制文字 */ super.draw( canvas ); /* 改变光晕进度 */ if( mHaloProcess > 1f ) { mOri = -1; } else if( mHaloProcess < 0f ) { mOri = 1; } mHaloProcess += ( mRate * mOri ); /* 使光晕动画 */ invalidateSelf(); } @Override public void onProcessChange ( float progress ) { mProgress = progress; invalidateSelf(); } public void setRate ( float rate ) { mRate = rate; } }
package walnoot.dodgegame.ui; import walnoot.dodgegame.DodgeGame; import walnoot.dodgegame.states.State; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont.TextBounds; public class ReturnButton extends TextButton{ private static final String TEXT = "BACK"; private static final float SCALE = 3f; private TextBounds bounds; private final OrthographicCamera camera; private final State previousState; public ReturnButton(OrthographicCamera camera, State previousState, String text){ super(text, 0, 0, SCALE, Keys.BACKSPACE); this.camera = camera; this.previousState = previousState; DodgeGame.SCALE_FONT.setScale(DodgeGame.FONT_SCALE * SCALE); bounds = new TextBounds(DodgeGame.SCALE_FONT.getBounds(text)); } public ReturnButton(OrthographicCamera camera, State previousState){ this(camera, previousState, TEXT); } public void update(){ float x = ((camera.viewportWidth * camera.zoom) - bounds.width) * 0.5f; float y = (-(camera.viewportHeight * camera.zoom) + bounds.height) * 0.5f; setPos(x, y); super.update(); } public void doAction(){ DodgeGame.setState(previousState); } }
/** * */ package pl.edu.agh.cyberwej.web.beans.payment; import java.util.Set; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.FacesConverter; import pl.edu.agh.cyberwej.data.objects.User; /** * @author Pita */ @FacesConverter("pl.cyberwej.setConverter") public class CustomSetConverter implements Converter { @Override public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) { return null; } @Override public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) { @SuppressWarnings("unchecked") Set<User> set = (Set<User>) arg2; StringBuilder builder = new StringBuilder(); int nrOfUsers = set.size(); int i = 0; for (User user : set) { i += 1; builder.append(user.getLogin()); if (i < nrOfUsers) { builder.append(", "); } } return builder.toString(); } }
package apptsched.services; import apptsched.domain.Employee; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; public interface EmployeeService { Employee save(Employee object); Iterable<Employee> save(Iterable<Employee> objectIterable); Employee findOne(Integer id); Employee findByEmail(String email); boolean exists(Integer id); Iterable<Employee> findAll(); long count(); void delete(Integer id); void delete(Employee object); void delete(Iterable<Employee> objectIterable); void deleteAll(); Iterable<Employee> findAll(Sort var1); Page<Employee> findAll(Pageable var1); }
package com.xeland.project; import java.util.Collection; import org.apache.commons.lang3.builder.EqualsBuilder; import org.eclipse.jdt.annotation.Nullable; public final class ClassR { private ClassR() { } public static EqualsResult baseEquals(final @Nullable Object thiss, @Nullable final Object obj) { return null; } public static <T> T cast(final Object obj) { return null; } @Deprecated public static <T> T castNotNull(@Nullable final T obj) { return null; } private static <T extends Comparable<T>> EqualsResult compare(final T t1, final T t2) { return EqualsResult.ER2; } public static <T> boolean equals(final T thiss, final @Nullable Object other, final EqualsFiller<T> filler) { return false; } public static <T> void equalsCollections(final EqualsBuilder b, final Collection<T> c1, final Collection<T> c2) { } public static <T extends Comparable<T>> int fullCompare(final T left, final T right) { return 0; } public static boolean fullEquals(final @Nullable Object left, final @Nullable Object right) { return true; } public static <T extends Comparable<T>> EqualsResult fullEquals(final T left, final T right) { return null; } public static EqualsResult nullEquals(@Nullable final Object thiss, @Nullable final Object obj) { return EqualsResult.ER4; } public static interface EqualsFiller<T> { } public static enum EqualsResult { ER1(true, true, 0), ER2(true, false, 1), ER3(true, false, -1), ER4(false, false, 0); private EqualsResult(final boolean shouldReturn, final boolean returnValue, final int compareResult) { } public EqualsBuilder createBuilder() { return new EqualsBuilder(); } public boolean getReturnValue() { return false; } public boolean shouldReturn() { return true; } public int toCompareResult() { return 0; } public boolean toEquals() { throw new IllegalStateException(); } } }
package windows; import impl.org.controlsfx.autocompletion.AutoCompletionTextFieldBinding; import impl.org.controlsfx.autocompletion.SuggestionProvider; import javafx.beans.property.SimpleBooleanProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.*; import javafx.scene.control.cell.CheckBoxTableCell; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.KeyCode; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.text.TextAlignment; import javafx.stage.DirectoryChooser; import javafx.stage.Stage; import main.FileWatcher; import main.Main; import main.util.WatcherInfo; import org.controlsfx.control.textfield.TextFields; import java.io.File; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.prefs.Preferences; import java.util.regex.Pattern; public class TabWatcher { private TableView<WatcherInfo> tableView; private ObservableList<WatcherInfo> list; private List<String> autoFill = Collections.singletonList(""); private SuggestionProvider<String> provider; private String regex = "^*[^\\$]*$"; public AnchorPane getWindow(String namePage) { AnchorPane watcher = new AnchorPane(); watcher.getStylesheets().add(this.getClass().getResource("/css/tabs.css").toExternalForm()); VBox vBox = new VBox(); HBox hBox = new HBox(); Label label = new Label(namePage); hBox.setStyle("-fx-background-color: #dddddd;"); AnchorPane.setTopAnchor(vBox, 0.0); AnchorPane.setBottomAnchor(vBox, 0.0); AnchorPane.setLeftAnchor(vBox, 0.0); AnchorPane.setRightAnchor(vBox, 0.0); label.setStyle("-fx-text-fill: black; -fx-font-size: 24pt; -fx-font-weight: normal; -fx-padding: 5"); label.setTextAlignment(TextAlignment.CENTER); hBox.getChildren().addAll(label); Design.addStackPaneIconHelp(hBox, "\tНа данной странице вы можете выбрать папки для наблюдения. " + "Вы узнаете все, что просходит с файлами в папке(-ах). " + "Активный флажок перенаправит новые файлы сканеру."); HBox hb_1 = new HBox(5); HBox hb_controls = new HBox(5); TextField field_watcher; Button dir_button_choose; CheckBox cb1; /* UI */ { // StackPane sp = new StackPane(); // sp.setStyle("-fx-background-color: red;"); // BorderPane bp = setBorderPane("watcher_off.png", "Наблюдатель", "123 d z dw q1 l;\t da; wd\\a 12 9"); // Group group = new Group(); // group.getChildren().add(bp); // // sp.getChildren().add(group); //// StackPane.setAlignment(bp, Pos.CENTER); // vBox.getChildren().add(sp); } { hb_1.setPadding(new Insets(5, 5, 0, 5)); field_watcher = TextFields.createClearableTextField(); field_watcher.setPrefWidth(Integer.MAX_VALUE); provider = SuggestionProvider.create(autoFill); new AutoCompletionTextFieldBinding<>(field_watcher, provider).setMinWidth(650); // field_watcher.setText(Preferences.userNodeForPackage(Main.class).get("dir_watcherField", null)); hb_1.getChildren().add(field_watcher); // СЛУШАТЕЛЬ ТЕКСТФИЛДА!!! field_watcher.textProperty().addListener((observable, oldValue, newValue) -> { File f = new File(newValue); try { if (f.exists()) { File[] list = f.listFiles(); if (list != null) { autoFill = getString(list); provider.clearSuggestions(); provider.addPossibleSuggestions(autoFill); } } } catch (Exception ignore) { System.out.println(); } }); field_watcher.setOnKeyReleased(keyEvent -> { if (keyEvent.getCode() == KeyCode.ENTER) { addWatch(field_watcher.getText()); } }); dir_button_choose = new Button(". . ."); dir_button_choose.getStyleClass().add("button-my"); Stage stage_fileChooser = new Stage(); DirectoryChooser directoryChooser = new DirectoryChooser(); dir_button_choose.setOnAction(event -> { dir_button_choose.setDisable(true); File file = directoryChooser.showDialog(stage_fileChooser); if (file != null) { field_watcher.setText(file.getPath()); addWatch(file.getPath()); } dir_button_choose.setDisable(false); }); hb_1.getChildren().add(dir_button_choose); watcher.getChildren().add(hb_1); } { hb_controls.setPadding(new Insets(5)); cb1 = new CheckBox("Включить наблюдатель"); cb1.setSelected(Preferences.userNodeForPackage(Main.class).getBoolean("isWatcher", false)); cb1.selectedProperty().addListener((observable, oldValue, newValue) -> { Preferences.userNodeForPackage(Main.class).putBoolean("isWatcher", newValue); }); hb_controls.getChildren().add(new Label()); watcher.getChildren().add(hb_controls); } { tableView = new TableView<>(); tableView.setEditable(true); // list = FXCollections.observableArrayList(); list = FXCollections.synchronizedObservableList(FXCollections.observableArrayList()); TableColumn<WatcherInfo, String> filePath = new TableColumn<>("Папки под наблюдением"); TableColumn<WatcherInfo, Boolean> fileWatching = new TableColumn<>(""); // Defines how to fill data for each cell. filePath.setCellValueFactory(new PropertyValueFactory<>("path")); fileWatching.setCellValueFactory(new PropertyValueFactory<>("watching")); filePath.prefWidthProperty().bind(tableView.widthProperty().subtract(32)); //90% fileWatching.setMaxWidth(30); // fileWatching.prefWidthProperty(); //10% // tableView.setRowFactory(tv -> { // TableRow<WatcherInfo> row = new TableRow<>(); // row.setOnMouseClicked(event -> { // if (! row.isEmpty() && event.getButton()== MouseButton.PRIMARY && event.getClickCount() == 1) { // WatcherInfo clickedRow = row.getItem(); // System.out.println(""); // } // }); // return row ; // }); // ==== SINGLE? (CHECH BOX) === fileWatching.setCellValueFactory(param -> { WatcherInfo watcherInfo = param.getValue(); SimpleBooleanProperty booleanProp = new SimpleBooleanProperty(watcherInfo.isWatching()); // Note: singleCol.setOnEditCommit(): Not work for CheckBoxTableCell. // When "Single?" column change. booleanProp.addListener((observable, oldValue, newValue) -> { watcherInfo.setWatching(newValue); if (newValue) { System.out.println("resumed"); watcherInfo.getLink().resume(); } else { System.out.println("stopped"); watcherInfo.getLink().stop(); watcherInfo.getLink().stop(); } }); return booleanProp; }); // fileWatching.setCellFactory(p -> { CheckBoxTableCell<WatcherInfo, Boolean> cell = new CheckBoxTableCell<>(); cell.setAlignment(Pos.CENTER); return cell; }); tableView.setPlaceholder(new Label("Наблюдаемых объектов нет")); // tableView.setStyle("-fx-selection-bar: red; -fx-selection-bar-non-focused: salmon;"); tableView.getStyleClass().add("table-view"); //noinspection unchecked tableView.getColumns().addAll(filePath, fileWatching); tableView.setItems(list); tableView.setPrefHeight(490); } { //log } vBox.getChildren().addAll(hBox, hb_1, hb_controls, new Separator(), tableView); watcher.getChildren().addAll(vBox); return watcher; } private List<String> getString(File[] files) { List<String> file = new ArrayList<>(); for (File f : files) { if (f.isDirectory() && Pattern.matches(regex, f.getName())) { file.add(f.getPath()); } } return file; } private void addWatch(String path) { File file = new File(path); if (file.exists() && file.isDirectory()) { for (int i = 0; i < list.size(); i++) { if (file.getPath().contains(list.get(i).getPath())) return; else if (list.get(i).getPath().contains(file.getPath())) { list.get(i).getLink().stop(); list.get(i).getLink().stopWatcher(); list.remove(i); // try { // Thread.sleep( 10); // } catch (InterruptedException ignored) { } // Platform.runLater(() -> { // tableView.refresh(); // }); i--; } } doing(file); } } private void doing(File file) { try { FileWatcher fileWatcher = new FileWatcher(Paths.get(file.getPath())); fileWatcher.addObserver(Main.scanEngine.getPrinter()); fileWatcher.watchOffers(); // Main.scanEngine.addWatcher(fileWatcher); //Добавим таблицу WatcherInfo temp = new WatcherInfo(file.getPath(), true); temp.Link(fileWatcher); list.add(temp); tableView.refresh(); } catch (Exception ignored) { } } //Scanning private BorderPane setBorderPane(String iconPath, String title, String Desc) { BorderPane bp = new BorderPane(); // { // //Иконка // ImageView imageView = new ImageView(new Image(iconPath)); // imageView.setFitWidth(144); // imageView.setFitHeight(100); // bp.setTop(imageView); // } // { // StackPane setAl = new StackPane(); // Label category = new Label(title); // setAl.getChildren().addAll(category); // bp.setBottom(setAl); // } // bp.setPadding(new Insets(0,0,0,0)); return bp; } }
package de.uniwue.jpp.deckgen; import java.awt.event.ActionEvent; import de.uniwue.jpp.deckgen.repository.CardRepository; import de.uniwue.jpp.deckgen.service.csp.*; import de.uniwue.jpp.deckgen.service.csp.constraints.*; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JList; public class AddConstraintAction extends AbstractAction{ private static final long serialVersionUID = 1L; private Dominion dominion; private CardRepository cardRepo; private JList<String> jlist; public AddConstraintAction(Dominion dominion, CardRepository cardRepo, JList<String> jlist){ super(); this.dominion=dominion; this.cardRepo=cardRepo; this.jlist = jlist; } public void actionPerformed(ActionEvent e) { String stringText = ((JButton)e.getSource()).getText(); String selection = jlist.getSelectedValue(); IConstraint tempConstraint=null; if(selection!=null){ if(stringText.contains("Card")){ tempConstraint = new ExcludeCardConstraint(cardRepo.find(selection)); } else{ tempConstraint = new ExcludeExtensionConstraint(selection); } dominion.addConstraint(tempConstraint); } } }
package com.marijannovak.littletanks; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class OnlineScoreFragment extends Fragment { private ListView lvOnline; private ArrayList<ScoreItem> onlineScoreList; private ScoreAdapter onlineScAdapter; private FirebaseDatabase fbDatabase; private DatabaseReference dbRef; private FirebaseAuth mAuth; private ProgressBar spinnerProgress; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.online_tab,container,false); fbDatabase = FirebaseDatabase.getInstance(); dbRef = fbDatabase.getReference(""); mAuth = FirebaseAuth.getInstance(); if(mAuth.getCurrentUser() == null) Toast.makeText(getActivity(), "Log in to see online scores!", Toast.LENGTH_SHORT).show(); this.lvOnline = (ListView) view.findViewById(R.id.lvOnlineScores); this.spinnerProgress = (ProgressBar) view.findViewById(R.id.spinProgress); onlineScoreList = new ArrayList<>(); dbRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot data : dataSnapshot.getChildren()) { ScoreItem score = new ScoreItem(); score.setPlayerName(data.child("username").getValue(String.class)); score.setScore(data.child("score").getValue(Integer.class)); score.setKilled(data.child("killed").getValue(Integer.class)); score.setPlayTime(data.child("time").getValue(Integer.class)); onlineScoreList.add(score); } Collections.sort(onlineScoreList, new Comparator<ScoreItem>() { @Override public int compare(ScoreItem item1, ScoreItem item2) { return item2.getScore() - item1.getScore(); } }); onlineScAdapter = new ScoreAdapter(onlineScoreList); lvOnline.setAdapter(onlineScAdapter); spinnerProgress.setVisibility(View.GONE); } @Override public void onCancelled(DatabaseError databaseError) { spinnerProgress.setVisibility(View.GONE); } }); return view; } }
package forca; import org.junit.Test; import static org.junit.Assert.*; public class JogoTest { @Test public void deveConterUmaLetra() { Jogo jogo = new Jogo(); char letra = 'a'; assertTrue(jogo.contem(letra)); } @Test public void naoPodeConterUmaLetra() { Jogo jogo = new Jogo(); char letra = 'x'; assertFalse(jogo.contem(letra)); } @Test public void naoDeveTerNenhumaLetraReveladaNoInicioDoJogo() { Jogo jogo = new Jogo(); assertEquals("_ _ _ _ _ _", jogo.estadoAtual()); } @Test public void deveRevelarUmaLetraExistente() { Jogo jogo = new Jogo(); jogo.contem('a'); assertEquals("a _ _ _ _ _", jogo.estadoAtual()); } @Test public void deveRevelarUmaOutraLetraExistente() { Jogo jogo = new Jogo(); jogo.contem('e'); assertEquals("_ _ e _ _ e", jogo.estadoAtual()); } @Test public void deveRevelarDuasLetrasDiferentesExistentes() { Jogo jogo = new Jogo(); jogo.contem('a'); jogo.contem('e'); assertEquals("a _ e _ _ e", jogo.estadoAtual()); } }
package com.ifeng.recom.mixrecall.common.service; import com.google.common.collect.Lists; import com.google.gson.Gson; import com.ifeng.recom.mixrecall.common.constant.DocType; import com.ifeng.recom.mixrecall.common.constant.FlowTypeAsync; import com.ifeng.recom.mixrecall.common.model.item.Index4User; import com.ifeng.recom.mixrecall.common.model.item.LastDocBean; import com.ifeng.recom.mixrecall.common.model.request.MixRequestInfo; import com.ifeng.recom.mixrecall.common.util.GsonUtil; import com.ifeng.recom.mixrecall.common.util.StringZipUtil; import com.ifeng.recom.mixrecall.common.util.http.HttpClientUtil; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.ifeng.recom.mixrecall.common.factory.JsonTypeFactory.MapStringListIndex4User; import static com.ifeng.recom.mixrecall.common.util.http.HttpClientUtil.transMapToPairs; /** * ctr服务api,可以分别 调用线上 * Created by jibin on 2017/6/28. */ public class PositivefeedClient { protected static Logger logger = LoggerFactory.getLogger(PositivefeedClient.class); private static final String positivefeedUrl = "http://local.recom.ifeng.com/positivefeed/list?uid="; /** * 查询正反馈服务 * * @param mixRequestInfo * @param timeout * @return 获取正反馈结果,结果为一个map,key为simId */ public static Map<String, List<Index4User>> getPositivefeedResult(MixRequestInfo mixRequestInfo, List<LastDocBean> lastDocBeanList, DocType docType, int timeout) { String uid = mixRequestInfo.getUid(); Map<String, List<Index4User>> indexResult = null; try { MixRequestInfo tmp = new MixRequestInfo(); tmp.setUid(mixRequestInfo.getUid()); tmp.setDebugUser(mixRequestInfo.isDebugUser()); tmp.setAbTestMap(mixRequestInfo.getAbTestMap()); tmp.setUserTypeMap(mixRequestInfo.getUserTypeMap()); tmp.setRecomChannel(mixRequestInfo.getRecomChannel()); tmp.setProid(mixRequestInfo.getProid()); tmp.setLastDocBeans(lastDocBeanList); String flowType = FlowTypeAsync.positiveFeedNew; if (DocType.VIDEO.equals(docType)) { flowType = FlowTypeAsync.positiveFeedVideoNew; } tmp.setFlowType(flowType); Map<String, String> postParam = new HashMap<>(); postParam.put("requestInfo", new Gson().toJson(tmp)); String url = positivefeedUrl + uid; String result = HttpClientUtil.httpPost(url, transMapToPairs(postParam), timeout); if (StringUtils.isNotBlank(result)) { result = StringZipUtil.decompress(result); indexResult = GsonUtil.json2Object(result, MapStringListIndex4User); } } catch (Exception e) { logger.error("{} getPositivefeed ERROR:{}", mixRequestInfo.getUid(), e); } return indexResult; } public static void main(String[] args) { // String uid = "geyalu"; String uid = "867392030450848"; MixRequestInfo mixRequestInfo = new MixRequestInfo(); Map<String, Boolean> userTypeMap = new HashMap<>(); mixRequestInfo.setUserTypeMap(userTypeMap); mixRequestInfo.setUid(uid); //last doc List<LastDocBean> lastDocBeanList = Lists.newArrayList(); LastDocBean lastDocBean1 = new LastDocBean("66559695", "clusterId_50244589",""); LastDocBean lastDocBean2 = new LastDocBean("44732264", "clusterId_26802883",""); lastDocBeanList.add(lastDocBean1); lastDocBeanList.add(lastDocBean2); mixRequestInfo.setLastDocBeans(lastDocBeanList); //user info //userTypeMap.put("isWhiteLv2NotWxbNotBSG", true); userTypeMap.put("isWxb", false); userTypeMap.put("isLvsWhite", true); userTypeMap.put("isBeiJingUserNotWxb", true); mixRequestInfo.setDebugUser(true); // mixRequestInfo.setFlowType(FlowTypeAsync.positiveFeedNew); mixRequestInfo.setFlowType(FlowTypeAsync.IncreasedateMerge); for (int i = 0; i < 10; i++) { Map<String, List<Index4User>> result = getPositivefeedResult(mixRequestInfo, lastDocBeanList, DocType.DOCPIC, 5000); System.out.println(new Gson().toJson(result)); } } }
public class MyFirstPojo { private String name; public static void main(String [] args) { for (String arg : args) { MyFirstPojo pojo = new MyFirstPojo(arg); // Here's how you create a POJO System.out.println(pojo); } } public MyFirstPojo(String name) { this.name = name; } public String getName() { return this.name; } public String toString() { return this.name; } }
// https://www.youtube.com/watch?v=zzqAE1J2ieA class Solution { public int smallestRangeI(int[] A, int K) { int minVal = A[0]; int maxVal = A[0]; for (int i = 0; i < A.length; i++) { minVal = Math.min(minVal, A[i]); maxVal = Math.max(maxVal, A[i]); } if (minVal + K >= maxVal - K) return 0; else return (maxVal - K) - (minVal + K); } }
package LimpBiscuit.Demo.Controller; import LimpBiscuit.Demo.Entity.User; import LimpBiscuit.Demo.Repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller @RequestMapping("/login") public class LoginController { @Autowired private UserRepository userRepository; @GetMapping("") public String get() { return "Login"; } @PostMapping("") public String post(@RequestParam("email") String email, @RequestParam("password") String password) { User user = userRepository.findByEmail(email); try { user.getEmail(); } catch (Exception e) { return "Login"; } BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); String hash = passwordEncoder.encode(password); System.out.println(hash); System.out.println(user.getHash()); if (passwordEncoder.matches(password, user.getHash())) { return "Home"; } return "Login"; } }
package com.progressive.Tests; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.Assert; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import com.progressive.Pages.homePages; public class mercuryLogin { WebDriver driver; @Parameters({"browser"}) @BeforeTest public void setupTest(String browswer) throws InterruptedException { if(browswer=="mozila") { System.setProperty("webdriver.chrome.driver", "C:\\Users\\Agile1Tech\\Desktop\\Selenium Testing libraries\\chromedriver.exe"); driver = new ChromeDriver(); } if(browswer=="chrome") { System.setProperty("webdriver.chrome.driver", "C:\\Users\\Agile1Tech\\Desktop\\Selenium Testing libraries\\chromedriver.exe"); driver = new ChromeDriver(); } Thread.sleep(2000); driver.manage().window().maximize(); driver.navigate().to("http://newtours.demoaut.com/"); driver.manage().deleteAllCookies(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); } @Parameters({"username","password","expecteddata"}) @Test public void loginTest(String usernamedata, String passworddata, String expecteddata) { WebElement username = driver.findElement(By.name("userName")); WebElement password = driver.findElement(By.name("password")); // hardcoding our data username.sendKeys(usernamedata); password.sendKeys(passworddata); String actualTitle = driver.getTitle(); Assert.assertEquals(actualTitle,expecteddata); } @AfterTest public void aftertest() throws InterruptedException { Thread.sleep(2000); driver.quit(); } }
package com.liferay.sales.demo.BulkLoadCategories.constants; /** * @author Ben */ public class BulkLoadCategoriesPortletKeys { public static final String BulkLoadCategories = "bulkloadcategories"; }
package initializer; public class Rate { private Currency currency; private double factor; public Rate(Currency currency, double factor) { this.currency = currency; this.factor = factor; } public Currency getCurrency() { return currency; } public double getFactor() { return factor; } }
package com.groupdy.midpoint; import java.util.Date; import com.parse.ParseClassName; import com.parse.ParseObject; import com.parse.ParseUser; /** * An extension of ParseObject that makes * accessing information about a given * Invitation more convenient * * @author jordan */ @ParseClassName("Invitation") public class Invitation extends ParseObject { public Invitation() { // A default constructor is required } public void createInvitation(ParseUser invitee, Date date, Meal meal) { put("inviter", ParseUser.getCurrentUser()); put("invitee", invitee); put("status", "pending"); put("activeUntil", date); // TODO: Remove "invitedTo" key from object put("invitedTo", meal); } public String status() { return get("status").toString(); } public void accept() { put("status", "accepted"); } public void decline() { put("status", "declined"); } }
package language.thread.problems.problem0003; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * https://segmentfault.com/a/1190000006671595 * 数组A内容为 1,2,3,4...52 ,数组B内容为26个英文字母,使用两个线程分别输入两个数组, * 打印内容为:12a34b56c78e....... 这样的规律 */ public class AnswerOne { // 这个实现也可以在while循环中用join实现: public static void main(String[] args) throws InterruptedException { StringBuffer stringBuffer = new StringBuffer(); int[] arrOne = new int[52]; for (int i=1;i<53;i++) { arrOne[i-1] = i; } String[] arrTwo = new String[26]; for (int i=0;i<26;i++) { arrTwo[i]= String.valueOf((char )('a'+i)); } Executor executor = Executors.newFixedThreadPool(2); // CyclicBarrier cyclicBarrier = new CyclicBarrier(2); CountDownLatch countDownLatch = new CountDownLatch(2); int cnt = 0; while (cnt < 26) { System.out.println(cnt); executor.execute(new numOperator(arrOne,countDownLatch,cnt,stringBuffer)); countDownLatch.await(); executor.execute(new strOperator(arrTwo, cnt, stringBuffer)); cnt++; countDownLatch = new CountDownLatch(2); } System.out.println(stringBuffer.toString()); ((ExecutorService) executor).shutdown(); } private static class numOperator implements Runnable { int[] arr; CountDownLatch countDownLatch; int cnt; StringBuffer stringBuffer; public numOperator(int[] arrOne, CountDownLatch countDownLatch, int cnt, StringBuffer stringBuffer) { this.arr = arrOne; this.countDownLatch = countDownLatch; this.cnt = cnt; this.stringBuffer = stringBuffer; } @Override public void run() { for (int i=cnt*2;i<cnt*2+2;i++) { stringBuffer.append(arr[i]); countDownLatch.countDown(); } } } private static class strOperator implements Runnable { String[] arr; int cnt; StringBuffer stringBuffer; public strOperator(String[] arrTwo, int cnt, StringBuffer stringBuffer) { this.arr = arrTwo; this.cnt = cnt; this.stringBuffer = stringBuffer; } @Override public void run() { stringBuffer.append(arr[cnt]); } } }
package student.pl.edu.pb.geodeticapp.geoutils; public class CS2000RefSystemPicker { private final static double FIRST_LT = 16.5; private final static double SECOND_LT = 19.5; private final static double THIRD_LT = 22.5; public static ReferenceSystemConverter.ReferenceSystem getReferenceSystem(double longitude) { if (longitude < FIRST_LT) { return ReferenceSystemConverter.ReferenceSystem.CS2000z5; } else if (longitude >= FIRST_LT && longitude < SECOND_LT) { return ReferenceSystemConverter.ReferenceSystem.CS2000z6; } else if (longitude >= SECOND_LT && longitude < THIRD_LT) { return ReferenceSystemConverter.ReferenceSystem.CS2000z7; } else { return ReferenceSystemConverter.ReferenceSystem.CS2000z8; } } }
package org.kevoree.registry.config; /** * Application constants. */ public final class Constants { //Regex for acceptable logins public static final String LOGIN_REGEX = "^[a-z0-9]*$"; public static final String TDEF_NAME_REGEX = "^[A-Z][\\w]*$"; public static final String DU_VERSION_REGEX = "^(?:[0-9]+)\\.(?:[0-9]+)\\.(?:[0-9]+)(?:-(?:[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?(?:\\+[0-9A-Za-z-]+)?$"; public static final String NS_NAME_REGEX = "^[a-z0-9]+$"; // Spring profiles for development, test and production, see http://jhipster.github.io/profiles/ public static final String SPRING_PROFILE_DEVELOPMENT = "dev"; public static final String SPRING_PROFILE_PRODUCTION = "prod"; public static final String SYSTEM_ACCOUNT = "system"; public static final String ANONYMOUS_USER = "anonymoususer"; private Constants() { } }
package com.qkj.manage.domain; import java.util.Date; public class MyProcess { private Integer uuid;// (int)主键自增 private Integer process_id;// (int)类型0无 1活动 2至事由 3:工时 private Integer biz_id;// (int)业务ID private String biz_user;// (varchar)业务时间 private Date biz_time;// (varchar)业务人 private String biz_note;// (text)业务备注 private Integer biz_status01;// (int)业务状态1 private Integer biz_status02;// (int)业务状态2 private Integer biz_status03;// (int)业务状态3 private Integer biz_status04;// (int)业务状态4 private Integer biz_status05;// (int)业务状态5 private String biz_sign;// (varchar)业务标记 // 以下为非数据库字段 private String uname; public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public Integer getUuid() { return uuid; } public void setUuid(Integer uuid) { this.uuid = uuid; } public Integer getProcess_id() { return process_id; } public void setProcess_id(Integer process_id) { this.process_id = process_id; } public Integer getBiz_id() { return biz_id; } public void setBiz_id(Integer biz_id) { this.biz_id = biz_id; } public String getBiz_user() { return biz_user; } public void setBiz_user(String biz_user) { this.biz_user = biz_user; } public Date getBiz_time() { return biz_time; } public void setBiz_time(Date biz_time) { this.biz_time = biz_time; } public String getBiz_note() { return biz_note; } public void setBiz_note(String biz_note) { this.biz_note = biz_note; } public Integer getBiz_status01() { return biz_status01; } public void setBiz_status01(Integer biz_status01) { this.biz_status01 = biz_status01; } public Integer getBiz_status02() { return biz_status02; } public void setBiz_status02(Integer biz_status02) { this.biz_status02 = biz_status02; } public Integer getBiz_status03() { return biz_status03; } public void setBiz_status03(Integer biz_status03) { this.biz_status03 = biz_status03; } public Integer getBiz_status04() { return biz_status04; } public void setBiz_status04(Integer biz_status04) { this.biz_status04 = biz_status04; } public Integer getBiz_status05() { return biz_status05; } public void setBiz_status05(Integer biz_status05) { this.biz_status05 = biz_status05; } public String getBiz_sign() { return biz_sign; } public void setBiz_sign(String biz_sign) { this.biz_sign = biz_sign; } }
package com.twair; import org.springframework.util.StringUtils; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; public class FlightSearch { private List<Flight> flightList; public FlightSearch(List<Flight> flightList) { this.flightList = flightList; } public List<Flight> getFlightList() { return flightList; } public FlightSearch byLocation(String source, String destination) { if(source == null || source.isEmpty() || destination == null || destination.isEmpty()) { throw new IllegalArgumentException("source cannot be null"); } List<Flight> matchingFlights = new ArrayList<Flight>(); for (Flight flight : flightList) { if (flight.getSource().equals(source) && flight.getDestination().equals(destination)) { matchingFlights.add(flight); } } return new FlightSearch(matchingFlights); } public FlightSearch byAvailableSeats(int numberOfSeats) { if(numberOfSeats < 0) { throw new IllegalArgumentException("number of seats can not be negative"); } List<Flight> matchingFlights = new ArrayList<>(); for (Flight flight : flightList) { if(flight.canBook(numberOfSeats)) { matchingFlights.add(flight); } } return new FlightSearch(matchingFlights); } public FlightSearch byDeparture(Calendar departureDate) { if(departureDate == null) { return this; } List<Flight> matchingFlights = new ArrayList<>(); for (Flight flight : flightList) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); if (departureDate != null) { if (dateFormat.format(flight.getDepartureTime().getTime()).equals(dateFormat.format(departureDate.getTime()))) { matchingFlights.add(flight); } } } return new FlightSearch(matchingFlights); } public FlightSearch searchSeatsByClass(String classInfo, int numberOfSeats) { if(StringUtils.isEmpty(classInfo)) { return this; } List<Flight> matchingFlights = new ArrayList<>(); for (Flight flight : flightList) { if(flight.getAvailableSeatsByClass(classInfo) >= numberOfSeats) { matchingFlights.add(flight); } } return new FlightSearch(matchingFlights); } public int getTotalTicketPrice (String classInfo, int numberOfSeats){ if("".equals(classInfo) || (classInfo == null) || numberOfSeats <= 0) { throw new IllegalArgumentException(" Illegal Argument passed as input"); } int price = 0; for (Flight flight : flightList) { if(flight.getAvailableSeatsByClass(classInfo) >= numberOfSeats) { price = flight.getPrice(classInfo,numberOfSeats); } } return price; } }
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.neuron.mytelkom.base; import android.app.Application; import uk.co.chrisjenx.calligraphy.CalligraphyConfig; public class MyTelkomApplication extends Application { public MyTelkomApplication() { } public void onCreate() { super.onCreate(); CalligraphyConfig.initDefault("fonts/MyriadPro-Regular.otf", 0x7f010000); } }
import java.text.DecimalFormat; import java.util.Scanner; public class Plus_minus { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); DecimalFormat numberFormat = new DecimalFormat("#0.000000"); double count = 0,count2 = 0,count3=0; int test = in.nextInt(); int[] num = new int[test]; for(int i = 0; i<test; i++){ num[i] = in.nextInt(); if(num[i] < 0){ count++; } if(num[i] > 0){ count2++; } if(num[i] == 0){ count3++; } } //System.out.println((count2/test)+"\n"+(count/test)+"\n"+(count3/test)); System.out.println(numberFormat.format(count2/test)); //System.out.println(); System.out.println(numberFormat.format(count/test)); //System.out.println(); System.out.println(numberFormat.format(count3/test)); } }
package com.github.nik9000.nnfa.heap; import static com.github.nik9000.nnfa.heap.AcceptsMatcher.accepts; import static org.apache.lucene.util.TestUtil.randomRealisticUnicodeString; import static org.hamcrest.Matchers.not; import org.apache.lucene.util.LuceneTestCase; import org.junit.Test; import com.github.nik9000.nnfa.builder.NfaBuilder; public class UnionTest extends LuceneTestCase { @Test public void basic() { Nfa nfa = new NfaBuilder().mark().string("candle").mark().string("light").union().build(); assertThat(nfa, accepts("candle")); assertThat(nfa, accepts("light")); assertThat(nfa, not(accepts("lemmon"))); } @Test public void unicode() { String str1 = randomRealisticUnicodeString(random(), 1, 20); String str2 = randomRealisticUnicodeString(random(), 1, 20); Nfa nfa = new NfaBuilder().mark().string(str1).mark().string(str2).union().build(); assertThat(nfa, accepts(str1)); assertThat(nfa, accepts(str2)); assertThat(nfa, not(accepts(str1 + str2))); assertThat(nfa, not(accepts(str2 + str1))); assertThat(nfa, not(accepts(str1 + str1))); assertThat(nfa, not(accepts(str2 + str2))); } @Test public void prefix() { Nfa nfa = new NfaBuilder().string("candle").mark().string(" flame").mark().string(" light").union().build(); assertThat(nfa, accepts("candle flame")); assertThat(nfa, accepts("candle light")); assertThat(nfa, not(accepts("candle"))); assertThat(nfa, not(accepts(" flame"))); assertThat(nfa, not(accepts(" light"))); } @Test public void suffix() { Nfa nfa = new NfaBuilder().mark().string("best").mark().string("state").union().string(" actor").build(); assertThat(nfa, accepts("best actor")); assertThat(nfa, accepts("state actor")); assertThat(nfa, not(accepts("best"))); assertThat(nfa, not(accepts("state"))); assertThat(nfa, not(accepts(" actor"))); } @Test public void empty() { Nfa nfa = new NfaBuilder().string("candle").mark().mark().string(" light").union().build(); assertThat(nfa, accepts("candle")); assertThat(nfa, accepts("candle light")); assertThat(nfa, not(accepts(" light"))); } @Test public void single() { Nfa nfa = new NfaBuilder().mark().string("candle").union(1).build(); assertThat(nfa, accepts("candle")); assertThat(nfa, not(accepts("lemmon"))); } @Test public void many() { int total = 20; String prefix = randomRealisticUnicodeString(random()); String suffix = randomRealisticUnicodeString(random()); String[] option = new String[total]; NfaBuilder builder = new NfaBuilder().string(prefix); for (int i = 0; i < total; i++) { option[i] = randomRealisticUnicodeString(random()); builder.mark().string(option[i]); } builder.union(total).string(suffix); Nfa nfa = builder.build(); for (int i = 0; i < total; i++) { assertThat(nfa, accepts(prefix + option[i] + suffix)); assertThat(nfa, accepts(option[i] + suffix).notIfNonEmpty(prefix)); assertThat(nfa, accepts(prefix + option[i]).notIfNonEmpty(suffix)); } } }
package ar.edu.utn.d2s.model.points; import ar.edu.utn.d2s.model.openhours.DayEnum; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.time.LocalTime; import java.util.HashSet; import java.util.Set; import static org.mockito.Mockito.*; import static org.junit.Assert.*; public class CgpTest { private Cgp cgp; @Before public void setUp() throws Exception { Service service1 = mock(Service.class); when(service1.isOpen(DayEnum.MONDAY, LocalTime.of(12, 0))).thenReturn(true); when(service1.isOpen(DayEnum.TUESDAY, LocalTime.of(18, 0))).thenReturn(false); when(service1.getName()).thenReturn("Service1"); Service service2 = mock(Service.class); when(service2.isOpen(DayEnum.MONDAY, LocalTime.of(12, 0))).thenReturn(false); when(service2.isOpen(DayEnum.TUESDAY, LocalTime.of(18, 0))).thenReturn(false); when(service2.getName()).thenReturn("Service2"); Service service3 = mock(Service.class); when(service3.isOpen(DayEnum.MONDAY, LocalTime.of(12, 0))).thenReturn(false); when(service3.isOpen(DayEnum.TUESDAY, LocalTime.of(12, 0))).thenReturn(false); when(service3.getName()).thenReturn("Service3"); Set<Service> services = new HashSet<>(); services.add(service1); services.add(service2); services.add(service3); cgp = new Cgp("CGP", "", null, null, services); } @After public void tearDown() throws Exception { } @Test public void isOpenTest() throws Exception { assertTrue(cgp.isOpen(DayEnum.MONDAY, LocalTime.of(12, 0), null)); assertTrue(cgp.isOpen(DayEnum.MONDAY, LocalTime.of(12, 0), "Service1")); assertFalse(cgp.isOpen(DayEnum.MONDAY, LocalTime.of(12, 0), "Service2")); assertFalse(cgp.isOpen(DayEnum.TUESDAY, LocalTime.of(18, 0), null)); assertFalse(cgp.isOpen(DayEnum.TUESDAY, LocalTime.of(18, 0), "Service1")); assertFalse(cgp.isOpen(DayEnum.TUESDAY, LocalTime.of(18, 0), "Service2")); assertFalse(cgp.isOpen(DayEnum.TUESDAY, LocalTime.of(18, 0), "Service3")); } }
import com.cyp.dao.UserMapper; import com.cyp.pojo.User; import com.cyp.utils.MybatisUtils; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import java.util.List; public class UserMapperTest { @Test public void test(){ SqlSession sqlSession = MybatisUtils.getSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); // List<User> list = mapper.getUsers(); // for (User user : list){ //// System.out.println(user); //// } User user = mapper.getUserById(1); System.out.println(user); sqlSession.close(); } @Test public void test2(){ SqlSession sqlSession = MybatisUtils.getSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); int a = mapper.addUser(new User(5,"绿哥","12345")); System.out.println(a); // mapper.updateUser(new User(1,"to","12333")); // System.out.println(a); // mapper.deleteUser(1); sqlSession.commit(); sqlSession.close(); } @Test public void test3(){ SqlSession sqlSession = MybatisUtils.getSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); userMapper.deleteUser(1); sqlSession.commit(); sqlSession.close(); } }
package scheduling; /* * 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. */ import java.io.IOException; import java.lang.reflect.Array; import javax.swing.JFrame; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import personalassistant.LoadAgent_Name; import static scheduling.AddGenerator2.TableInfos; import scheduling.DataGENcos; /** * * @author Af */ public class AddGenerator extends JFrame { public static int order = 0; private PreliminarInfo geninfwindow; private static ErrorMessage errormess; public static ArrayList<DataThermal> InfoSheet_t = new ArrayList(); public static ArrayList<DataHydro> InfoSheet_h = new ArrayList(); public static ArrayList<DataWind> InfoSheet_w = new ArrayList(); public static ArrayList<DataGENcos> InfoGENCO = new ArrayList(); public static String prov_name, prov_address1, prov_address2, prov_email; public static List<String> provisString; public static double [][] preHydroData;// = {{2,62,100,152,200,6,225,0.051,110},{5,163,80,100,150,6,162,0.058,150},{14,464,790,500,1000,6,1200,0.603,200},{19,662,33,50,60,6,66,0.051,250},{18,628,13,8,20,6,26,0.051,350},{14,479,1200,1000,2000,6,2586,0.199,1500},{29,985,50,40,100,6,115,0.500,2000},{30,1028,90,100,150,6,181,0.048,1000}}; public static double [][] preLinearization; //= {{0.80,0.30,0.20,0.10,15.00},{0.40,0.30,0.50,0.10,39.50},{0.20,0.10,0.30,0.20,112.50},{0.10,0.10,0.05,0.05,160.75},{0.10,0.40,0.20,0.10,152.50},{1.30,3.00,1.50,0.80,116.25},{0.75,1.50,1.20,0.90,239.00},{0.80,0.30,0.50,0.10,249.50}}; public static double [][] preOutputLimits;// = {{1.440,1.530,1.620,28.62},{1.896,2.133,2.370,69.52},{2.700,3.375,4.050,139.05},{1.929,2.894,3.858,116.38},{1.830,2.745,3.660,186.66},{18.135,18.833,19.530,833.28},{21.510,22.944,24.378,1159.63},{23.952,25.449,26.946,550.90}}; public static double [] hourlyinflow;// = {0.05,0.1}; public static double [] curves; public static double [] preinflow; public static double [][] precosts; public static double [][] preThermalData;// = {{30, 120, 40, 65, 5, 5, 900, 500, 3200, -5},{20, 110, 30, 50, 4, 3, 780, 360, 3200, -6},{130,700,80,110,6,4,4800,2250,3200,1},{100,500,100,130,4,3,7000,3600,3200,1},{120,550,100,120,4,3,6600,3300,3200,-1},{45,210,55,62,3,4,4200,2230,3200,-1}}; public static String [] preThermalFuelindex;// = {1,1,1,3,3,2}; public static double [][] preThermalcosts;// = {{2200,12},{2400,15},{6500,11},{930.5,20},{900,15},{130.2,20.5}}; public static double [][] preThermalFuelCons;// = {{45,0.3},{50,0.25},{90,0.14},{2430.5,55},{2000,0.212},{1.248,0.334}}; public static double [][] preThermalEMISSIONS;// = {{3.1604,0.0029},{3.1604,0.0029},{3.1604,0.0029},{1.84,0.00034},{1.84,0.00034},{2.8523,0.00033}}; public static double [] preGasesPrice = new double [2]; public static double [][] preWindForecast; public static double [][] preWindData; public static double [][] preWindCosts; /** * Creates new form AddGenerator */ public AddGenerator() { initComponents(); this.setTitle("Add Generator"); this.setResizable(false); this.setAlwaysOnTop(true); this.setLocationRelativeTo(null); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); try{ Import_export.LoadHydro(); Import_export.LoadThermal(); Import_export.LoadWind(); }catch(Exception u){ System.out.print(u); } if(personalassistant.LoadAgent_Name.isLoaded){ try{ scheduling.Import_export.LoadGENERATOR_toTable(AddGenerator.prov_name); }catch(IOException e){ System.out.print(e); } System.out.print(InfoSheet_t.size()); AddButton.setEnabled(false); RemoveButton.setEnabled(false); UpdateButton.setEnabled(false); jTable2.setModel(new javax.swing.table.DefaultTableModel( Import_export.loadedGencoData, new String [] { "ID", "Technology", "Fuel", "Min Power (MW)","Max Power (MW)", "MCost (USD/MW)" } )); } Name1.setText(AddGenerator.prov_name); Name1.setEnabled(false); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); Name1 = new javax.swing.JTextField(); jPanel3 = new javax.swing.JPanel(); AddButton = new javax.swing.JButton(); RemoveButton = new javax.swing.JButton(); UpdateButton = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); jTable2 = new javax.swing.JTable(); jButton1 = new javax.swing.JButton(); jButton5 = new javax.swing.JButton(); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(jTable1); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "GenCo's Info", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Arial", 1, 12))); // NOI18N jLabel1.setText("Name:"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addGap(18, 18, 18) .addComponent(Name1, javax.swing.GroupLayout.DEFAULT_SIZE, 576, Short.MAX_VALUE) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(19, 19, 19) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(Name1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(17, Short.MAX_VALUE)) ); jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Technology Portfolio", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Arial", 1, 12))); // NOI18N AddButton.setText("Add"); AddButton.setPreferredSize(new java.awt.Dimension(71, 36)); AddButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AddButtonActionPerformed(evt); } }); RemoveButton.setText("Remove"); RemoveButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { RemoveButtonActionPerformed(evt); } }); UpdateButton.setText("Update"); UpdateButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { UpdateButtonActionPerformed(evt); } }); jTable2.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); jScrollPane2.setViewportView(jTable2); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(AddButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(RemoveButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(UpdateButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addContainerGap(17, Short.MAX_VALUE) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(AddButton, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(RemoveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(UpdateButton, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(14, 14, 14)) ); jButton1.setText("Cancel"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton5.setText("Save"); jButton5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton5ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton5) .addGap(18, 18, 18) .addComponent(jButton1) .addGap(25, 25, 25)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(29, 29, 29) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jButton5)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); pack(); }// </editor-fold>//GEN-END:initComponents //CANCEL BUTTON private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed this.dispose(); // TODO add your handling code here: }//GEN-LAST:event_jButton1ActionPerformed //SAVE BUTTON private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed if(personalassistant.LoadAgent_Name.isLoaded){ try{ Import_export.SaveLoadedGenerator(AddGenerator.prov_name); personalassistant.LoadAgent_Name.isLoaded = false; this.dispose(); }catch(IOException e){ System.out.print(e); } catch (MinMaxException ex) { Logger.getLogger(AddGenerator.class.getName()).log(Level.SEVERE, null, ex); } catch (MediumValueException ex) { Logger.getLogger(AddGenerator.class.getName()).log(Level.SEVERE, null, ex); } }else{ errormess = new ErrorMessage("","No units inserted for saving!"); errormess.setVisible(true); } }//GEN-LAST:event_jButton5ActionPerformed //ADD BUTTON private void AddButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddButtonActionPerformed geninfwindow = new PreliminarInfo(); geninfwindow.setVisible(true); this.dispose(); }//GEN-LAST:event_AddButtonActionPerformed //UPDATE BUTTON private void UpdateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_UpdateButtonActionPerformed errormess = new ErrorMessage("","No units inserted for update"); errormess.setVisible(true); }//GEN-LAST:event_UpdateButtonActionPerformed private void RemoveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RemoveButtonActionPerformed errormess = new ErrorMessage("","No units available for removal"); errormess.setVisible(true); }//GEN-LAST:event_RemoveButtonActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(AddGenerator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AddGenerator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AddGenerator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AddGenerator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new AddGenerator().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton AddButton; private javax.swing.JTextField Name1; private javax.swing.JButton RemoveButton; private javax.swing.JButton UpdateButton; private javax.swing.JButton jButton1; private javax.swing.JButton jButton5; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTable jTable1; private javax.swing.JTable jTable2; // End of variables declaration//GEN-END:variables }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package edu.math.nelson.chris; import edu.jenks.dist.math.AbstractRational; /** * * @author chris */ public class Rational extends AbstractRational{ /** * @param args the command line arguments */ public Rational(long numer, long denom){ super(numer,denom); if(denom<0){ long newNumer = numer - (2*numer); long newDenom = denom + (-2*denom); super.setNumerator(newNumer); super.setDenominator(newDenom); } reduce(); } public static void main(String[] args) { Rational test = new Rational(789,433); Rational num = new Rational (147,313); System.out.println(num.compareTo(test)); } public boolean equals(AbstractRational rn2){ long num1 = this.getNumerator(); long num2 = rn2.getNumerator(); long den1 = this.getDenominator(); long den2 = rn2.getDenominator(); return (num1==num2)&&(den1==den2); } public void reduce(){ long den = this.getDenominator(); long num = this.getNumerator(); long greatest = 1; if(num != 0){ greatest = gcd(num, den); } num = num / greatest; den = den / greatest; this.setNumerator(num); this.setDenominator(den); } public String toString(){ long num = this.getNumerator(); long den = this.getDenominator(); if(num % den == 0){ long integer = num / den; return "" + integer; } return num + "/" + den; } public boolean decimalTerminates(){ long denom = this.getDenominator(); while(denom % 2 ==0 || denom %5 == 0){ if(denom % 2 == 0){ denom /= 2; }else{ denom /= 5; } System.out.println(denom); } if(denom == 1){ return true; } return false; } public int compareTo(AbstractRational arg0){ long num1 = this.getNumerator(); long num2 = arg0.getNumerator(); long den1 = this.getDenominator(); long den2 = arg0.getDenominator(); num1 *= den2; num2 *= den1; den1 *= den2; Rational difference = new Rational((num1-num2),den1); long diff = difference.getNumerator(); int ret = Math.toIntExact(diff); if(diff>0 && diff<Integer.MAX_VALUE){ return ret; }else if(diff<0 && diff>Integer.MIN_VALUE){ return ret; } return 0; } public AbstractRational multiply(AbstractRational op2){ long num1 = this.getNumerator(); long num2 = op2.getNumerator(); long den1 = this.getDenominator(); long den2 = op2.getDenominator(); long newNum = num1 * num2; long newDen = den1 * den2; Rational mult = new Rational(newNum, newDen); return mult; } public AbstractRational divide(AbstractRational op2){ return this.multiply(op2.reciprocal()); } public AbstractRational reciprocal(){ long num = this.getNumerator(); long den = this.getDenominator(); long temp = this.getNumerator(); num = den; den = temp; Rational recip = new Rational(num, den); return recip; } public AbstractRational subtract(AbstractRational op2){ long negNum = -op2.getNumerator(); long den = op2.getDenominator(); Rational newRational = new Rational(negNum,den); return this.add(newRational); } public AbstractRational add(AbstractRational op2){ long num1 = this.getNumerator(); long num2 = op2.getNumerator(); long den1 = this.getDenominator(); long den2 = op2.getDenominator(); num2 *= den1; num1 *= den2; den1 *= den2; long newNum = num1 + num2; Rational add = new Rational(newNum, den1); return add; } }
package com.checkout.shop.preinterview.java; public enum ProductInfo { APPLE(0.60), ORANGE(0.25); double price; ProductInfo(double p) { price = p; } double showPrice() { return price; } }
package me.gleep.oreganized.effects; import com.mojang.blaze3d.matrix.MatrixStack; import me.gleep.oreganized.util.ModDamageSource; import me.gleep.oreganized.util.RegistryHandler; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.AbstractGui; import net.minecraft.client.gui.DisplayEffectsScreen; import net.minecraft.client.renderer.texture.PotionSpriteUploader; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.entity.Entity; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.monster.MonsterEntity; import net.minecraft.potion.Effect; import net.minecraft.potion.EffectInstance; import net.minecraft.potion.EffectType; import net.minecraft.util.math.AxisAlignedBB; import java.util.List; public class DawnShine extends Effect { public DawnShine() { super(EffectType.NEUTRAL, 0xAFAFFF); } @Override public boolean isInstant() { return false; } @Override public boolean shouldRenderInvText(EffectInstance effect) { return true; } @Override public boolean shouldRenderHUD(EffectInstance effect) { return false; } @Override public boolean shouldRender(EffectInstance effect) { return true; } @Override public void performEffect(LivingEntity entityLivingBaseIn, int amplifier) { if (entityLivingBaseIn.isEntityUndead()) { if (entityLivingBaseIn.getHealth() > 1.0F) { entityLivingBaseIn.attackEntityFrom(ModDamageSource.MAGIC, 1.0F); } if (amplifier > 0) { List<Entity> list = entityLivingBaseIn.getEntityWorld().getEntitiesInAABBexcluding(entityLivingBaseIn, new AxisAlignedBB( entityLivingBaseIn.getPosX() + 2.0D, entityLivingBaseIn.getPosY() + 2.0D, entityLivingBaseIn.getPosZ() + 2.0D, entityLivingBaseIn.getPosX() - 2.0D, entityLivingBaseIn.getPosY() - 2.0D, entityLivingBaseIn.getPosZ() - 2.0D), (Entity entity) -> entity instanceof LivingEntity ); int i = 0; for (Entity e : list) { if (i <= Math.floor(Math.sqrt(amplifier))) { if (((LivingEntity) e).getActivePotionEffect(RegistryHandler.DAWN_SHINE.get()) == null && ((LivingEntity) e).getActivePotionEffect(RegistryHandler.NON_DAWN_SHINE.get()) == null) { ((LivingEntity) e).addPotionEffect(new EffectInstance(RegistryHandler.NON_DAWN_SHINE.get(), 200, 0)); i++; } } } } } else { EffectInstance instance = entityLivingBaseIn.removeActivePotionEffect(RegistryHandler.DAWN_SHINE.get()); if (instance != null) entityLivingBaseIn.addPotionEffect(new EffectInstance(RegistryHandler.NON_DAWN_SHINE.get(), instance.getDuration(), instance.getAmplifier())); } } @Override public boolean isReady(int duration, int amplifier) { int i = 25 >> amplifier; if (i > 0) { return duration % i == 0; } else { return true; } } /** * Called to draw the this Potion onto the player's inventory when it's active. * This can be used to e.g. render Potion icons from your own texture. * * @param effect the active PotionEffect * @param gui the gui instance * @param mStack The MatrixStack * @param x the x coordinate * @param y the y coordinate * @param z the z level */ @Override public void renderInventoryEffect(EffectInstance effect, DisplayEffectsScreen<?> gui, MatrixStack mStack, int x, int y, float z) { } /** * Called to draw the this Potion onto the player's ingame HUD when it's active. * This can be used to e.g. render Potion icons from your own texture. * * @param effect the active PotionEffect * @param gui the gui instance * @param mStack The MatrixStack * @param x the x coordinate * @param y the y coordinate * @param z the z level * @param alpha the alpha value, blinks when the potion is about to run out */ @Override public void renderHUDEffect(EffectInstance effect, AbstractGui gui, MatrixStack mStack, int x, int y, float z, float alpha) { } }
package com.nt.dao; import com.nt.bo.UserBo; public interface IUserDao { public String authentication(UserBo bo); }
package com.beadhouse.controller; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import com.beadhouse.in.CollectionParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.beadhouse.out.BasicData; import com.beadhouse.service.CollectionService; @RestController public class CollectionController { @Autowired CollectionService collectionService; /** * 用户收藏消息 * * @param request * @return */ @RequestMapping("collection") @ResponseBody @Transactional public BasicData collection(@Valid @RequestBody CollectionParam param, HttpServletRequest request) { return collectionService.collection(param); } /** * 删除收藏消息 * * @param request * @return */ @RequestMapping("delcollection") @ResponseBody @Transactional public BasicData delcollection(@Valid @RequestBody CollectionParam param, HttpServletRequest request) { return collectionService.delcollection(param); } /** * 老人收藏消息 * * @param request * @return */ @RequestMapping("eldercollection") @ResponseBody @Transactional public BasicData eldercollection(@Valid @RequestBody CollectionParam param, HttpServletRequest request) { return collectionService.eldercollection(param); } /** * 删除老人收藏消息 * * @param request * @return */ @RequestMapping("elder/delcollection") @ResponseBody @Transactional public BasicData deleldercollection(@Valid @RequestBody CollectionParam param, HttpServletRequest request) { return collectionService.deleldercollection(param); } }
package com.javarush.task.task17.task1710; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; /* CRUD */ public class Solution { public static List<Person> allPeople = new ArrayList<Person>(); static { allPeople.add(Person.createMale("Иванов Иван", new Date())); //сегодня родился id=0 allPeople.add(Person.createMale("Петров Петр", new Date())); //сегодня родился id=1 } public static void main(String[] args) throws ParseException { DateTimeFormatter oldFormat = DateTimeFormatter.ofPattern( "dd/MM/yyyy" , Locale.UK ); DateTimeFormatter newFormat = DateTimeFormatter.ofPattern( "dd-MMM-yyyy" , Locale.UK ); DateTimeFormatter defaultFormat = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy"); SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy"); if(args[0].equals("-c")){ String date = LocalDate.parse(args[3], oldFormat).format(newFormat); Date newDate = sdf.parse(date); if(args[2].equals("м")){ Person person = Person.createMale(args[1], new SimpleDateFormat("dd/MM/yyyy").parse(args[3])); allPeople.add(person); System.out.println(allPeople.indexOf(person)); System.out.println(sdf.format(person.getBirthDate())); }else{ Person person = Person.createFemale(args[1], new SimpleDateFormat("dd/MM/yyyy").parse(args[3])); allPeople.add(person); System.out.println(allPeople.indexOf(person)); } } else if(args[0].equals("-u")){ String date = LocalDate.parse(args[4], oldFormat).format(newFormat); Date newDate = sdf.parse(date); int id = Integer.parseInt(args[1]); allPeople.get(id).setName(args[2]); allPeople.get(id).setBirthDate(newDate); if(args[3].equals("m")) allPeople.get(id).setSex(Sex.MALE); else allPeople.get(id).setSex(Sex.FEMALE); } else if(args[0].equals("-d")){ int id = Integer.parseInt(args[1]); allPeople.get(id).setName(null); allPeople.get(id).setBirthDate(null); allPeople.get(id).setSex(null); } else if(args[0].equals("-i")){ int id = Integer.parseInt(args[1]); String name = allPeople.get(id).getName(); String oldBd = allPeople.get(id).getBirthDate().toString(); String date = LocalDate.parse(oldBd, defaultFormat).format(newFormat); Sex sex = allPeople.get(id).getSex(); String s; if(sex.toString().equals("MALE")) s="м"; else s="ж"; System.out.println(name + " " + s + " " + date); } } }
package slimeknights.tconstruct.tools.traits; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.TextFormatting; import net.minecraft.world.World; import net.minecraftforge.event.entity.player.PlayerEvent; import slimeknights.tconstruct.library.Util; import slimeknights.tconstruct.library.potion.TinkerPotion; import slimeknights.tconstruct.library.traits.AbstractTrait; import slimeknights.tconstruct.library.utils.ToolHelper; public class TraitMomentum extends AbstractTrait { public static final TinkerPotion Momentum = new TinkerPotion(Util.getResource("momentum"), false, false); public TraitMomentum() { super("momentum", TextFormatting.BLUE); } @Override public void miningSpeed(ItemStack tool, PlayerEvent.BreakSpeed event) { float boost = Momentum.getLevel(event.getEntityPlayer()); boost /= 80f; // 40% boost max event.setNewSpeed(event.getNewSpeed() + event.getOriginalSpeed() * boost); } @Override public void afterBlockBreak(ItemStack tool, World world, IBlockState state, BlockPos pos, EntityLivingBase player, boolean wasEffective) { int level = 1; level += Momentum.getLevel(player); level = Math.min(32, level); int duration = (int) ((10f / ToolHelper.getActualMiningSpeed(tool)) * 1.5f * 20f); Momentum.apply(player, duration, level); } }
package com.wenyuankeji.spring.dao.impl; import java.io.Serializable; import java.util.List; import javax.annotation.Resource; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.stereotype.Repository; import com.wenyuankeji.spring.dao.IStoreinfoDao; import com.wenyuankeji.spring.model.StoreinfoModel; import com.wenyuankeji.spring.util.BaseException; @Repository public class StoreinfoDaoImpl implements IStoreinfoDao{ @Resource(name = "sessionFactory") private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override public StoreinfoModel searchStoreinfo(int storeid) throws BaseException { StoreinfoModel storeinfoModel = null; try { Session session = sessionFactory.getCurrentSession(); String hql = "FROM StoreinfoModel WHERE storeid=?"; Query query = session.createQuery(hql); query.setInteger(0, storeid); @SuppressWarnings("unchecked") List<Object> oList = query.list(); if (null != oList && oList.size() > 0) { storeinfoModel = (StoreinfoModel) oList.get(0); } return storeinfoModel; } catch (Exception e) { throw new BaseException(e.getMessage()); } } @Override public boolean updateStoreinfo(StoreinfoModel storeinfoModel) { Session session = sessionFactory.getCurrentSession(); StringBuffer sql = new StringBuffer("UPDATE StoreinfoModel SET state=? WHERE storeid = ? "); Query query = session.createQuery(sql.toString()); query.setInteger(0, storeinfoModel.getState()); query.setInteger(1, storeinfoModel.getStoreid()); int isok = query.executeUpdate(); if (isok > 0) { return true; } return false; } @Override public List<StoreinfoModel> searchStoreinfo(String storeid, String startTime, String endTime, String state, String name, int page, int rows) throws BaseException { Session session = sessionFactory.getCurrentSession(); try { StringBuffer sql = new StringBuffer("FROM StoreinfoModel WHERE 1=1 "); //商户ID if (storeid !=null && storeid.trim().length() > 0) { sql.append(" and storeid='"+ storeid +"' "); } //注册开始时间 if (startTime !=null && startTime.trim().length() > 0) { sql.append(" and createtime>='"+ startTime +" 00:00:00' "); } //注册结束时间 if (endTime !=null && endTime.trim().length() > 0) { sql.append(" and createtime<='"+ endTime +" 23:59:59' "); } //审核状态 if (state !=null && state.trim().length() > 0 && !state.equals("-1")) { if("0".equals(state)){ sql.append(" and state != 2 "); }else{ sql.append(" and state = 2 "); } } //商户名称 if (name !=null && name.trim().length() > 0) { sql.append(" and name like '%"+ name +"%' "); } Query query = session.createQuery(sql.toString()); query.setFirstResult((page - 1) * rows); query.setMaxResults(rows); @SuppressWarnings("unchecked") List<StoreinfoModel> storeinfoModels = (List<StoreinfoModel>) query.list(); return storeinfoModels; } catch (Exception e) { throw new BaseException(e.getMessage()); } } @Override public int searchStoreinfoCount(String storeid, String startTime, String endTime, String state, String name) throws BaseException { Session session = sessionFactory.getCurrentSession(); try { StringBuffer sql = new StringBuffer("FROM StoreinfoModel WHERE 1=1 "); //商户ID if (storeid !=null && storeid.trim().length() > 0) { sql.append(" and storeid='"+ storeid +"' "); } //注册开始时间 if (startTime !=null && startTime.trim().length() > 0) { sql.append(" and createtime>='"+ startTime +" 00:00:00' "); } //注册结束时间 if (endTime !=null && endTime.trim().length() > 0) { sql.append(" and createtime<='"+ endTime +" 23:59:59' "); } //审核状态 if (state !=null && state.trim().length() > 0 && !state.equals("-1")) { if("0".equals(state)){ sql.append(" and state != 2 "); }else{ sql.append(" and state = 2 "); } } //商户名称 if (name !=null && name.trim().length() > 0) { sql.append(" and name like '%"+ name +"%' "); } Query query = session.createQuery(sql.toString()); @SuppressWarnings("unchecked") List<StoreinfoModel> storeinfoModels = (List<StoreinfoModel>) query.list(); return storeinfoModels.size(); } catch (Exception e) { throw new BaseException(e.getMessage()); } } @Override public int addInitStoreinfo(StoreinfoModel storeinfoModel) throws Exception { int result = 0; Session session = sessionFactory.getCurrentSession(); Serializable isok = session.save(storeinfoModel); if (Integer.parseInt(isok.toString()) > 0) { result = Integer.parseInt(isok.toString()); } return result; } @Override public boolean updateStore(StoreinfoModel storeinfo) throws BaseException { Session session = sessionFactory.getCurrentSession(); try { StringBuffer hql = new StringBuffer(); hql.append("UPDATE StoreinfoModel SET "); hql.append("name=?, "); hql.append("provinceid=?, "); hql.append("cityid=?, "); hql.append("districtid=?, "); hql.append("address=?, "); hql.append("tel=?, "); hql.append("carnumber=?, "); hql.append("businesshours=?, "); hql.append("areaid=?, "); hql.append("empiricalmode=?, "); hql.append("intro=?, "); hql.append("bossname=?, "); hql.append("bossmobile=?, "); hql.append("storemanagername=?, "); hql.append("storemanagermobile=?, "); hql.append("state=?, "); hql.append("longitude=?, "); hql.append("latitude=?, "); hql.append("ownername=?, "); hql.append("bank=?, "); hql.append("cardnumber=?, "); hql.append("allocation=? "); hql.append("WHERE "); hql.append("storeid=? "); Query query = session.createQuery(hql.toString()); query.setString(0, storeinfo.getName()); query.setInteger(1, storeinfo.getProvinceid()); query.setInteger(2, storeinfo.getCityid()); query.setInteger(3, storeinfo.getDistrictid()); query.setString(4, storeinfo.getAddress()); query.setString(5, storeinfo.getTel()); query.setInteger(6, storeinfo.getCarnumber()); query.setString(7, storeinfo.getBusinesshours()); query.setInteger(8, storeinfo.getAreaid()); query.setInteger(9, storeinfo.getEmpiricalmode()); query.setString(10, storeinfo.getIntro()); query.setString(11, storeinfo.getBossname()); query.setString(12, storeinfo.getBossmobile()); query.setString(13, storeinfo.getStoremanagername()); query.setString(14, storeinfo.getStoremanagermobile()); query.setInteger(15, storeinfo.getState()); query.setString(16, storeinfo.getLongitude()); query.setString(17, storeinfo.getLatitude()); query.setString(18, storeinfo.getOwnername()); query.setString(19, storeinfo.getBank()); query.setString(20, storeinfo.getCardnumber()); query.setString(21, storeinfo.getAllocation()); query.setInteger(22, storeinfo.getStoreid()); int isok = query.executeUpdate(); if (isok > 0) { return true; } } catch (Exception e) { throw new BaseException(e.getMessage()); } return false; } }
package Files; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class Main { public static StringBuilder str = new StringBuilder(); public static String FILEPATH = "C:/Users/503242115/IdeaProjects/Initial" + File.separator; public static void main(String[] args) { addDir(FILEPATH + "Games"); addDir(FILEPATH + "Games/src"); addDir(FILEPATH + "Games/res"); addDir(FILEPATH + "Games/res/drawables"); addDir(FILEPATH + "Games/res/vectors"); addDir(FILEPATH + "Games/res/icons"); addDir(FILEPATH + "Games/savegames"); addDir(FILEPATH + "Games/src/main"); addDir(FILEPATH + "Games/src/test"); addDir(FILEPATH + "Games/temp"); addFile(FILEPATH + "Games/src/main//Main.java"); addFile(FILEPATH + "Games/src/main//Utils.java"); File temp_txt = new File(FILEPATH + "Games/temp//temp.txt"); try { if (temp_txt.createNewFile()) System.out.println(">> File 'temp.txt' was successfully created"); str.append("\n>> File 'temp.txt' was successfully created"); try (FileOutputStream fos = new FileOutputStream(temp_txt)) { byte[] bytes = str.toString().getBytes(); fos.write(bytes, 0, bytes.length); } catch (IOException io) { System.out.println(io.getMessage()); } ; } catch (IOException io) { System.out.println(io.getMessage()); } } private static StringBuilder addFile(String fileName) { File file = new File(fileName); try { if (file.createNewFile()) System.out.println(">> File '" + fileName + "' was successfully created"); str.append("\n>> File '" + fileName + "' was successfully created"); } catch (IOException io) { System.out.println(io.getMessage()); } return str; } private static StringBuilder addDir(String dirName) { File dir = new File(dirName); if (dir.mkdir()) System.out.println(">> Dir '" + dirName + "' was successfully created"); str.append("\n>> Dir '" + dirName + "' was successfully created"); return str; } }
package turtlekit.viewer.viewer3D.engine.tools; import javax.media.opengl.GL2; public class Material { private GL2 gl; private float data; public Material(GL2 cGl, float cData){ gl = cGl; data = cData; initMaterial(); } public void initMaterial(){ float mat_amb_diff[] = { data/255.f, data/255.f, data/255.f, 1.0f }; float mat_specular[] = { data/255.f, data/255.f, data/255.f, 1.0f }; float low_shininess[] = { 0.0f }; gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_SPECULAR, mat_specular, 0); gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_SHININESS, low_shininess, 0); gl.glMaterialfv(GL2.GL_FRONT_AND_BACK, GL2.GL_AMBIENT, mat_amb_diff, 0); gl.glMaterialfv(GL2.GL_FRONT_AND_BACK, GL2.GL_DIFFUSE, mat_amb_diff, 0); } }
package model; import java.util.ArrayList; public class Order { private String item; private int quantity; private final int cost = 10; private String merchantEmail; private String merchantKey; private String orderName; private static ArrayList<Object> payoptions = new ArrayList<Object>(); private static ArrayList<Object> payoptionsNames = new ArrayList<Object>(); public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public int getCost() { return cost; } public String getItems() { return item; } public void setItem(String item) { this.item = item; } public String getMerchantKey() { return merchantKey; } public void setMerchantKey(String merchantKey) { this.merchantKey = merchantKey; } public String getMerchantEmail() { return merchantEmail; } public void setMerchantEmail(String merchantEmail) { this.merchantEmail = merchantEmail; } public String getOrderName() { return orderName; } public void setOrderName(String orderName) { this.orderName = orderName; } public ArrayList<Object> getPayoptions() { return payoptions; } public void setPayoptions(ArrayList<Object> payoptions) { Order.payoptions = payoptions; } public ArrayList<Object> getPayoptionsNames() { return payoptionsNames; } public void setPayoptionsNames(ArrayList<Object> payoptionsNames) { Order.payoptionsNames = payoptionsNames; } }
package gov.nih.mipav.model.algorithms.filters; import gov.nih.mipav.model.algorithms.*; import gov.nih.mipav.model.structures.*; import java.io.*; /** * Algorithm to apply Regularized Isotropic Nonlinear Diffusion as described by: * * <P>Joachim Weickert <I>Chapter 15</I> in Handbook of Computer Vision and Applications, Volume 2 Signal Processing and * Pattern Recognition. The book is published by Academic Press, ISBN 0-12-379772-1</P> * * <P>Here is a listing of the author's terminology used in the title.</P> * * <UL> * <LI><B>Regularized</B> the computed image is blurred with a Gaussian kernel prior to taking finite derivatives</LI> * <LI> <B>Isotropic</B> the gradient and flux are parallel</LI> * <LI> <B>Nonlinear</B> the weights used for combining pixels change over the image, space variant.</LI> * <LI><B>Diffusion</B> this model uses the heat equation</LI> * </UL> * * @version 1.0; 31, July 2003 * @author Paul F. Hemler, Ph.D. */ public class AlgorithmRegularizedIsotropicDiffusion extends AlgorithmBase { //~ Instance fields ------------------------------------------------------------------------------------------------ /** The number of iterations. */ int numIterations = 0; /** * The time parameter step size, called tau in the algorithm description In 2D for stability the time step should be * <= 0.25. In 3D for stability the time step should be <= 1/6. */ float timeStep = 0.25f; /** Handle to the separable convolution kernel. */ private AlgorithmSeparableConvolver algoSepConvolver; /** Handle to the separable convolution kernel. */ private AlgorithmSeparableConvolver algoSepConvolverB; /** Handle to the separable convolution kernel. */ private AlgorithmSeparableConvolver algoSepConvolverG; /** Handle to the separable convolution kernel. */ private AlgorithmSeparableConvolver algoSepConvolverR; /** Diffusion contrast parameter. */ private float contrast = 0.15f; /** Flag indicating 2.5D processing. */ private boolean do25D = true; /** Contrast multiplied by the maximum gradient. */ private float lambda; // /** Standard deviations of the gaussian used to calculate the kernels. */ private float[] sigmas = null; /** Standard deviation used for the Gaussians. */ private float stdDev = 1.0f; /** Storage location for the 1D gaussian kernels. */ private float[] xDataRound = null; /** Image dimensions. */ private int xDim, yDim, zDim; /** Storage location for the 1D gaussian kernels. */ private float[] yDataRound = null; /** Storage location for the 1D gaussian kernels. */ private float[] zDataRound = null; //~ Constructors --------------------------------------------------------------------------------------------------- /** * Creates a new AlgorithmRegularizedIsotropicDiffusion object. * * @param destImg ModelImage image model where result image is to stored * @param srcImg ModelImage source image model * @param numI int number of iterations * @param stdDev float standard deviation used in the Gaussians * @param contrast float diffusion contrast parameter * @param do25D boolean If true, process each slice separately */ public AlgorithmRegularizedIsotropicDiffusion(ModelImage destImg, ModelImage srcImg, int numI, float stdDev, float contrast, boolean do25D) { super(destImg, srcImg); numIterations = numI; this.stdDev = stdDev; this.contrast = contrast; this.do25D = do25D; } //~ Methods -------------------------------------------------------------------------------------------------------- /** * Prepares this class for destruction. */ public void finalize() { srcImage = null; sigmas = null; xDataRound = null; yDataRound = null; zDataRound = null; super.finalize(); } // end finalize() /** * Starts the program. */ public void runAlgorithm() { if (srcImage == null) { displayError("AlgorithmRegularizedIsotropicDiffusion.run() Source Image is null"); return; } if ((srcImage.getNDims() == 2) || do25D) { timeStep = 0.2f; } else { timeStep = 0.15f; } if (srcImage.isColorImage()) { if (srcImage.getNDims() == 2) { run2DC(1); } else if ((srcImage.getNDims() == 3) && (do25D == true)) { run2DC(srcImage.getExtents()[2]); } else { run3DC(); } } else { if (srcImage.getNDims() == 2) { run2D(1); } else if ((srcImage.getNDims() == 3) && (do25D == true)) { run2D(srcImage.getExtents()[2]); } else { run3D(); } } } // end run() /** * Returns the weighting for values used in computing new (diffused) pixel values. * * @param d float Value to compute the diffusivity * * @return float The value of the diffusivity corresponding to the d value */ private float diffusivity(float d) { return (1.0f / (1.0f + ((d * d) / (lambda * lambda)))); } // end diffusivity(...) /** * Returns the value in a 2D image buffer of the pixel at location col, row. * * @param buffer float[] The image buffer * @param col int Column index * @param row int Row index * * @return float The pixel value */ private float getVal(float[] buffer, int col, int row) { float rtnVal; if (col < 0) { col = 0; } if (col >= xDim) { col = xDim - 1; } if (row < 0) { row = 0; } if (row >= yDim) { row = yDim - 1; } rtnVal = buffer[(row * xDim) + col]; return rtnVal; } // end getVal(...) /** * Returns the value in a 3D image buffer of the pixel at location col, row, slice. * * @param buffer float[] The image buffer * @param col int Column index * @param row int Row index * @param slice int Slice index * * @return float The pixel value */ private float getVal(float[] buffer, int col, int row, int slice) { float rtnVal; if (col < 0) { col = 0; } if (col >= xDim) { col = xDim - 1; } if (row < 0) { row = 0; } if (row >= yDim) { row = yDim - 1; } if (slice < 0) { slice = 0; } if (slice >= zDim) { slice = zDim - 1; } rtnVal = buffer[(slice * yDim * xDim) + (row * xDim) + col]; return rtnVal; } // end getVal(...) /** * Computes the gradient magnitude of the buffer passed in. This version computes values for the image borders and * corners * * @param img float [] source buffer * @param mag float [] a buffer where the gradient magnitude will be placed */ private void gradientMagnitude(float[] img, float[] mag) { int row, col, cIndex; float gradX; float gradY; for (row = 0; row < yDim; row++) { cIndex = row * xDim; for (col = 0; col < xDim; cIndex++, col++) { if (col == 0) { gradX = 2 * (img[cIndex + 1] - img[cIndex]); } else if (col == (xDim - 1)) { gradX = 2 * (img[cIndex] - img[cIndex - 1]); } else { gradX = img[cIndex + 1] - img[cIndex - 1]; } if (row == 0) { gradY = 2 * (img[cIndex + xDim] - img[cIndex]); } else if (row == (yDim - 1)) { gradY = 2 * (img[cIndex] - img[cIndex - xDim]); } else { gradY = img[cIndex + xDim] - img[cIndex - xDim]; } mag[cIndex] = (float) Math.sqrt((gradX * gradX) + (gradY * gradY)); } // for (col = 0; ...) } // for (row = 0; ...) } // end gradientMagnitude(...) /** * Computes the gradient magnitude of the buffer passed in. This version computes values for the image borders and * corners * * @param img float [] source buffer * @param mag float [] a buffer where the gradient magnitude will be placed */ private void gradientMagnitude3D(float[] img, float[] mag) { int slice, row, col, cIndex, sIndex; float gradX; float gradY; float gradZ; int sliceSize = yDim * xDim; for (slice = 0; slice < zDim; slice++) { sIndex = slice * sliceSize; for (row = 0; row < yDim; row++) { cIndex = sIndex + (row * xDim); for (col = 0; col < xDim; cIndex++, col++) { if (col == 0) { gradX = 2 * (img[cIndex + 1] - img[cIndex]); } else if (col == (xDim - 1)) { gradX = 2 * (img[cIndex] - img[cIndex - 1]); } else { gradX = img[cIndex + 1] - img[cIndex - 1]; } if (row == 0) { gradY = 2 * (img[cIndex + xDim] - img[cIndex]); } else if (row == (yDim - 1)) { gradY = 2 * (img[cIndex] - img[cIndex - xDim]); } else { gradY = img[cIndex + xDim] - img[cIndex - xDim]; } if (slice == 0) { gradZ = 2 * (img[cIndex + sliceSize] - img[cIndex]); } else if (slice == (zDim - 1)) { gradZ = 2 * (img[cIndex] - img[cIndex - sliceSize]); } else { gradZ = img[cIndex + sliceSize] - img[cIndex - sliceSize]; } mag[cIndex] = (float) Math.sqrt((gradX * gradX) + (gradY * gradY) + (gradZ * gradZ)); } // for (col = 0; ...) } // for (row = 0; ...) } // for (slice = 0; ...) } // end gradientMagnitude3D(...) /** * DOCUMENT ME! * * @param do3D boolean Flag indicating if a 3D kernel should be computed */ private void makeKernels1D(boolean do3D) { // make 1D rounding kernels with no derivatives int xkDim, ykDim, zkDim; int[] derivOrder = new int[1]; int[] kExtents = new int[1]; xkDim = Math.round(5 * sigmas[0]); if ((xkDim % 2) == 0) { xkDim++; } if (xkDim < 3) { xkDim = 3; } ykDim = Math.round(5 * sigmas[1]); if ((ykDim % 2) == 0) { ykDim++; } if (ykDim < 3) { ykDim = 3; } kExtents[0] = xkDim; float[] sigmasX = new float[1]; sigmasX[0] = sigmas[0]; derivOrder[0] = 0; xDataRound = new float[xkDim]; GenerateGaussian Gx = new GenerateGaussian(xDataRound, kExtents, sigmasX, derivOrder); Gx.calc(false); kExtents[0] = ykDim; float[] sigmasY = new float[1]; sigmasY[0] = sigmas[1]; derivOrder[0] = 0; yDataRound = new float[ykDim]; GenerateGaussian Gy = new GenerateGaussian(yDataRound, kExtents, sigmasY, derivOrder); Gy.calc(true); if (do3D) { zkDim = Math.round(5 * sigmas[2]); if ((zkDim % 2) == 0) { zkDim++; } if (zkDim < 3) { zkDim = 3; } kExtents[0] = zkDim; float[] sigmasZ = new float[1]; sigmasZ[0] = sigmas[2]; derivOrder[0] = 0; zDataRound = new float[zkDim]; GenerateGaussian Gz = new GenerateGaussian(zDataRound, kExtents, sigmasZ, derivOrder); Gz.calc(true); } } /** * Iterates the Regularized Isotropic Nonlinear Diffusion algorithm for 2D and 2.5D images. * * @param numImages int number of images to be blurred. If 2D image then nImage = 1, if 3D image where each slice * is to processed independently then nImages equals the number of slices in the volume. */ private void run2D(int numImages) { fireProgressStateChanged(0, srcImage.getImageName(), "Regularized Isotropic Diffusion ..."); // OK, here is where the meat of the algorithm goes int length; int[] extents = new int[2]; extents[0] = srcImage.getExtents()[0]; extents[1] = srcImage.getExtents()[1]; xDim = extents[0]; yDim = extents[1]; length = xDim * yDim; // buffers for the image data float[] sourceBuffer; float[] resultBuffer; float[] gaussianBuffer; float[] gradientBuffer; // copy the image data into the sourceBuffer so we can access it try { sourceBuffer = new float[length]; resultBuffer = new float[length]; gradientBuffer = new float[length]; } catch (OutOfMemoryError e) { sourceBuffer = resultBuffer = gaussianBuffer = gradientBuffer = null; errorCleanUp("AlgorithmRegularizedIsotropicDiffusion: Out of memory when creating image buffer", true); return; } // catch{} // Gaussian blur the input image as a 2.5D image set sigmas = new float[2]; sigmas[0] = sigmas[1] = stdDev; makeKernels1D(false); // source image is in sourceBuffer, gaussian smoothed image is in gaussianBuffer int startIndex; float stepProgressValue = ((float)100)/(numImages * numIterations); float progressValue = 0; for (int imgNumber = 0; imgNumber < numImages; imgNumber++) { startIndex = imgNumber * length; try { srcImage.exportData(startIndex, length, sourceBuffer); } catch (IOException error) { sourceBuffer = resultBuffer = gaussianBuffer = gradientBuffer = null; errorCleanUp("AlgorithmRegularizedIsotropicDiffusion: could NOT export source image", true); return; } // catch() for (int iterNum = 0; iterNum < numIterations; iterNum++) { progressValue +=stepProgressValue; fireProgressStateChanged((int)progressValue); // make the magnitude of the gradient image of the gaussian smoothed source image // A separate constructor AlgorithmSeparableConvolver call is needed for each iteration // because the constructor has the line // MipavUtil.arrayCopy(srcBuffer, 0, inputBuffer, 0, srcBuffer.length); // so having the constructor before the iteration loop would result in // using the initial srcBuffer for each iteration. algoSepConvolver = new AlgorithmSeparableConvolver(sourceBuffer, extents, new float[][]{xDataRound, yDataRound}, srcImage.isColorImage()); algoSepConvolver.run(); gaussianBuffer = algoSepConvolver.getOutputBuffer(); algoSepConvolver.finalize(); algoSepConvolver = null; gradientMagnitude(gaussianBuffer, gradientBuffer); upDateImage(resultBuffer, sourceBuffer, gradientBuffer); // copy resultBuffer to sourceBuffer for the next iteration if (iterNum < (numIterations - 1)) { for (int i = 0; i < length; i++) { sourceBuffer[i] = resultBuffer[i]; } } } // end for (int iterNum = 0; ...) // OK, the resultBuffer is filled with the results of the algorithm, // put this data into the destination image so it will be displayed in // in the ViewJFrameWizard try { destImage.importData(startIndex, resultBuffer, true); } catch (IOException error) { sourceBuffer = resultBuffer = gaussianBuffer = gradientBuffer = null; errorCleanUp("AlgorithmRegularizedIsotropicDiffusion: Could NOT import resultBuffer to the image", true); return; } // end try{}-catch{} } // end for (imgNumber = 0; ...) fireProgressStateChanged(100); if (threadStopped) { finalize(); return; } setCompleted(true); } // end run2D /** * Iterates the Regularized Isotropic Nonlinear Diffusion algorithm for 2D and 2.5D color images. * * @param numImages int number of slices to be blurred. If 2D image then nImage = 1, if 3D image where each slice * is to processed independently then nImages equals the number of slices in the volume. */ private void run2DC(int numImages) { fireProgressStateChanged(0, srcImage.getImageName(), "Regularized Isotropic Diffusion ..."); // OK, here is where the meat of the algorithm goes int length; int i; int[] extents = new int[2]; extents[0] = srcImage.getExtents()[0]; extents[1] = srcImage.getExtents()[1]; xDim = extents[0]; yDim = extents[1]; length = xDim * yDim; // buffers for the image data float[] sourceBufferR = null; float[] sourceBufferG = null; float[] sourceBufferB = null; float[] resultBufferR = null; float[] resultBufferG = null; float[] resultBufferB = null; float[] gaussianBufferR = null; float[] gaussianBufferG = null; float[] gaussianBufferB = null; float[] gradientBuffer; float[] gradientBufferR = null; float[] gradientBufferG = null; float[] gradientBufferB = null; boolean useRed = true; boolean useGreen = true; boolean useBlue = true; int colorsPresent = 3; srcImage.calcMinMax(); if (srcImage.getMinR() == srcImage.getMaxR()) { useRed = false; colorsPresent--; } if (srcImage.getMinG() == srcImage.getMaxG()) { useGreen = false; colorsPresent--; } if (srcImage.getMinB() == srcImage.getMaxB()) { useBlue = false; colorsPresent--; } // copy the image data into the sourceBuffer so we can access it try { if (useRed) { sourceBufferR = new float[length]; resultBufferR = new float[length]; gaussianBufferR = new float[length]; gradientBufferR = new float[length]; } if (useGreen) { sourceBufferG = new float[length]; resultBufferG = new float[length]; gaussianBufferG = new float[length]; gradientBufferG = new float[length]; } if (useBlue) { sourceBufferB = new float[length]; resultBufferB = new float[length]; gaussianBufferB = new float[length]; gradientBufferB = new float[length]; } gradientBuffer = new float[length]; for (i = 0; i < length; i++) { gradientBuffer[i] = 0.0f; } } catch (OutOfMemoryError e) { sourceBufferR = sourceBufferG = sourceBufferB = null; resultBufferR = resultBufferG = resultBufferB = null; gaussianBufferR = gaussianBufferG = gaussianBufferB = null; gradientBuffer = gradientBufferR = gradientBufferG = gradientBufferB = null; errorCleanUp("AlgorithmRegularizedIsotropicDiffusion: Out of memory when creating image buffer", true); return; } // catch{} // Gaussian blur the input image as a 2.5D image set sigmas = new float[2]; sigmas[0] = sigmas[1] = stdDev; makeKernels1D(false); // source image is in sourceBuffer, gaussian smoothed image is in gaussianBuffer int startIndex; float stepProgressValue = ((float)100)/(numImages * numIterations); for (int imgNumber = 0; imgNumber < numImages; imgNumber++) { startIndex = 4 * imgNumber * length; try { if (useRed) { srcImage.exportRGBData(1, startIndex, length, sourceBufferR); } if (useGreen) { srcImage.exportRGBData(2, startIndex, length, sourceBufferG); } if (useBlue) { srcImage.exportRGBData(3, startIndex, length, sourceBufferB); } } catch (IOException error) { sourceBufferR = sourceBufferG = sourceBufferB = null; resultBufferR = resultBufferG = resultBufferB = null; gaussianBufferR = gaussianBufferG = gaussianBufferB = null; gradientBuffer = gradientBufferR = gradientBufferG = gradientBufferB = null; errorCleanUp("AlgorithmRegularizedIsotropicDiffusion: could NOT export source image", true); return; } // catch() for (int iterNum = 0; iterNum < numIterations; iterNum++) { fireProgressStateChanged(Math.round(stepProgressValue * iterNum)); if (useRed) { // make the magnitude of the gradient image of the gaussian smoothed source image // A separate constructor AlgorithmSeparableConvolver call is needed for each iteration // because the constructor has the line // MipavUtil.arrayCopy(srcBuffer, 0, inputBuffer, 0, srcBuffer.length); // so having the constructor before the iteration loop would result in // using the initial srcBuffer for each iteration. algoSepConvolverR = new AlgorithmSeparableConvolver(sourceBufferR, extents, new float[][]{xDataRound, yDataRound}, false); algoSepConvolverR.run(); gaussianBufferR = algoSepConvolverR.getOutputBuffer(); algoSepConvolverR.finalize(); algoSepConvolverR = null; gradientMagnitude(gaussianBufferR, gradientBufferR); for (i = 0; i < length; i++) { gradientBuffer[i] = gradientBufferR[i]; } } if (useGreen) { algoSepConvolverG = new AlgorithmSeparableConvolver(sourceBufferG, extents, new float[][]{xDataRound, yDataRound}, false); algoSepConvolverG.run(); gaussianBufferG = algoSepConvolverG.getOutputBuffer(); algoSepConvolverG.finalize(); algoSepConvolverG = null; gradientMagnitude(gaussianBufferG, gradientBufferG); for (i = 0; i < length; i++) { gradientBuffer[i] += gradientBufferG[i]; } } if (useBlue) { algoSepConvolverB = new AlgorithmSeparableConvolver(sourceBufferB, extents, new float[][]{xDataRound, yDataRound}, false); algoSepConvolverB.run(); gaussianBufferB = algoSepConvolverB.getOutputBuffer(); algoSepConvolverB.finalize(); algoSepConvolverB = null; gradientMagnitude(gaussianBufferB, gradientBufferB); for (i = 0; i < length; i++) { gradientBuffer[i] += gradientBufferB[i]; } } for (i = 0; i < length; i++) { gradientBuffer[i] /= colorsPresent; } if (useRed) { upDateImage(resultBufferR, sourceBufferR, gradientBuffer); } if (useGreen) { upDateImage(resultBufferG, sourceBufferG, gradientBuffer); } if (useBlue) { upDateImage(resultBufferB, sourceBufferB, gradientBuffer); } // copy resultBuffer to sourceBuffer for the next iteration if (iterNum < (numIterations - 1)) { if (useRed) { for (i = 0; i < length; i++) { sourceBufferR[i] = resultBufferR[i]; } } // if (useRed) if (useGreen) { for (i = 0; i < length; i++) { sourceBufferG[i] = resultBufferG[i]; } } // if (useGreen) if (useBlue) { for (i = 0; i < length; i++) { sourceBufferB[i] = resultBufferB[i]; } } // if (useBlue) } // if (iterNum < (numIterations - 1)) } // end for (int iterNum = 0; ...) // OK, the resultBuffer is filled with the results of the algorithm, // put this data into the destination image so it will be displayed in // in the ViewJFrameWizard try { if (useRed) { for (i = 0; i < length; i++) { if ((resultBufferR[i] > 255.0f) && (destImage.getType() == ModelStorageBase.ARGB)) { resultBufferR[i] = 255.0f; } else if (resultBufferR[i] < 0.0f) { resultBufferR[i] = 0.0f; } } destImage.importRGBData(1, startIndex, resultBufferR, false); } if (useGreen) { for (i = 0; i < length; i++) { if ((resultBufferG[i] > 255.0f) && (destImage.getType() == ModelStorageBase.ARGB)) { resultBufferG[i] = 255.0f; } else if (resultBufferG[i] < 0.0f) { resultBufferG[i] = 0.0f; } } destImage.importRGBData(2, startIndex, resultBufferG, false); } if (useBlue) { for (i = 0; i < length; i++) { if ((resultBufferB[i] > 255.0f) && (destImage.getType() == ModelStorageBase.ARGB)) { resultBufferB[i] = 255.0f; } else if (resultBufferB[i] < 0.0f) { resultBufferB[i] = 0.0f; } } destImage.importRGBData(3, startIndex, resultBufferB, false); } } catch (IOException error) { sourceBufferR = sourceBufferG = sourceBufferB = null; resultBufferR = resultBufferG = resultBufferB = null; gaussianBufferR = gaussianBufferG = gaussianBufferB = null; gradientBuffer = gradientBufferR = gradientBufferG = gradientBufferB = null; errorCleanUp("AlgorithmRegularizedIsotropicDiffusion: Could NOT import resultBuffer to the image", true); return; } // end try{}-catch{} } // end for (imgNumber = 0; ...) fireProgressStateChanged(100); destImage.calcMinMax(); if (threadStopped) { finalize(); return; } setCompleted(true); } // end run2DC /** * Iterates the Regularized Isotropic Nonlinear Diffusion algorithm for 3D images. */ private void run3D() { fireProgressStateChanged(0, srcImage.getImageName(), "Regularized Isotropic Diffusion ..."); // OK, here is where the meat of the algorithm goes int length; int[] extents = srcImage.getExtents(); xDim = extents[0]; yDim = extents[1]; zDim = extents[2]; length = xDim * yDim * zDim; // buffers for the image data float[] sourceBuffer; float[] resultBuffer; float[] gaussianBuffer; float[] gradientBuffer; // copy the image data into the sourceBuffer so we can access it try { sourceBuffer = new float[length]; resultBuffer = new float[length]; gaussianBuffer = new float[length]; gradientBuffer = new float[length]; } catch (OutOfMemoryError e) { sourceBuffer = resultBuffer = gaussianBuffer = gradientBuffer = null; errorCleanUp("AlgorithmRegularizedIsotropicDiffusion: Out of memory when creating image buffer", true); return; } // catch{} // Gaussian blur the input image as a 3D image sigmas = new float[3]; sigmas[0] = sigmas[1] = sigmas[2] = stdDev; makeKernels1D(true); // source image is in sourceBuffer, gaussian smoothed image is in gaussianBuffer try { srcImage.exportData(0, length, sourceBuffer); } catch (IOException error) { sourceBuffer = resultBuffer = gaussianBuffer = gradientBuffer = null; errorCleanUp("AlgorithmRegularizedIsotropicDiffusion: could NOT export source image", true); return; } // catch() float stepProgressValue = ((float)100)/numIterations; for (int iterNum = 0; iterNum < numIterations; iterNum++) { // make the magnitude of the gradient image of the gaussian smoothed // source image // A separate constructor AlgorithmSeparableConvolver call is needed for each iteration // because the constructor has the line // MipavUtil.arrayCopy(srcBuffer, 0, inputBuffer, 0, srcBuffer.length); // so having the constructor before the iteration loop would result in // using the initial srcBuffer for each iteration. algoSepConvolver = new AlgorithmSeparableConvolver(sourceBuffer, extents, new float[][]{xDataRound, yDataRound, zDataRound}, srcImage.isColorImage()); linkProgressToAlgorithm(algoSepConvolver); algoSepConvolver.setProgressValues(generateProgressValues(getMinProgressValue() + Math.round(stepProgressValue * iterNum), getMinProgressValue() + Math.round(stepProgressValue * (iterNum+1)))); algoSepConvolver.run(); gaussianBuffer = algoSepConvolver.getOutputBuffer(); algoSepConvolver.finalize(); algoSepConvolver = null; gradientMagnitude3D(gaussianBuffer, gradientBuffer); upDateImage3D(resultBuffer, sourceBuffer, gradientBuffer); // copy resultBuffer to sourceBuffer for the next iteration if (iterNum < (numIterations - 1)) { for (int i = 0; i < length; i++) { sourceBuffer[i] = resultBuffer[i]; } } } // end for (int iterNum = 0; ...) fireProgressStateChanged(100); // OK, the resultBuffer is filled with the results of the algorithm, // put this data into the destination image so it will be displayed in // in the ViewJFrameWizard try { destImage.importData(0, resultBuffer, true); } catch (IOException error) { sourceBuffer = resultBuffer = gaussianBuffer = gradientBuffer = null; errorCleanUp("AlgorithmRegularizedIsotropicDiffusion: Could NOT import resultBuffer to the image", true); return; } // end try{}-catch{} if (threadStopped) { finalize(); return; } setCompleted(true); } // end run3D /** * Iterates the Regularized Isotropic Nonlinear Diffusion algorithm for 3D color images. */ private void run3DC() { fireProgressStateChanged(0, srcImage.getImageName(), "Regularized Isotropic Diffusion ..."); // OK, here is where the meat of the algorithm goes int length; int i; int[] extents = srcImage.getExtents(); xDim = extents[0]; yDim = extents[1]; zDim = extents[2]; length = xDim * yDim * zDim; // buffers for the image data float[] sourceBufferR = null; float[] sourceBufferG = null; float[] sourceBufferB = null; float[] resultBufferR = null; float[] resultBufferG = null; float[] resultBufferB = null; float[] gaussianBufferR = null; float[] gaussianBufferG = null; float[] gaussianBufferB = null; float[] gradientBuffer; float[] gradientBufferR = null; float[] gradientBufferG = null; float[] gradientBufferB = null; boolean useRed = true; boolean useGreen = true; boolean useBlue = true; int colorsPresent = 3; srcImage.calcMinMax(); if (srcImage.getMinR() == srcImage.getMaxR()) { useRed = false; colorsPresent--; } if (srcImage.getMinG() == srcImage.getMaxG()) { useGreen = false; colorsPresent--; } if (srcImage.getMinB() == srcImage.getMaxB()) { useBlue = false; colorsPresent--; } // copy the image data into the sourceBuffer so we can access it try { if (useRed) { sourceBufferR = new float[length]; resultBufferR = new float[length]; gaussianBufferR = new float[length]; gradientBufferR = new float[length]; } if (useGreen) { sourceBufferG = new float[length]; resultBufferG = new float[length]; gaussianBufferG = new float[length]; gradientBufferG = new float[length]; } if (useBlue) { sourceBufferB = new float[length]; resultBufferB = new float[length]; gaussianBufferB = new float[length]; gradientBufferB = new float[length]; } gradientBuffer = new float[length]; for (i = 0; i < length; i++) { gradientBuffer[i] = 0.0f; } } catch (OutOfMemoryError e) { sourceBufferR = sourceBufferG = sourceBufferB = null; resultBufferR = resultBufferG = resultBufferB = null; gaussianBufferR = gaussianBufferG = gaussianBufferB = null; gradientBuffer = gradientBufferR = gradientBufferG = gradientBufferB = null; errorCleanUp("AlgorithmRegularizedIsotropicDiffusion: Out of memory when creating image buffer", true); return; } // catch{} // Gaussian blur the input image as a 3D image sigmas = new float[3]; sigmas[0] = sigmas[1] = sigmas[2] = stdDev; makeKernels1D(true); // source image is in sourceBuffer, gaussian smoothed image is in gaussianBuffer try { if (useRed) { srcImage.exportRGBData(1, 0, length, sourceBufferR); } if (useGreen) { srcImage.exportRGBData(2, 0, length, sourceBufferG); } if (useBlue) { srcImage.exportRGBData(3, 0, length, sourceBufferB); } } catch (IOException error) { sourceBufferR = sourceBufferG = sourceBufferB = null; resultBufferR = resultBufferG = resultBufferB = null; gaussianBufferR = gaussianBufferG = gaussianBufferB = null; gradientBuffer = gradientBufferR = gradientBufferG = gradientBufferB = null; errorCleanUp("AlgorithmRegularizedIsotropicDiffusion: could NOT export source image", true); return; } // catch() float stepProgressValue = ((float)100)/numIterations; for (int iterNum = 0; iterNum < numIterations; iterNum++) { fireProgressStateChanged(Math.round(stepProgressValue * iterNum)); if (useRed) { // make the magnitude of the gradient image of the gaussian smoothed source image // A separate constructor AlgorithmSeparableConvolver call is needed for each iteration // because the constructor has the line // MipavUtil.arrayCopy(srcBuffer, 0, inputBuffer, 0, srcBuffer.length); // so having the constructor before the iteration loop would result in // using the initial srcBuffer for each iteration. algoSepConvolverR = new AlgorithmSeparableConvolver(sourceBufferR, extents, new float[][]{xDataRound, yDataRound, zDataRound}, false); algoSepConvolverR.run(); gaussianBufferR = algoSepConvolverR.getOutputBuffer(); algoSepConvolverR.finalize(); algoSepConvolverR = null; gradientMagnitude3D(gaussianBufferR, gradientBufferR); for (i = 0; i < length; i++) { gradientBuffer[i] = gradientBufferR[i]; } } if (useGreen) { algoSepConvolverG = new AlgorithmSeparableConvolver(sourceBufferG, extents, new float[][]{xDataRound, yDataRound, zDataRound}, false); algoSepConvolverG.run(); gaussianBufferG = algoSepConvolverG.getOutputBuffer(); algoSepConvolverG.finalize(); algoSepConvolverG = null; gradientMagnitude3D(gaussianBufferG, gradientBufferG); for (i = 0; i < length; i++) { gradientBuffer[i] += gradientBufferG[i]; } } if (useBlue) { algoSepConvolverB = new AlgorithmSeparableConvolver(sourceBufferB, extents, new float[][]{xDataRound, yDataRound, zDataRound}, false); algoSepConvolverB.run(); gaussianBufferB = algoSepConvolverB.getOutputBuffer(); algoSepConvolverB.finalize(); algoSepConvolverB = null; gradientMagnitude3D(gaussianBufferB, gradientBufferB); for (i = 0; i < length; i++) { gradientBuffer[i] += gradientBufferB[i]; } } for (i = 0; i < length; i++) { gradientBuffer[i] /= colorsPresent; } if (useRed) { upDateImage3D(resultBufferR, sourceBufferR, gradientBuffer); } if (useGreen) { upDateImage3D(resultBufferG, sourceBufferG, gradientBuffer); } if (useBlue) { upDateImage3D(resultBufferB, sourceBufferB, gradientBuffer); } // copy resultBuffer to sourceBuffer for the next iteration if (iterNum < (numIterations - 1)) { if (useRed) { for (i = 0; i < length; i++) { sourceBufferR[i] = resultBufferR[i]; } } // if (useRed) if (useGreen) { for (i = 0; i < length; i++) { sourceBufferG[i] = resultBufferG[i]; } } // if (useGreen) if (useBlue) { for (i = 0; i < length; i++) { sourceBufferB[i] = resultBufferB[i]; } } // if (useBlue) } // if (iterNum < (numIterations - 1)) } // end for (int iterNum = 0; ...) fireProgressStateChanged(100); // OK, the resultBuffer is filled with the results of the algorithm, // put this data into the destination image so it will be displayed in // in the ViewJFrameWizard try { if (useRed) { for (i = 0; i < length; i++) { if ((resultBufferR[i] > 255.0f) && (destImage.getType() == ModelStorageBase.ARGB)) { resultBufferR[i] = 255.0f; } else if (resultBufferR[i] < 0.0f) { resultBufferR[i] = 0.0f; } } destImage.importRGBData(1, 0, resultBufferR, false); } if (useGreen) { for (i = 0; i < length; i++) { if ((resultBufferG[i] > 255.0f) && (destImage.getType() == ModelStorageBase.ARGB)) { resultBufferG[i] = 255.0f; } else if (resultBufferG[i] < 0.0f) { resultBufferG[i] = 0.0f; } } destImage.importRGBData(2, 0, resultBufferG, false); } if (useBlue) { for (i = 0; i < length; i++) { if ((resultBufferB[i] > 255.0f) && (destImage.getType() == ModelStorageBase.ARGB)) { resultBufferB[i] = 255.0f; } else if (resultBufferB[i] < 0.0f) { resultBufferB[i] = 0.0f; } } destImage.importRGBData(3, 0, resultBufferB, false); } } catch (IOException error) { sourceBufferR = sourceBufferG = sourceBufferB = null; resultBufferR = resultBufferG = resultBufferB = null; gaussianBufferR = gaussianBufferG = gaussianBufferB = null; gradientBuffer = gradientBufferR = gradientBufferG = gradientBufferB = null; errorCleanUp("AlgorithmRegularizedIsotropicDiffusion: Could NOT import resultBuffer to the image", true); return; } // end try{}-catch{} destImage.calcMinMax(); if (threadStopped) { finalize(); return; } setCompleted(true); } // end run3DC /** * DOCUMENT ME! * * @param resltBuffer float [] The preallocated result buffer * @param srcBuffer float [] The initialized source buffer containing the input image * @param gradBuffer float [] The initialized buffer containing the magnitude of the gradient of the Gaussian * blurred input image */ private void upDateImage(float[] resltBuffer, float[] srcBuffer, float[] gradBuffer) { int row, col, cIndex; float leftGradVal, rightGradVal, topGradVal, bottomGradVal, centerGradVal; float leftImgVal, rightImgVal, topImgVal, bottomImgVal, centerImgVal; float leftDiffVal, rightDiffVal, topDiffVal, bottomDiffVal, centerDiffVal; float maxGrad = gradBuffer[0]; int length = yDim * xDim; for (int idx = 1; idx < length; idx++) { if (gradBuffer[idx] > maxGrad) { maxGrad = gradBuffer[idx]; } } // for (int idx = 1; ...) lambda = contrast * maxGrad; for (row = 0; row < yDim; row++) { cIndex = row * xDim; for (col = 0, cIndex += col; col < xDim; cIndex++, col++) { centerGradVal = gradBuffer[cIndex]; centerDiffVal = diffusivity(centerGradVal); rightGradVal = getVal(gradBuffer, col + 1, row); rightDiffVal = diffusivity(rightGradVal); leftGradVal = getVal(gradBuffer, col - 1, row); leftDiffVal = diffusivity(leftGradVal); bottomGradVal = getVal(gradBuffer, col, row + 1); bottomDiffVal = diffusivity(bottomGradVal); topGradVal = getVal(gradBuffer, col, row - 1); topDiffVal = diffusivity(topGradVal); centerImgVal = srcBuffer[cIndex]; leftImgVal = getVal(srcBuffer, col - 1, row); rightImgVal = getVal(srcBuffer, col + 1, row); bottomImgVal = getVal(srcBuffer, col, row + 1); topImgVal = getVal(srcBuffer, col, row - 1); resltBuffer[cIndex] = centerImgVal + (0.5f * timeStep * ((topImgVal * (topDiffVal + centerDiffVal)) + (leftImgVal * (leftDiffVal + centerDiffVal)) - (centerImgVal * (leftDiffVal + rightDiffVal + bottomDiffVal + topDiffVal + (4.0f * centerDiffVal))) + (rightImgVal * (centerDiffVal + rightDiffVal)) + (bottomImgVal * (centerDiffVal + bottomDiffVal)))); } // end for (col = 0; ...) } // end for (row = 0; ...) } // end upDateImage(...) /** * DOCUMENT ME! * * @param resltBuffer float [] The preallocated result buffer * @param srcBuffer float [] The initialized source buffer containing the input image * @param gradBuffer float [] The initialized buffer containing the magnitude of the gradient of the Gaussian * blurred input image */ private void upDateImage3D(float[] resltBuffer, float[] srcBuffer, float[] gradBuffer) { int slice, row, col, sIndex, cIndex; float leftGradVal, rightGradVal, topGradVal, bottomGradVal, centerGradVal; float zLowGradVal, zHighGradVal; float leftImgVal, rightImgVal, topImgVal, bottomImgVal, centerImgVal; float zLowImgVal, zHighImgVal; float leftDiffVal, rightDiffVal, topDiffVal, bottomDiffVal, centerDiffVal; float zLowDiffVal, zHighDiffVal; float maxGrad = gradBuffer[0]; int sliceSize = yDim * xDim; int length = zDim * sliceSize; for (int idx = 1; idx < length; idx++) { if (gradBuffer[idx] > maxGrad) { maxGrad = gradBuffer[idx]; } } // for (int idx = 1; ...) lambda = contrast * maxGrad; for (slice = 0; slice < zDim; slice++) { sIndex = slice * sliceSize; for (row = 0; row < yDim; row++) { cIndex = sIndex + (row * xDim); for (col = 0, cIndex += col; col < xDim; cIndex++, col++) { centerGradVal = gradBuffer[cIndex]; centerDiffVal = diffusivity(centerGradVal); rightGradVal = getVal(gradBuffer, col + 1, row, slice); rightDiffVal = diffusivity(rightGradVal); leftGradVal = getVal(gradBuffer, col - 1, row, slice); leftDiffVal = diffusivity(leftGradVal); bottomGradVal = getVal(gradBuffer, col, row + 1, slice); bottomDiffVal = diffusivity(bottomGradVal); topGradVal = getVal(gradBuffer, col, row - 1, slice); topDiffVal = diffusivity(topGradVal); zLowGradVal = getVal(gradBuffer, col, row, slice - 1); zLowDiffVal = diffusivity(zLowGradVal); zHighGradVal = getVal(gradBuffer, col, row, slice + 1); zHighDiffVal = diffusivity(zHighGradVal); centerImgVal = srcBuffer[cIndex]; leftImgVal = getVal(srcBuffer, col - 1, row, slice); rightImgVal = getVal(srcBuffer, col + 1, row, slice); bottomImgVal = getVal(srcBuffer, col, row + 1, slice); topImgVal = getVal(srcBuffer, col, row - 1, slice); zLowImgVal = getVal(srcBuffer, col, row, slice - 1); zHighImgVal = getVal(srcBuffer, col, row, slice + 1); resltBuffer[cIndex] = centerImgVal + (0.5f * timeStep * ((topImgVal * (topDiffVal + centerDiffVal)) + (leftImgVal * (leftDiffVal + centerDiffVal)) - (centerImgVal * (leftDiffVal + rightDiffVal + bottomDiffVal + topDiffVal + zLowDiffVal + zHighDiffVal + (6.0f * centerDiffVal))) + (rightImgVal * (centerDiffVal + rightDiffVal)) + (bottomImgVal * (centerDiffVal + bottomDiffVal)) + (zLowImgVal * (centerDiffVal + zLowDiffVal)) + (zHighImgVal * (centerDiffVal + zHighDiffVal)))); } // end for (col = 0; ...) } // end for (row = 0; ...) } // for (slice = 0; ...) } // end upDateImage3D(...) } // end class AlgorithmRegularizedIsotropicDiffusion
package com.doc.spring.custom; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Set; import org.springframework.format.AnnotationFormatterFactory; import org.springframework.format.Parser; import org.springframework.format.Printer; public class CustomDataTimeFormatterAnnotationFactory implements AnnotationFormatterFactory<CustomDataTime>{ public Set<Class<?>> getFieldTypes() { Set<Class<?>> fieldTypes = new HashSet<Class<?>>(4); fieldTypes.add(Date.class); return Collections.unmodifiableSet(fieldTypes); } public Printer<?> getPrinter(CustomDataTime annotation, Class<?> fieldType) { CustomDatatimeformater formater = new CustomDatatimeformater(annotation.pattern()); return formater; } public Parser<?> getParser(CustomDataTime annotation, Class<?> fieldType) { CustomDatatimeformater formater = new CustomDatatimeformater(annotation.pattern()); return formater; } }
package io.github.satr.aws.lambda.bookstore.services; // Copyright © 2020, github.com/satr, MIT License import io.github.satr.aws.lambda.bookstore.entity.Basket; public interface BookOrderService { Basket getBasket(); }
package com.itheima.advice; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; @Component @Aspect public class MyAdvice { //抽取切面表达式 @Pointcut("execution(* com.itheima.dao.*impl.*.add*(..))") public void pointCut() {} @Before("pointCut()") public void Before() { System.out.println("前置增强..."); } @AfterReturning("pointCut()") public void afterReturning() { System.out.println("后置增强..."); } @AfterThrowing("pointCut()") public void afterThrowing() { System.out.println("异常抛出后增强..."); } @After("pointCut()") public void after() { System.out.println("最终增强..."); } // @Around("pointCut()") public Object surround(ProceedingJoinPoint proceedingJoinPoint) { Object proceed = null; try { System.out.println("环绕前通知"); proceed = proceedingJoinPoint.proceed(); System.out.println("环绕后通知"); } catch (Throwable throwable) { throwable.printStackTrace(); System.out.println("异常抛出通知"); } finally { System.out.println("最终通知"); } return proceed; } }
/* * (C) Copyright IBM Corp. 2020. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.ibm.cloud.cloudant.v1.model; import com.ibm.cloud.cloudant.v1.model.Attachment; import com.ibm.cloud.cloudant.v1.utils.TestUtilities; import com.ibm.cloud.sdk.core.service.model.FileWithMetadata; import java.io.InputStream; import java.util.HashMap; import java.util.List; import org.testng.annotations.Test; import static org.testng.Assert.*; /** * Unit test class for the Attachment model. */ public class AttachmentTest { final HashMap<String, InputStream> mockStreamMap = TestUtilities.createMockStreamMap(); final List<FileWithMetadata> mockListFileWithMetadata = TestUtilities.creatMockListFileWithMetadata(); @Test public void testAttachment() throws Throwable { Attachment attachmentModel = new Attachment.Builder() .contentType("testString") .data(TestUtilities.createMockByteArray("This is a mock byte array value.")) .digest("testString") .encodedLength(Long.valueOf("0")) .encoding("testString") .follows(true) .length(Long.valueOf("0")) .revpos(Long.valueOf("1")) .stub(true) .build(); assertEquals(attachmentModel.contentType(), "testString"); assertEquals(attachmentModel.data(), TestUtilities.createMockByteArray("This is a mock byte array value.")); assertEquals(attachmentModel.digest(), "testString"); assertEquals(attachmentModel.encodedLength(), Long.valueOf("0")); assertEquals(attachmentModel.encoding(), "testString"); assertEquals(attachmentModel.follows(), Boolean.valueOf(true)); assertEquals(attachmentModel.length(), Long.valueOf("0")); assertEquals(attachmentModel.revpos(), Long.valueOf("1")); assertEquals(attachmentModel.stub(), Boolean.valueOf(true)); String json = TestUtilities.serialize(attachmentModel); Attachment attachmentModelNew = TestUtilities.deserialize(json, Attachment.class); assertTrue(attachmentModelNew instanceof Attachment); assertEquals(attachmentModelNew.contentType(), "testString"); assertEquals(attachmentModelNew.data(), TestUtilities.createMockByteArray("This is a mock byte array value.")); assertEquals(attachmentModelNew.digest(), "testString"); assertEquals(attachmentModelNew.encodedLength(), Long.valueOf("0")); assertEquals(attachmentModelNew.encoding(), "testString"); assertEquals(attachmentModelNew.follows(), Boolean.valueOf(true)); assertEquals(attachmentModelNew.length(), Long.valueOf("0")); assertEquals(attachmentModelNew.revpos(), Long.valueOf("1")); assertEquals(attachmentModelNew.stub(), Boolean.valueOf(true)); } }
package com.vaadin.vaadin_archetype_application; import com.google.api.client.util.DateTime; public class TimeSlot { public long id; public DateTime startTime, endTime; public TimeSlotVote[] votes; }
package com.redrocket.photoeditor.screens.presentation.gallery.view; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.media.ExifInterface; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.bumptech.glide.BitmapRequestBuilder; import com.bumptech.glide.Glide; import com.bumptech.glide.Priority; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool; import com.bumptech.glide.load.resource.bitmap.BitmapTransformation; import com.bumptech.glide.load.resource.bitmap.CenterCrop; import com.redrocket.photoeditor.R; import com.redrocket.photoeditor.screens.presentation.gallery.structures.PreviewDescriptor; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @TODO Class Description ... */ public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.PreviewHolder> { private static final String TAG = "GalleryAdapter"; private static final int PRELOAD_COUNT = 9; private final Context mContext; private List<PreviewDescriptor> mItems = new ArrayList<>(); private Map<String,Integer> mThumbPathToRotation = new HashMap<>(); GalleryAdapter(Context context) { mContext = context; } void setItems(final List<PreviewDescriptor> items) { mItems = items; for (PreviewDescriptor item : items) { if (item.thumbPath == null) continue; final int imageRotation = getRotation(item.imagePath); final int thumbRotation = getRotation(item.thumbPath); final int previewRotation = imageRotation - thumbRotation; mThumbPathToRotation.put(item.thumbPath,previewRotation); } notifyDataSetChanged(); } @Override public PreviewHolder onCreateViewHolder(ViewGroup parent, int viewType) { final View itemView = LayoutInflater.from(mContext). inflate(R.layout.gallery_item_preview, parent, false); return new PreviewHolder(itemView); } @Override public void onBindViewHolder(PreviewHolder holder, int position) { createRequest(position) .placeholder(R.color.steelGray) .priority(Priority.HIGH) .into(holder.preview); // final int preloadPos = position + PRELOAD_COUNT; // if (preloadPos >= 0 && preloadPos < mItems.size() // && holder.preview.getWidth() > 0 // && holder.preview.getHeight() > 0) { // createRequest(preloadPos) // .priority(Priority.LOW) // .preload(holder.preview.getWidth(), holder.preview.getHeight()); // } } private BitmapRequestBuilder<String, Bitmap> createRequest(final int position) { final String previewPath = mItems.get(position).thumbPath != null ? mItems.get(position).thumbPath : mItems.get(position).imagePath; BitmapRequestBuilder<String,Bitmap> builder = Glide .with(mContext) .load(previewPath) .asBitmap() .diskCacheStrategy(DiskCacheStrategy.RESULT); final List<BitmapTransformation> transforms = new ArrayList<>(); transforms.add(new CenterCrop(mContext)); if (mThumbPathToRotation.containsKey(previewPath)) { final int diffRotation = mThumbPathToRotation.get(previewPath); transforms.add(new BitmapTransformation(mContext) { @Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { final Matrix matrix = new Matrix(); matrix.postRotate(diffRotation); final Bitmap rotateBitmap = Bitmap.createBitmap(toTransform, 0, 0, toTransform.getWidth(), toTransform.getHeight(), matrix, true); return rotateBitmap; } @Override public String getId() { return "rotation"; } }); } builder = builder .transform(transforms.toArray(new BitmapTransformation[transforms.size()])) .crossFade(); return builder; } @Override public int getItemCount() { return mItems.size(); } private void handlePreviewClick(final int pos){ Log.i(TAG, "handlePreviewClick: "+pos); } class PreviewHolder extends RecyclerView.ViewHolder { private ImageView preview; public PreviewHolder(View itemView) { super(itemView); itemView.findViewById(R.id.button_preview).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { handlePreviewClick(getAdapterPosition()); } }); preview = (ImageView) itemView.findViewById(R.id.image_preview); } } private static int getRotation(final String path) { final ExifInterface exif; try { exif = new ExifInterface(path); } catch (IOException e) { e.printStackTrace(); return 0; } final int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED); switch (orientation) { case ExifInterface.ORIENTATION_NORMAL: return 0; case ExifInterface.ORIENTATION_ROTATE_90: return 90; case ExifInterface.ORIENTATION_ROTATE_180: return 180; case ExifInterface.ORIENTATION_ROTATE_270: return 270; default: return 0; } } }
package com.tpg.brks.ms.expenses.service; import com.tpg.brks.ms.expenses.domain.Account; import com.tpg.brks.ms.expenses.domain.AccountFixture; public interface DomainGiven extends AccountFixture { default Account givenAnAccount() { return johnDoeAccount(); } }
package com.cs.promotion; import com.cs.player.Player; import com.cs.user.User; import org.springframework.data.domain.Page; import java.util.Date; import java.util.List; import java.util.Map; /** * @author Hadi Movaghar */ public interface PromotionService { Promotion createPromotion(final Promotion promotion, final Long levelId, final User user); Promotion updatePromotion(final Promotion promotion, final User user); Map<PlayerPromotion, Promotion> getPlayerPromotions(final Long playerId); PlayerPromotion grantPromotionManually(final Player player, final Long promotionId); List<PlayerPromotion> assignPromotions(final Player player, final PromotionTrigger promotionTrigger, final PlayerCriteria playerCriteria); Page<Promotion> getPromotions(final User user, final Date startDate, final Date endDate, final String name, final PromotionTrigger promotionTrigger, final Integer page, final Integer size); Promotion getPromotionDetails(Long promotionId); }
package com.pengo.order.service; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.pengo.common.entity.Order; import com.pengo.order.mapper.OrderMapper; import org.springframework.stereotype.Service; @Service public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService { }
package exam; public class Address { private String streetName; private Integer zipCode; public Address(String streetName, Integer zipCode) { super(); this.streetName = streetName; this.zipCode = zipCode; } public String getStreetName() { return streetName; } public void setStreetName(String streetName) { this.streetName = streetName; } public Integer getZipCode() { return zipCode; } public void setZipCode(Integer zipCode) { this.zipCode = zipCode; } @Override public String toString() { return "Address [streetName=" + streetName + ", zipCode=" + zipCode + "]"; } }
/* * Copyright (c) 2015, Jirav All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.server.api.userimport; import pl.edu.icm.unity.server.authn.AuthenticationResult; /** * Internal API for triggering user import. * * @author Krzysztof Benedyczak */ public interface UserImportSerivce { /** * Perform user import. * @param identity * @param type * @return the returned object can be typically ignored, but is provided if caller is interested in * the results of import. The object's class is bit misnamed here, but it provides the complete information * which is the same as after remote authentication of a user. */ AuthenticationResult importUser(String identity, String type); }
package com.aiwac.service; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.UUID; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.omg.PortableInterceptor.ForwardRequestHelper; import com.aiwac.bean.request.WeChatJsTicket; import com.aiwac.bean.request.WeChatJsToken; import com.aiwac.constant.WeChatConstant; import com.aiwac.controller.WechatGetSignature; import com.aiwac.utils.JsonUtil; public class WeChatJsapiService { private static String jsapi_ticket; private static long last; private static final Logger logger = LogManager.getLogger(WeChatJsapiService.class); public static String getToken() { logger.info("fresh ticket"); String url ="https://api.weixin.qq.com/cgi-bin/token"; String para = "grant_type=client_credential&appid="+WeChatConstant.AppId+"&secret="+WeChatConstant.AppSecred+""; String result = HttpService.sendGet(url,para); WeChatJsToken access_token = (WeChatJsToken) JsonUtil.validateJsonStr(result, WeChatJsToken.class); String token = access_token.getAccess_token() ; //System.out.println(token); url ="https://api.weixin.qq.com/cgi-bin/ticket/getticket"; para = "access_token="+token+"&type=jsapi"; result = HttpService.sendGet(url,para); WeChatJsTicket access_ticket = (WeChatJsTicket) JsonUtil.validateJsonStr(result, WeChatJsTicket.class); String ticket = access_ticket.getTicket(); jsapi_ticket = ticket; logger.info("ticket:"+ticket); last = System.currentTimeMillis()/1000; return ticket; } public static String getSignature(String url,String noncestr,String timestamp) { if(jsapi_ticket==null || System.currentTimeMillis()/1000-last>7000) { getToken(); } String str = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url; //sha1加密 String signature = SHA1(str); return signature; } public static String SHA1(String str) { try { MessageDigest digest = java.security.MessageDigest .getInstance("SHA-1"); //如果是SHA加密只需要将"SHA-1"改成"SHA"即可 digest.update(str.getBytes()); byte messageDigest[] = digest.digest(); // Create Hex String StringBuffer hexStr = new StringBuffer(); // 字节数组转换为 十六进制 数 for (int i = 0; i < messageDigest.length; i++) { String shaHex = Integer.toHexString(messageDigest[i] & 0xFF); if (shaHex.length() < 2) { hexStr.append(0); } hexStr.append(shaHex); } return hexStr.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } }
package hash; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.GenericOptionsParser; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; public class HashCount extends Configured implements Tool{ static enum Counters { FaultyEntries }; public int run(String[] args) throws Exception { Job job = new Job(getConf()); Configuration conf = job.getConfiguration(); conf.set("mapreduce.child.java.opts", "-Xmx2048m"); job.setJarByClass(HashCount.class); ///job.setMapperClass(HashTagsSplitMapper.class); job.setMapperClass(TwitterDullMapper.class); job.setReducerClass(IntSumReducer.class); job.setCombinerClass(IntSumReducer.class); job.setNumReduceTasks(5); job.setInputFormatClass(SequenceFileInputFormat.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); Path outputPath = new Path(args[1]); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, outputPath); outputPath.getFileSystem(conf).delete(outputPath, true); job.waitForCompletion(true); return 1; } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); int res = ToolRunner.run(conf, new HashCount(), otherArgs); System.exit(res); } }
package hp.Seals.getErrorEventsApiVsDbTest; import com.google.common.base.Objects; public class EventTsPojo { private String cust_cd; private String evt_ocrd_ts; // public getter and setter Method public String getCust_cd() { return cust_cd; } public void setCust_cd(String cust_cd) { this.cust_cd = cust_cd; } public String getEvt_ocrd_ts() { return evt_ocrd_ts; } public void setEvt_ocrd_ts(String evt_ocrd_ts) { this.evt_ocrd_ts = evt_ocrd_ts; } @Override public boolean equals(Object ob) { boolean isEqual = false; if( this.cust_cd.equals(cust_cd) && this.evt_ocrd_ts.equals(evt_ocrd_ts) ) { isEqual = true; } return isEqual; } @Override public int hashCode() { return Objects.hashCode( "cust_cd" + "evt_ocrd_ts" ); } @Override public String toString() { return "[" + cust_cd + "," + evt_ocrd_ts +"]" ; } }
package string; import java.util.ArrayList; public class ValidIP { static boolean debug = true; public static void print2DList(ArrayList<ArrayList<String>> IP_List, boolean debug) { for (ArrayList<String> IP : IP_List) { if (debug == true) { System.out.println(IP.toString()); } } } public static ArrayList<ArrayList<String>> getAllIPsFromString(String str, int start, int end) { if (str.length() == 2) { ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>(2); ArrayList<String> tempList = new ArrayList<String>(2); String temp = "" + str.charAt(0); String temp2 = "" + str.charAt(1); tempList.add(temp); tempList.add(temp2); // Add [3,4] result.add(new ArrayList<String>(tempList)); // Add [34] tempList = new ArrayList<String>(); tempList.add(str); result.add(new ArrayList<String>(tempList)); return result; } String substr = str.substring(start + 1, end); ArrayList<ArrayList<String>> IPList = getAllIPsFromString(substr, start, substr.length()); String firstCharacter = "" + str.charAt(start); ArrayList<ArrayList<String>> ans = new ArrayList<ArrayList<String>>(2); // Add String in front of List for (ArrayList<String> IP : IPList) { ArrayList<String> temp = new ArrayList<String>(IP); temp.add(0, firstCharacter); ans.add(temp); } // At char to first element for (ArrayList<String> IP : IPList) { String address = IP.get(0); String concatenatedAddress = firstCharacter + address; IP.set(0, concatenatedAddress); ans.add(new ArrayList<String>(IP)); } return ans; } public static int digits(int num) { int digits = 0; if (num == 0) { return 1; } while (num > 0) { ++digits; num = num / 10; } return digits; } public static boolean isAddressValid(String address) { boolean isValid = true; if (address.length() < 4) { int add = Integer.parseInt(address); // Padded with zero are invalid if (address.length() > digits(add)) { isValid = false; } // Not in Range if (add < 0 || add > 255) { isValid = false; } } else { isValid = false; } return isValid; } public static ArrayList<ArrayList<String>> filterValidIPs(ArrayList<ArrayList<String>> allIPS) { ArrayList<ArrayList<String>> filteredIPs = new ArrayList<ArrayList<String>>(); for (ArrayList<String> IP : allIPS) { if (IP.size() == 4) { boolean isIPValid = true; for (String address : IP) { if (!isAddressValid(address)) { isIPValid = false; break; } } if (isIPValid) { filteredIPs.add(new ArrayList<String>(IP)); } } } return filteredIPs; } public static ArrayList<String> restoreIpAddresses(String str) { ArrayList<String> result = new ArrayList<String>(); int start = 0; int n = str.length(); if (n > 3 && n < 13) { ArrayList<ArrayList<String>> allIPS = getAllIPsFromString(str, start, n); ArrayList<ArrayList<String>> validIps = filterValidIPs(allIPS); result = formatIPAddress(validIps); } return result; } public static ArrayList<String> formatIPAddress(ArrayList<ArrayList<String>> IPS) { ArrayList<String> ipList = new ArrayList<String>(); for (ArrayList<String> IP : IPS) { String ipAddress = IP.get(0) + "." + IP.get(1) + "." + IP.get(2) + "." + IP.get(3); ipList.add(ipAddress); } return ipList; } public static void main(String args[]) { String str = "0002"; System.out.print(restoreIpAddresses(str)); } }
package tech.liujin.drawable.progress.text; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint.Style; import android.graphics.Rect; import android.graphics.RectF; import android.support.annotation.NonNull; /** * @author Liujin 2019/5/13:16:24:35 */ public class FillCircleProgressDrawable extends TextCenterProgressDrawable { private RectF mRectF; private float mStart; private float mEnd; public FillCircleProgressDrawable ( ) { mRectF = new RectF(); mPaint.setStyle( Style.FILL ); mPaint.setColor( Color.RED ); mTextPaint.setColor( Color.WHITE ); } @Override protected void onBoundsChange ( Rect bounds ) { int width = bounds.width(); int height = bounds.height(); int size = Math.min( width, height ); float rx = width * 1f / 2; float ry = height * 1f / 2; float radius = size * 1f / 2 - 2; mRectF.set( rx - radius, ry - radius, rx + radius, ry + radius ); super.onBoundsChange( bounds ); } @Override public void draw ( @NonNull Canvas canvas ) { canvas.drawArc( mRectF, mStart, mEnd - mStart, false, mPaint ); super.draw( canvas ); } @Override public void onProcessChange ( float progress ) { mProgress = progress; float v = 180 * mProgress; mStart = 90 - v; mEnd = 90 + v; invalidateSelf(); } }
/* * #%L * NettyReplyHandler.java - mongodb-async-netty - Allanbank Consulting, Inc. * %% * Copyright (C) 2014 - 2015 Allanbank Consulting, Inc. * %% * 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. * #L% */ package com.allanbank.mongodb.netty; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import com.allanbank.mongodb.client.Message; import com.allanbank.mongodb.client.transport.TransportResponseListener; import com.allanbank.mongodb.client.transport.bio.MessageInputBuffer; import com.allanbank.mongodb.util.log.Log; import com.allanbank.mongodb.util.log.LogFactory; /** * NettyReplyHandler provides a class to handle replies in the Netty pipeline. * * @copyright 2015, Allanbank Consulting, Inc., All Rights Reserved */ final class NettyReplyHandler extends ChannelInboundHandlerAdapter { /** The logger for the transport. */ private static final Log LOG = LogFactory.getLog(NettyReplyHandler.class); /** The listener for the responses. */ private final TransportResponseListener myResponseListener; /** * Creates a new NettyReplyHandler. * * @param listener * The listener for the responses. */ public NettyReplyHandler(final TransportResponseListener listener) { super(); myResponseListener = listener; } /** * {@inheritDoc} * <p> * If the message is a {@link Message} then forwards the message to the * {@link TransportResponseListener}. * </p> */ @Override public void channelRead(final ChannelHandlerContext ctx, final Object msg) { if (msg instanceof Message) { myResponseListener .response(new MessageInputBuffer(((Message) msg))); } else { LOG.warn("Received a non-message: {}.", msg); ctx.close(); } } }
package com.daylyweb.music.service; import java.util.List; import com.daylyweb.music.mapper.FeedBack; import com.daylyweb.music.mapper.Zan; public interface LogService { List getZan(int page,int limit,long longstart,long longend,String keyword); int insertZan(Zan zan); int delZan(String ids); List getFeedBack(int page,int limit,long longstart,long longend,String keyword); int insertFeedBack(FeedBack feedback); int delFeedBack(String ids); List getInfo(int page,int limit,long longstart,long longend,String keyword); int delInfo(String ids); }
package com.cinema.sys.model.base; import java.util.Date; import javax.persistence.Id; import javax.persistence.Table; @Table(name="sys_front_menu") public class TFrontMenu { @Id private String menuid; private String name; private String code; private String pid; private Short cseq; private String url; private Short enabled; private Short isopen; private Date createtime; private String creator; private Date updatetime; private String updator; private String icon; public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon == null ? null : icon.trim(); } public String getMenuid() { return menuid; } public void setMenuid(String menuid) { this.menuid = menuid == null ? null : menuid.trim(); } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getCode() { return code; } public void setCode(String code) { this.code = code == null ? null : code.trim(); } public String getPid() { return pid; } public void setPid(String pid) { this.pid = pid == null ? null : pid.trim(); } public Short getCseq() { return cseq; } public void setCseq(Short cseq) { this.cseq = cseq; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url == null ? null : url.trim(); } public Short getEnabled() { return enabled; } public void setEnabled(Short enabled) { this.enabled = enabled; } public Short getIsopen() { return isopen; } public void setIsopen(Short isopen) { this.isopen = isopen; } public Date getCreatetime() { return createtime; } public void setCreatetime(Date createtime) { this.createtime = createtime; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator == null ? null : creator.trim(); } public Date getUpdatetime() { return updatetime; } public void setUpdatetime(Date updatetime) { this.updatetime = updatetime; } public String getUpdator() { return updator; } public void setUpdator(String updator) { this.updator = updator == null ? null : updator.trim(); } }
package com.mkdutton.labfive.fragments; import android.app.AlertDialog; import android.app.Fragment; import android.graphics.Bitmap; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageView; import com.mkdutton.labfive.R; import java.text.Normalizer; /** * Created by Matt on 10/9/14. */ public class FormFragment extends Fragment{ public static final String TAG = "FORM_FRAG"; ImageView mImageView; public static FormFragment newInstance() { return new FormFragment(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_form, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mImageView = (ImageView)getActivity().findViewById(R.id.imageView); } public String[] getDataToSave (){ EditText et_top = ((EditText)getActivity().findViewById(R.id.topField)); EditText et_btm =((EditText)getActivity().findViewById(R.id.bottomField)); if (et_btm.getText().toString().isEmpty() || et_top.getText().toString().isEmpty()){ alertUser("Empty Field:", "Ensure both fields contain text"); } else { String[] strings = new String[]{ //remove the special characters to ensure file name is ok. Normalizer.normalize(et_top.getText().toString(), Normalizer.Form.NFD).replaceAll("[^ a-zA-Z]", ""), et_btm.getText().toString() }; return strings; } return null; } public void setImage(Bitmap _image) { mImageView.setImageBitmap(_image); } public void alertUser(String _title, String _message){ AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); alert.setTitle(_title) .setMessage(_message) .setPositiveButton("Ok", null) .show(); } }
package com.github.JohnDorsey.audio3; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /** * Created by John on 12/8/15. */ public class SaveTo { public FileOutputStream fileOutputStream; public File savingTo; public String fileName; public SaveTo(String nFileName) { fileName = nFileName; savingTo = new File(fileName); try { fileOutputStream = new FileOutputStream(savingTo); } catch (FileNotFoundException cantFind) { System.err.println("SaveTo.SaveTo(String): FileNoteFoundException: " + cantFind); } } public void write(byte toWrite) { try { fileOutputStream.write((int) toWrite); } catch (IOException ioe) { System.err.println("SaveTo.write(byte): IOException: " + ioe); } } public void write(byte[] toWrite) { try { fileOutputStream.write(toWrite); } catch (IOException ioe) { System.err.println("SaveTo.write(byte[]): IOException: " + ioe); } } }
package com.myou.appclient.activity; import java.util.HashMap; import java.util.Map; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.myou.appclient.base.Commons; import com.myou.appclient.base.RequestCode; import com.myou.appclient.ui.AsyncImageLoader; import com.myou.appclient.ui.AsyncImageLoader.ImageCallback; import com.myou.appclient.ui.CustomDialog; import com.myou.appclient.util.ConnectionUtils; import com.myou.appclient.util.ExceptionHandle; import com.myou.appclient.util.StringUtils; import com.myou.appclient.util.UrlUtils; import com.myou.appclient.util.ui.UIUtils; /** * Title: 智旅app<br> * Description: Activity基类<br> * Copyright: Copyright (c) 2013<br> * Company: MYOU<br> * * @author jjy * @version 1.0 */ /** * @author Administrator * */ public abstract class BaseActivity extends FragmentActivity { /** 类名 */ protected static String LOGNAME = ExceptionHandle.LOGNAME; /** 加载界面 */ private ProgressDialog progressDialog; /** 加载界面是否销毁 */ private boolean destroyed = false; /** 加载界面的结果 */ protected Object result; /** 加载界面的url */ protected String url = UrlUtils.HOST; public String urlType = ""; protected abstract void myCreate(Bundle savedInstanceState); @Override protected void onCreate(Bundle savedInstanceState) { try { super.onCreate(savedInstanceState); myCreate(savedInstanceState); } catch (Exception e) { // show("系统异常,请稍后重试。"); // finish(); } } /** * 回调 */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == RequestCode.EWM && data!= null && data.getExtras() != null) { String orderNo = data.getExtras().getString("orderNo"); String capture = data.getExtras().getString("capture"); if(StringUtils.isEmpty(Commons.getInstance().getUserPk())){ show("二维码扫描有效,请登陆后查询是否可以使用"); return; } urlType = "ewm"; Map<String, Object> map = new HashMap<String, Object>(); map.put("content", capture); map.put("id", orderNo); map.put("member", Commons.getInstance().getUserPk()); run("usercoupon.ashx", map); } super.onActivityResult(requestCode, resultCode, data); } public void to_phone(View v) { String str = ((TextView)v).getText().toString().replaceAll("电话:", ""); UIUtils.call(this, str); } public void detailButtonDo( int i2){ detailButtonDo(R.id.share_btn_wrap, i2); } public void detailButtonDo(int i1, int i2){ detailButtonDo(i1, i2, 0); } public void showAlertDialog(String[] items, DialogInterface.OnClickListener listener){ new AlertDialog.Builder(this).setTitle("温馨提示:请选择") .setItems(items, listener).show(); } public void detailButtonDo(int i1, int i2, int i3){ View old1View = (View) findViewById(R.id.share_btn_wrap); old1View.setVisibility(8); View i1View = (View) findViewById(i1); View i2View = (View) findViewById(i2); i1View.setVisibility(0); i2View.setVisibility(0); if(i3 != 0){ View view = (View) findViewById(i3); view.setVisibility(0); } } public void addBackClick(){ View ab_back = findViewById(R.id.ab_back); ab_back.setVisibility(0); } public void addShare(){ View ab_back = findViewById(R.id.title_share); ab_back.setVisibility(0); View title_search = findViewById(R.id.title_search); title_search.setVisibility(8); } public void addSearch(){ View ab_back = findViewById(R.id.title_search); ab_back.setVisibility(0); } public void ab_back(View v){ finish(); } public void share(View v) { UIUtils.share(this, "试试"); } public void setText(int id, String text){ TextView textview = (TextView) findViewById(id); textview.setText(text); } /** * 设置图片 * @param imageView * @param value */ public void setImage(final ImageView imageView, String value){ AsyncImageLoader asyncImageLoader = new AsyncImageLoader(); imageView.setTag(value); Drawable cachedImage = asyncImageLoader.loadDrawable(value, new ImageCallback() { public void imageLoaded(Drawable imageDrawable, String imageUrl) { ImageView imageViewByTag = (ImageView) imageView.findViewWithTag(imageUrl); if (imageViewByTag != null) { imageViewByTag.setImageDrawable(imageDrawable); } } }, this); imageView.setImageDrawable(cachedImage); } /** * 获得数据 * @param xmlName * @return */ protected SharedPreferences getSharedPreferences(String xmlName){ return this.getSharedPreferences(xmlName, Activity.MODE_APPEND); } protected SharedPreferences getSharedPreferences(){ return getSharedPreferences("typeInfo"); } /** * 保存数据 * @param xmlName * @param key * @param value * @return */ protected Editor getEditor(String xmlName){ return getSharedPreferences(xmlName).edit(); } protected Editor getEditor(){ return getSharedPreferences("typeInfo").edit(); } /** * 简单的提示信息 */ public void show(int id) { show(id, false); } public void show(Object obj) { show(obj, false); } public void show(int id, boolean isLong) { try { show(getString(id), isLong); } catch (Exception e) { show(id + "", isLong); } } public void show(Object obj, boolean isLong) { Toast toast = Toast .makeText(this, String.valueOf(obj), (isLong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT)); toast.show(); } /** * 稍微简单的封装一下 task */ public void showLoadingProgressDialog() { this.showProgressDialog(getString(R.string.loading2)); } @Override public void onDestroy() { super.onDestroy(); destroyed = true; } public void showProgressDialog(CharSequence message) { if (progressDialog == null) { progressDialog = new ProgressDialog(this); progressDialog.setIndeterminate(true); } progressDialog.setMessage(message); progressDialog.show(); } public void dismissProgressDialog() { if (progressDialog != null && !destroyed) { progressDialog.dismiss(); } } protected void runEndDo(Object result) { } public String getUrl() { return url; } /** * @param path 路径 (想见枚举ServletType) * @param map 请求的参数 */ public void run(String type, Map<String, Object> map) { run(type, map, true); } public void run(String type, Map<String, Object> map, boolean isShowLoading){ new BaseTask(isShowLoading, UrlUtils.putEnd(type, map)).execute(""); } public Object getResult() { return result; } public class BaseTask extends AsyncTask<Object, Object, Object> { boolean isShowLoading; protected Map<String, Object> map; public BaseTask(boolean isShowLoading, Map<String, Object> map) { this.isShowLoading = isShowLoading; this.map = map; } @Override protected void onPreExecute() { if(isShowLoading){ showLoadingProgressDialog(); } } @Override protected Object doInBackground(Object... arg0) { return BaseActivity.this.doInBackground(map, arg0); } @Override protected void onPostExecute(Object result1) { BaseActivity.this.onPostExecute(result1); } protected void runEndDo(Object obj){ try { BaseActivity.this.runEndDo(obj); } catch (Exception e) { Log.e(LOGNAME, e.getMessage(), e); } } } public String getMethodType(){ return "GET"; } public void noRunDo(String type, Map<String, Object> map){ onPostExecute(doInBackground(UrlUtils.putEnd(type, map), "")) ; } public Object doInBackground(Map<String, Object> map, Object... arg0) { return ConnectionUtils.DO(this, url, getMethodType(), map); } public void onPostExecute(Object result1) { if(result1 == null){ show(R.string.dialog_net_err_msg); // 如果是 业务异常,显示异常msg }else if(result1.equals("0")){ show("服务器异常,请稍后重试!"); }else if(result1.toString().startsWith("服务器返回状态")){ show(result1 + " " + getResources().getString(R.string.dialog_net_err_msg)); }else{ // 处理真正的空数据 Log.i(LOGNAME, "请求数据成功:" + url + ",数据:" + result1); result = result1; runEndDo(result1); } dismissProgressDialog(); } /** * 是否显示退出提示 默认不显示 * @return */ public boolean isShowEsc(){ return false; } /** 客户端的icon */ public final static int BASEICON = R.drawable.ic_launcher; /** * 有输入框的弹出框 * @param text * @param posListener * @param negListener */ public void show_TEXT_DLG(String text, DialogInterface.OnClickListener posListener, DialogInterface.OnClickListener negListener){ show_TEXT_DLG(text, "确定", "取消", posListener, negListener); } public void show_TEXT_DLG(String text, String posText, String negText, DialogInterface.OnClickListener posListener, DialogInterface.OnClickListener negListener){ new AlertDialog.Builder(this) .setTitle(text) .setIcon(android.R.drawable.ic_dialog_info) .setView(new EditText(this)) .setPositiveButton(posText, posListener) .setNegativeButton(negText, negListener) .show(); } /** * 有按钮的提示界面 * @param buttonText * @param message * @param posListener */ public void show_MSG_DLG(String buttonText, String message, OnClickListener posListener) { CustomDialog dialog = new CustomDialog(BaseActivity.this); dialog.createAlert(message, BASEICON, buttonText, posListener); dialog.show(); } public void show_MSG_DLG(String message, OnClickListener posListener) { show_MSG_DLG("确定", message, posListener); } /** * @param message * 显示的主题内容 * @param icon * (Drawable)图标资源 * @param PosButtonText * 确定按钮文字,不设置默认为 “确定”, 如果没有 “确定” 按钮,则将此参数设置为:null * @param NegButtonText * 取消按钮文字,不设置默认为 "取消", 如果没有 “取消” 按钮,则将此参数设置为:null * @param posListener * 确定按钮响应事件 * @param negListener * 取消按钮相应事件 */ public void show_YES_NO(String message, String title, int icon, String PosButtonText, String NegButtonText, DialogInterface.OnClickListener posListener, DialogInterface.OnClickListener negListener) { CustomDialog dialog = new CustomDialog(BaseActivity.this); dialog.initTitle(title); dialog.createAlert(message, icon, PosButtonText, NegButtonText, posListener, negListener); dialog.show(); } /** * @param message * 显示的主题内容 * @param title * 标题 * @param posListener * 确定按钮响应事件 * @param negListener * 取消按钮相应事件 */ public void show_YES_NO(String message, String title, DialogInterface.OnClickListener posListener, DialogInterface.OnClickListener negListener) { show_YES_NO(message, title, BASEICON, getString(R.string.dialog_yes_msg), getString(R.string.dialog_no_msg), posListener, negListener); } /** * @param message * 显示的主题内容 * @param posListener * 确定按钮响应事件 * @param negListener * 取消按钮相应事件 */ public void show_YES_NO(String message, DialogInterface.OnClickListener posListener, DialogInterface.OnClickListener negListener) { show_YES_NO(message, getString(R.string.dialog_base_title), posListener, negListener); } }
package com.wso2.build.utils; import org.apache.commons.io.FileUtils; import org.apache.maven.model.Model; import org.apache.maven.model.Plugin; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.List; /** * Created by uvindra on 2/22/14. */ public class Utility { private static final String mvnBundlePluginName = "maven-bundle-plugin"; private static final String instructionsTag = "instructions"; public static List<String> getBundlePluginInstructionValues(MavenProject mavenProject, String searchInstruction) { List<Plugin> plugins = mavenProject.getBuildPlugins(); List<String> instructionValues = new LinkedList<String>(); for (Plugin plugin : plugins) { if (true != plugin.getArtifactId().equals(mvnBundlePluginName)) { continue; } Xpp3Dom config = (Xpp3Dom) plugin.getConfiguration(); Xpp3Dom[] instructions = config.getChildren(instructionsTag); for (Xpp3Dom instruction : instructions) { Xpp3Dom[] matchingInstructions = instruction.getChildren(searchInstruction); for (Xpp3Dom matchingInstruction : matchingInstructions) { String exportPackageValue = matchingInstruction.getValue(); instructionValues.add(exportPackageValue); } } } return instructionValues; } public static boolean isBundlePluginInstructionExist(MavenProject mavenProject, String searchInstruction) { List<Plugin> plugins = mavenProject.getBuildPlugins(); for (Plugin plugin : plugins) { if (true != plugin.getArtifactId().equals(mvnBundlePluginName)) { continue; } Xpp3Dom config = (Xpp3Dom) plugin.getConfiguration(); Xpp3Dom[] instructions = config.getChildren(instructionsTag); for (Xpp3Dom instruction : instructions) { Xpp3Dom[] matchingInstructions = instruction.getChildren(searchInstruction); if (0 < matchingInstructions.length) { return true; } } } return false; } public static boolean isElementSpecified(MavenProject mavenProject, String element) { Model model = mavenProject.getModel(); File pomFile = model.getPomFile(); try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(pomFile); NodeList nodeList = doc.getElementsByTagName(element); return (0 < nodeList.getLength()); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } public static boolean hasChildParentElement(MavenProject mavenProject, String childElement, String parentElement) { Model model = mavenProject.getModel(); File pomFile = model.getPomFile(); try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(pomFile); NodeList childNodes = doc.getElementsByTagName(childElement); if (0 == childNodes.getLength()) { // Specified child element does not exist return false; } for (int i = 0; i < childNodes.getLength(); ++i) { Node node = childNodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Node parentNode = node.getParentNode(); // The child elements parent is not the specified parent if (false == parentElement.equals(parentNode.getNodeName())) { return false; } } } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return true; } public static boolean hasParentChildElement(MavenProject mavenProject, String parentElement, String childElement) { Model model = mavenProject.getModel(); File pomFile = model.getPomFile(); try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(pomFile); NodeList parentNodes = doc.getElementsByTagName(parentElement); if (0 == parentNodes.getLength()) { // Specified parent element does not exist return false; } for (int i = 0; i < parentNodes.getLength(); ++i) { Node parentNode = parentNodes.item(i); if (parentNode.getNodeType() != Node.ELEMENT_NODE) { continue; } NodeList childNodes = parentNode.getChildNodes(); boolean isChildPresent = false; for (int j = 0; j < childNodes.getLength(); ++j) { Node childNode = childNodes.item(j); if (childNode.getNodeType() != Node.ELEMENT_NODE) { continue; } if (true == childElement.equals(childNode.getNodeName())) { isChildPresent = true; } } if (false == isChildPresent) { // Specified child not present in parent element return false; } } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return true; } public static List<NodeList> getChildrenOfParent(MavenProject mavenProject, String parentElement) { Model model = mavenProject.getModel(); File pomFile = model.getPomFile(); List<NodeList> childNodeList = new LinkedList<NodeList>(); try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(pomFile); NodeList parentNodes = doc.getElementsByTagName(parentElement); if (0 == parentNodes.getLength()) { // Specified parent element does not exist return childNodeList; } for (int i = 0; i < parentNodes.getLength(); ++i) { Node parentNode = parentNodes.item(i); if (parentNode.getNodeType() != Node.ELEMENT_NODE) { continue; } NodeList childNodes = parentNode.getChildNodes(); childNodeList.add(childNodes); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return childNodeList; } }
import java.util.*; public class array3 { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("Enter the size of the array:"); int n=sc.nextInt(); int A[]=new int[n]; int i,j,k,a,b,c,count=0; System.out.println("Enter the elements of the array:"); for(i=0;i<n;i++) { A[i]=sc.nextInt(); } System.out.println("Enter the value of a,b,c"); a=sc.nextInt(); b=sc.nextInt(); c=sc.nextInt(); for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { for(k=j+1;k<n;k++) { if((Math.abs(A[i]-A[j])<=a)&&(Math.abs(A[j]-A[k])<=b)&&(Math.abs(A[i]-A[k])<=c)) { System.out.println(A[i]+","+A[j]+","+A[k]); count++; } } } } System.out.println("Output : "+count); } }
package com.legaoyi.protocol.messagebody.decoder; import org.springframework.stereotype.Component; import com.legaoyi.protocol.message.decoder.MessageBodyDecoder; /** * @author <a href="mailto:shengbo.gao@gmail.com;78772895@qq.com">gaoshengbo</a> * @version 1.0.0 * @since 2019-05-20 */ @Component(MessageBodyDecoder.MESSAGE_BODY_DECODER_BEAN_PREFIX + "0700_14H_2019" + MessageBodyDecoder.MESSAGE_BODY_DECODER_BEAN_SUFFIX) public class Jt808_2019_0700_14H_MessageBodyDecoder extends Jt808_2019_0700_13H_MessageBodyDecoder { }
public class HashMapTerster { private static String SUBSET ="arr2[] is a subset of arr1[]"; private static String NO_SUBSET = "arr2[] is not a subset of arr1[]"; public static void main(String[] args) { int arr1[] = {10, 5, 2, 23, 19}; int arr2[] = {19, 5, 3}; FindSubset set = new FindSubset(); //System.out.println(set.findSubset(arr1, arr2, arr1.length, arr2.length) ? SUBSET : NO_SUBSET ); System.out.println(set.findSubsetBetter(arr1, arr2, arr1.length, arr2.length) ? SUBSET : NO_SUBSET ); } }
package com.gaoshin.stock.plugin; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; public class WebUtil { private static HashMap<String, byte[]> resources = new HashMap<String, byte[]>(); public static byte[] get(String addr) throws Exception { byte[] cache = resources.get(addr); if(cache != null) { return cache; } URL url = new URL(addr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream inputStream = conn.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buff = new byte[8192]; while(true) { int len = inputStream.read(buff); if(len < 0) { break; } baos.write(buff, 0, len); } inputStream.close(); byte[] byteArray = baos.toByteArray(); resources.put(addr, byteArray); return byteArray; } }
package com.Exam.DAO.implement; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; import org.apache.lucene.search.Query; import org.hibernate.search.jpa.FullTextEntityManager; import org.hibernate.search.jpa.FullTextQuery; import org.hibernate.search.jpa.Search; import org.hibernate.search.query.dsl.QueryBuilder; import org.springframework.stereotype.Repository; import com.Exam.DAO.SearchCustomerDAO; import com.Exam.Entity.Customer; @Repository public class SearchCustomerDAOIml implements SearchCustomerDAO{ @PersistenceContext EntityManager en; @Override @Transactional public List<Customer> search(String q) { FullTextQuery fullTextQuery = getFullTextQuery(q); List<Customer> list = fullTextQuery.getResultList(); return list; } public FullTextQuery getFullTextQuery(String q) { FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(en); QueryBuilder queryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Customer.class).get(); Query query = queryBuilder.keyword().onFields("maKH","tenKH","email").matching(q.toLowerCase()).createQuery(); FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(query, Customer.class); return fullTextQuery; } }
package xdroid.core; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import android.os.Process; import java.util.concurrent.atomic.AtomicInteger; /** * @author Oleksii Kropachov (o.kropachov@shamanland.com) */ public final class ThreadUtils implements Runnable { private static AtomicInteger sCounter; private static Runnable sStopper; private ThreadUtils() { // disallow public access } private static String newName() { AtomicInteger counter = sCounter; if (counter == null) { counter = new AtomicInteger(); sCounter = counter; } return ThreadUtils.class.getSimpleName() + '-' + counter.incrementAndGet(); } /** * @see #newThread(String, int, Handler.Callback) */ public static Handler newThread(Handler.Callback callback) { return newThread(null, Process.THREAD_PRIORITY_LOWEST, callback); } /** * @see #newThread(String, int, Handler.Callback) */ public static Handler newThread(String name, Handler.Callback callback) { return newThread(name, Process.THREAD_PRIORITY_LOWEST, callback); } /** * Creates new {@link HandlerThread} and returns new {@link Handler} associated with this thread. * * @param name name of thread, in case of null - the default name will be generated * @param priority one of constants from {@link android.os.Process} * @param callback message handling callback, may be null * @return new instance */ public static Handler newThread(String name, int priority, Handler.Callback callback) { HandlerThread thread = new HandlerThread(name != null ? name : newName(), priority); thread.start(); return new Handler(thread.getLooper(), callback); } /** * Creates new {@link Handler} with the same {@link Looper} as the original handler. * * @param original original handler, can not be null * @param callback message handling callback, may be null * @return new instance */ public static Handler newHandler(Handler original, Handler.Callback callback) { return new Handler(original.getLooper(), callback); } /** * @see #stopThread(Handler, boolean) */ public static void stopThread(Handler handler) { stopThread(handler, true); } /** * Post the {@link Runnable} instance with the following code to the {@link Handler} provided: * <pre> * public void run() { * Looper.myLooper().quit(); * } * </pre> * * @param handler target handler, can not be null * @param asap if true then method {@link Handler#postAtFrontOfQueue(Runnable)} will be used. */ public static void stopThread(Handler handler, boolean asap) { Runnable stopper = sStopper; if (stopper == null) { stopper = new ThreadUtils(); sStopper = stopper; } if (asap) { handler.postAtFrontOfQueue(stopper); } else { handler.post(stopper); } } @Override public void run() { Looper looper = Looper.myLooper(); if (looper != null) { looper.quit(); } } public static class ObjAsRunnableCallback implements Handler.Callback { public static final ObjAsRunnableCallback INSTANCE = new ObjAsRunnableCallback(); private ObjAsRunnableCallback() { // disallow public access } @Override public boolean handleMessage(Message message) { if (message.obj instanceof Runnable) { ((Runnable) message.obj).run(); return true; } return false; } } }
package com.duanc.mapper.common; import java.util.List; import com.duanc.model.dto.BrandDTO; public interface BrandCommonMapper { /** * @Title: getBrands * @Description: 获取所有的品牌 * @return List<BrandPO> */ List<BrandDTO> getBrands(); }
package com.tch.test.iwjw.march; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.tch.test.common.httpcomponent.httpclient.utils.HttpUtils; import lombok.extern.slf4j.Slf4j; @Slf4j public class DistributeCameraMan { private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(DistributeCameraMan.class); public static void main(String[] args) throws Exception { new DistributeCameraMan().handleNotPickedUpTask(null, null); } public void handleNotPickedUpTask(Date fromTime, Date toTime) throws Exception { //任务超过30分钟未被领取,任务分配给板块内“已预约”任务数量最少的组员 Set<Long> cityList = new HashSet<Long>();//任务的城市列表 //1.查询超过30分钟未被领取的任务(key:板块,value:该板块的未被领取的任务列表) Map<Long, List<HouseReserveTask>> townTaskMap = getNeedHandleTaskMap(fromTime, toTime, cityList); if(MapUtils.isEmpty(townTaskMap)){ log.info("没有需要处理的未领取的任务"); return; } Set<Long> townIds = townTaskMap.keySet();//keySet为全部待处理的任务的板块 //2.查询该板块内“已预约”任务数量最少的组员(key:板块,value:这个版块的摄影师id列表) Map<Long, Set<Long>> townCameraManMap = getTownCameraManMap(townIds, cityList); System.out.println(townCameraManMap); if(MapUtils.isEmpty(townCameraManMap)){ log.info("板块-摄影师映射map为空"); return; } //查询这些摄影师的“已预约”任务数量(key:摄影师id, value:摄影师“已预约”任务数量) Map<Long, Integer> cameraManTaskNumMap = getCameraManTaskNumMap(townCameraManMap); //3.将该任务分配给该组员 for(Long townId : townIds){ //按照板块分配task给摄影师 distributeTask(townId, townTaskMap, townCameraManMap, cameraManTaskNumMap); } } /** * 按照板块分配task给摄影师 * @param townId 板块id * @param townTaskMap key:板块,value:该板块的未被领取的任务列表 * @param townCameraManMap key:板块,value:这个版块的摄影师id列表 * @param cameraManTaskNumMap 摄影师任务数量缓存(key:摄影师id, value:摄影师“已预约”任务数量) */ private void distributeTask(Long townId, Map<Long, List<HouseReserveTask>> townTaskMap, Map<Long, Set<Long>> townCameraManMap, Map<Long, Integer> cameraManTaskNumMap) { //任务分配给板块内“已预约”任务数量最少的组员· for(HouseReserveTask task : townTaskMap.get(townId)){ try { //从给定的摄影师中找出任务数最少的 Long cameraManId = getLeastTaskCameraManId(cameraManTaskNumMap, townCameraManMap.get(townId)); if(cameraManId == null){ log.info("板块{}下未找到可分配的摄影师", townId); continue; } //将该任务分配给该摄影师 //将缓存中该摄影师的任务数量+1 cameraManTaskNumMap.put(cameraManId, cameraManTaskNumMap.get(cameraManId) + 1); } catch (Exception e) { //打印日志,但不影响下一个任务的分配 e.printStackTrace(); log.error(String.format("分配任务%d异常:", task.getId()), e); } } } /** * 从给定的摄影师中找出任务数最少的 * @param cameraManTaskNumMap 摄影师任务数量缓存(key:摄影师id, value:摄影师“已预约”任务数量) * @param cameraMen 给定的摄影师id列表 * @return */ private Long getLeastTaskCameraManId(Map<Long, Integer> cameraManTaskNumMap, Set<Long> cameraMen) { if(CollectionUtils.isEmpty(cameraMen)){ log.info("cameraMen为空,cameraManTaskNumMap{}", cameraManTaskNumMap); return null; } if(MapUtils.isEmpty(cameraManTaskNumMap)){ log.info("cameraManTaskNumMap为空,cameraMen{}", cameraMen); return null; } boolean isFirst = true; Long cameraManId = null; Integer taskNum = null; for(Map.Entry<Long, Integer> entry : cameraManTaskNumMap.entrySet()){ if(! cameraMen.contains(entry.getKey())){ //不在给定的摄影师中,不算在内 continue; } if(isFirst){//suppose the first one is the smallest. isFirst = false; cameraManId = entry.getKey(); taskNum = entry.getValue(); continue; }else{ if(entry.getValue() < taskNum){ //current taskNum is smaller taskNum = entry.getValue(); cameraManId = entry.getKey(); } } } return cameraManId; } /** * 查询摄影师的“已预约”任务数量 * @param cameraManId * @return */ private int getCameraManTaskNum(Long cameraManId){ return 1; } /** * 查询这些摄影师的“已预约”任务数量(key:摄影师id, value:摄影师“已预约”任务数量) * @return */ private Map<Long, Integer> getCameraManTaskNumMap(Map<Long, Set<Long>> townCameraManMap) { Map<Long, Integer> result = new HashMap<Long, Integer>(); Set<Long> cameraManIds = getCameraManIds(townCameraManMap); if(CollectionUtils.isEmpty(cameraManIds)){ log.info("摄影师列表cameraManIds为空"); return result; } //这里为了防止摄影师数量太多,导致慢SQL,针对每个摄影师执行一次查询 for(Long cameraManId : cameraManIds){ //查询摄影师的“已预约”任务数量 result.put(cameraManId, getCameraManTaskNum(cameraManId)); } return result; } /** * 获取全部摄影师id * @param townCameraManMap * @return */ private Set<Long> getCameraManIds(Map<Long, Set<Long>> townCameraManMap) { Set<Long> cameraManIds = new HashSet<Long>(); //townCameraManMap key:板块,value:这个版块的摄影师id列表 Collection<Set<Long>> cameraMenIdCollection = townCameraManMap.values(); if(CollectionUtils.isEmpty(cameraMenIdCollection)){ return cameraManIds; } for(Set<Long> set : cameraMenIdCollection){ cameraManIds.addAll(set); } return cameraManIds; } /** * 查询板块-摄影师信息(key:板块,value:这个版块的摄影师id列表) * @param townIds 所有感兴趣的板块列表 * @param cityIds 所有感兴趣的板块所属的城市列表 * @return * @throws Exception */ private Map<Long, Set<Long>> getTownCameraManMap(Set<Long> townIds, Set<Long> cityIds) throws Exception { Map<Long, Set<Long>> result = new HashMap<Long, Set<Long>>(); if(CollectionUtils.isEmpty(cityIds)){ log.info("城市列表为空。。。"); return result; } for(Long cityId : cityIds){ //查询该城市下全部摄影师列表 String allSurveyStr = HttpUtils.doGet("http://121.40.129.114:8116/UumSOA/agent/getAllSurveys.action?cityId=2"); @SuppressWarnings("unchecked") List<JSONObject> agentAreaOrgVos = JSON.parseObject(allSurveyStr).getObject("data", List.class); if(CollectionUtils.isEmpty(agentAreaOrgVos)){ log.info("城市{}的摄影师为空", cityId); continue; } for(JSONObject agentAreaOrgVo : agentAreaOrgVos){ //key:板块,value:这个版块的摄影师id列表 String groupInfoStr = HttpUtils.doGet("http://121.40.129.114:8116/UumSOA/agent/getRelationByGroupIdAndType.action?groupId=" + agentAreaOrgVo.get("agentGroupId") + "&groupType=1"); @SuppressWarnings("unchecked") List<JSONObject> estateVos = JSON.parseObject(groupInfoStr).getObject("data", List.class); //List<GroupAreaRelationVO> estateVos = JSON.parseObject(groupInfoStr, new TypeReference<List<GroupAreaRelationVO>>(){}); if(CollectionUtils.isEmpty(estateVos)){ log.info("estateVos为空, groupId{}", agentAreaOrgVo.get("agentGroupId")); continue; } for(JSONObject estateVo : estateVos){ //只关心未领取的任务所属的板块范围,不在该范围的,忽略 if(!townIds.contains(Long.parseLong(String.valueOf(estateVo.get("areaId"))))){ continue; } Set<Long> cameraManIds = result.get(Long.parseLong(String.valueOf(estateVo.get("areaId")))); if(cameraManIds == null){ cameraManIds = new HashSet<Long>(); result.put(Long.parseLong(String.valueOf(estateVo.get("areaId"))), cameraManIds); } //将该摄影师添加到负责该板块的摄影师列表中 cameraManIds.add(Long.parseLong(String.valueOf(agentAreaOrgVo.get("agentId")))); } } } return result; } /** * 查询指定时间内未被领取的任务(key:板块,value:该板块的未被领取的任务列表) * @return */ private Map<Long, List<HouseReserveTask>> getNeedHandleTaskMap(Date fromTime, Date toTime, Set<Long> cityList) { Map<Long, List<HouseReserveTask>> result = new HashMap<>(); List<HouseReserveTask> tasks = new ArrayList<>(); HouseReserveTask task = new HouseReserveTask(); task.setTownId(23L); task.setCityId(2L); tasks.add(task); tasks.add(task); tasks.add(task); tasks.add(task); result.put(23L, tasks); cityList.add(2L); return result; } }
package com.gaoxi.gaoxicontroller.entity; /** * @author limm * @data 2020/5/14 17:57 */ public class B { }
package mtuci.nikitakutselay.mobileapplicationprogrammingcourse; /** * Created by nikitakucelaj on 12.12.2017. */ public class ApplicationListMenuItem { public static final int COPY_APPLICATION_NAME = 0; public static final int COPY_PACKAGE_NAME = 1; public static final int SHOW_APPLICATION_INFO = 2; }
import structure.LazySplayNet; import structure.SplayNet; import java.util.Scanner; public class NetMain { public static void main(String[] args) { /* Input Type Line 1--> number of nodes in the input tree (eg. m) Line 2--> list keys of all nodes present in the tree (m integers) Line 3--> alpha value -- single integer Line 4--> number of search queries (eg, n) Line 5 to line (n+5)--> n pairs of integers in next n lines Eg of input :- 7 5 2 3 7 1 10 0 5 4 0 3 1 2 2 5 1 7 Corresponding output: original Tree: 5 2 1 0 3 7 10 Final tree: 2 0 1 5 3 7 10 total_routing_cost=9 epoch_routing_cost=4 adjustment_cost=5 */ Scanner s = new Scanner(System.in); int totNodes = s.nextInt(); SplayNet input_net = new SplayNet(); for (int i = 0; i < totNodes; i++) { int in = s.nextInt(); input_net.insert(in); } int alpha = s.nextInt(); LazySplayNet lazy_net = new LazySplayNet(input_net, alpha); int tot_comm_req = s.nextInt(); for (int i = 0; i < tot_comm_req; i++) { int u = s.nextInt(); int v = s.nextInt(); lazy_net.request(u, v); System.out.println(lazy_net.total_routing_cost); } } }
package isSymmetric101; import dataStructure.*; import java.util.*; /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { /** * 层次遍历法 * @param root * @return */ public boolean isSymmetric2(TreeNode root) { ArrayDeque<TreeNode> queue = new ArrayDeque<>(); int length = 0; int i = 0; TreeNode emptynode = new TreeNode(0); TreeNode node = null; if(root == null) return true; queue.add(root); while (!queue.isEmpty()){ length = queue.size(); TreeNode[] aTree = new TreeNode[length]; queue.toArray(aTree); for(i = 0; i < length/2; ++i){ if(aTree[i] == emptynode && aTree[length - 1 - i] == emptynode) continue; if((aTree[i] == emptynode && aTree[length - 1 - i] != emptynode) || (aTree[i] != emptynode && aTree[length - 1 - i] == emptynode)) return false; if(aTree[i].val != aTree[length - 1 - i].val) return false; } for(i = 0; i < length; ++i){ node = queue.poll(); if(node != emptynode) { queue.add(node.left == null ? emptynode : node.left); queue.add(node.right == null ? emptynode : node.right); } } } return true; } /** * 递归 * @param root * @return */ public boolean isSymmetric(TreeNode root) { if(root == null) return true; return helper(root.left, root.right); } private boolean helper(TreeNode t1, TreeNode t2){ if(t1 == null && t2 == null) return true; if(t1 == null || t2 == null) return false; if(t1.val != t2.val) return false; return helper(t1.left, t2.right) && helper(t1.right, t2.left); } }
package com.zeal.smartdo.model; /** * @author 廖伟健 */ public class BBSBean extends BaseBean { public String id; public long createTime; public int postsId; public int forumUserId; public String isShield; public String postTitle; public String postContent; public String postTag; public String isLock; public String isDelete; public String isVote; public String topPicId; public int isTop; public int isHot; public int isBest; public String isRecommend; public String postsIntegral; public long lastUpdateDate; public String postsStatus; public int isContainsAttach; public String postsType; public int posId; public String posName; public String locationName; public String locationCity; public String other; public String nickName; public String headImage; public int commentCount; public int favoriteCount; public int praiseCount; public int isPraise; public int isFavorite; public String code; public String msg; public int totalPage; }
package com.wdl.base.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.MappedSuperclass; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Version; import org.hibernate.annotations.CreationTimestamp; /** * @author bin * */ @MappedSuperclass public abstract class BaseEntity implements Serializable { private static final long serialVersionUID = 1L; /** * 主键ID自动生成策略 */ @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") protected Long id; /** * 版本号 */ @Version @Column(name = "version") protected Integer version; /** * 创建时间 */ @Column(name = "create_date_time") @Temporal(TemporalType.TIMESTAMP) @CreationTimestamp protected Date createDateTime; /** * 最后修改时间 */ @Column(name = "update_date_time") @Temporal(TemporalType.TIMESTAMP) @CreationTimestamp protected Date updateDateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public Date getCreateDateTime() { return createDateTime; } public void setCreateDateTime(Date createDateTime) { this.createDateTime = createDateTime; } public Date getUpdateDateTime() { return updateDateTime; } public void setUpdateDateTime(Date updateDateTime) { this.updateDateTime = updateDateTime; } }
package ru.jft.first; import org.testng.Assert; import org.testng.annotations.Test; public class PointTests { @Test public void testDistance() { Point p1 = new Point(10, -30); Point p2 = new Point(0, 45); Assert.assertEquals(p2.getDistance(p1), 76.0); } }
/* * 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. */ /** * * @author orion */ public class MoleController { private Model brain; private View ui; public MoleController(Model brain, View ui) { this.brain = brain; this.ui = ui; } }
package com.egswebapp.egsweb.util; import com.egswebapp.egsweb.model.User; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import java.io.InputStream; import java.io.StringWriter; import java.util.Properties; public class EmailSendUtil { private Session session; private Properties prop; private static final EmailSendUtil instance = new EmailSendUtil(); private static final SampleVelocity sampleVelocity = new SampleVelocity(); private EmailSendUtil() { InputStream input = EmailSendUtil.class.getClassLoader().getResourceAsStream("mail-config.properties"); { prop = new Properties(); if (input == null) { System.out.println("Sorry, unable to find mail-config.properties"); } else { try { prop.load(input); session = Session.getDefaultInstance(prop, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( prop.getProperty("mail.username"), prop.getProperty("mail.password")); } }); } catch (Exception ex) { throw new RuntimeException("Unable to send email", ex); } } } } public static EmailSendUtil getInstance() { return instance; } public void sendEmail( final User user, final Email email) { try { BodyPart messageBodyPart = new MimeBodyPart(); MimeMessage message = new MimeMessage(session); message.addRecipient(Message.RecipientType.TO, new InternetAddress(email.getRecipientAddress())); message.setSubject(email.getSubject()); StringWriter out = sampleVelocity.configVelocity(email.getBody(), user); messageBodyPart.setContent(out.toString(), "text/html"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); message.setContent(multipart, "text/html"); Transport.send(message); System.out.println("message sent successfully"); } catch (MessagingException e) { throw new RuntimeException(e); } } }
package edu.ktu.ds.lab2.cpu; import edu.ktu.ds.lab2.demo.Car; import edu.ktu.ds.lab2.demo.CarsGenerator; import edu.ktu.ds.lab2.demo.SimpleBenchmark; import edu.ktu.ds.lab2.demo.Timekeeper; import edu.ktu.ds.lab2.gui.ValidationException; import edu.ktu.ds.lab2.utils.*; import edu.ktu.ds.lab2.utils.SortedSet; import java.util.*; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Semaphore; public class BenchMark { public static final String FINISH_COMMAND = " "; private static final ResourceBundle MESSAGES = ResourceBundle.getBundle("edu.ktu.ds.lab2.gui.messages"); private static final String[] BENCHMARK_NAMES = {"TreecontainsAll", "TreeContains", "HashContainAll", "HashContains"}; private static final int[] COUNTS = {10000, 20000, 40000, 80000}; private final Timekeeper timeKeeper; private final String[] errors; private final TreeSet<Integer> tree = new TreeSet<>(); private final HashSet<Integer> hast = new HashSet<>(); private final Collection<Integer> col = new ArrayList<>(); /** * For console benchmark */ public BenchMark() { timeKeeper = new Timekeeper(COUNTS); errors = new String[]{ MESSAGES.getString("badSetSize"), MESSAGES.getString("badInitialData"), MESSAGES.getString("badSetSizes"), MESSAGES.getString("badShuffleCoef") }; } /** * For Gui benchmark * * @param resultsLogger * @param semaphore */ public BenchMark(BlockingQueue<String> resultsLogger, Semaphore semaphore) { semaphore.release(); timeKeeper = new Timekeeper(COUNTS, resultsLogger, semaphore); errors = new String[]{ MESSAGES.getString("badSetSize"), MESSAGES.getString("badInitialData"), MESSAGES.getString("badSetSizes"), MESSAGES.getString("badShuffleCoef") }; } public static void main(String[] args) { executeTest(); } public void GenerateNumbers(int k) { for(int i =0; i < k; i++) { tree.add(i); hast.add(i); } } public void NumberCollection(int k) { k = (int)Math.floor(k / 2); for(int i =0; i < k; i++) { Random num = new Random(); int number = num.nextInt(k + 1000); col.add(number); } } public static void executeTest() { // suvienodiname skaičių formatus pagal LT lokalę (10-ainis kablelis) Locale.setDefault(new Locale("LT")); Ks.out("Greitaveikos tyrimas:\n"); new BenchMark().startBenchmark(); } public void startBenchmark() { try { benchmark(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Exception ex) { ex.printStackTrace(System.out); } } private void benchmark() throws InterruptedException { try { boolean keep = false; for (int k : COUNTS) { Random numb = new Random(); int numbertofind = numb.nextInt(k / 2); tree.clear(); hast.clear(); col.clear(); GenerateNumbers(k); NumberCollection(k); timeKeeper.startAfterPause(); timeKeeper.start(); keep = tree.containsAll(col); timeKeeper.finish(BENCHMARK_NAMES[0]); tree.contains(numbertofind); timeKeeper.finish(BENCHMARK_NAMES[1]); hast.containsAll(col); timeKeeper.finish(BENCHMARK_NAMES[2]); hast.contains(numbertofind); timeKeeper.finish(BENCHMARK_NAMES[3]); timeKeeper.seriesFinish(); } timeKeeper.logResult(FINISH_COMMAND); } catch (ValidationException e) { if (e.getCode() >= 0 && e.getCode() <= 3) { timeKeeper.logResult(errors[e.getCode()] + ": " + e.getMessage()); } else if (e.getCode() == 4) { timeKeeper.logResult(MESSAGES.getString("allSetIsPrinted")); } else { timeKeeper.logResult(e.getMessage()); } } } }
package br.com.View; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import br.com.UsuarioController.AlunosController; import javax.swing.JTextField; import javax.swing.JLabel; import javax.swing.JOptionPane; import java.awt.Font; import javax.swing.JButton; import java.awt.event.ActionListener; import java.io.IOException; import java.awt.event.ActionEvent; public class RemoverAlunoFrame extends JFrame { /** * */ private static final long serialVersionUID = 1L; private JPanel contentPane; private JTextField RAtxt; private JLabel lblNewLabel_1; /** * Launch the application. */ public static void main(String[] args) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { } EventQueue.invokeLater(new Runnable() { public void run() { try { RemoverAlunoFrame frame = new RemoverAlunoFrame(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } AlunosController controlador = new AlunosController(); /** * Create the frame. */ public RemoverAlunoFrame() { setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 450, 300); // contentPane = new JPanel(); try { contentPane = new FundoBg("C:\\Users\\wagne\\Desktop\\Estudos progamção 2\\APS-Interface\\Imagens\\Fundos de tela\\FundoRemoverAluno.png"); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); RAtxt = new JTextField(); RAtxt.setBounds(161, 121, 112, 20); contentPane.add(RAtxt); RAtxt.setColumns(10); lblNewLabel_1 = new JLabel("RA"); lblNewLabel_1.setFont(new Font("Tahoma", Font.PLAIN, 14)); lblNewLabel_1.setBounds(141, 122, 17, 14); contentPane.add(lblNewLabel_1); JButton btnNewButton = new JButton("Remover"); btnNewButton.setBounds(171, 152, 89, 23); contentPane.add(btnNewButton); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { remover(); JOptionPane.showMessageDialog(null, "Aluno Removido com sucesso!", "Operação Concluida", JOptionPane.INFORMATION_MESSAGE); RAtxt.setText(""); } }); } private void remover() { controlador.Deletar(RAtxt.getText()); } }
open module modmain { // allow reflective access, currently used in the example_jerry-mouse requires modb1; requires modb2; }