text
stringlengths
10
2.72M
package com.example.demo.entity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; import java.io.Serializable; import java.util.List; @Getter @Setter @AllArgsConstructor @NoArgsConstructor @Entity @Table(name = "publisher") public class Publisher implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @Column(name = "name") private String name; @Column(name = "address") private String address; @Column(name = "email") private String email; @OneToMany(mappedBy = "publisher", fetch = FetchType.LAZY) private List<Book> books; }
package com.laurenelder.aquapharm; public class Fish { public String name; public Integer minTemp; public Integer maxTemp; public String image; public String edible; public Fish(String fishName, Integer minfishTemp, Integer maxfishTemp, String fishImage, String fishEdible) { this.name = fishName; this.minTemp = minfishTemp; this.maxTemp = maxfishTemp; this.image = fishImage; this.edible = fishEdible; } public String toString() { return name; } }
/** * ファイル名 : VSM18010XController.java * 作成者 : nv-manh * 作成日時 : 2018/05/31 * Copyright © 2017-2018 TAU Corporation. All Rights Reserved. */ package jp.co.tau.web7.admin.supplier.controllers; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import javax.servlet.http.HttpServletResponse; import javax.xml.ws.ResponseWrapper; import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import jp.co.tau.web7.admin.supplier.common.CommonConstants; import jp.co.tau.web7.admin.supplier.common.ScreenConstants; import jp.co.tau.web7.admin.supplier.dto.UserInfoDTO; import jp.co.tau.web7.admin.supplier.dto.VSM18010XSearchDTO; import jp.co.tau.web7.admin.supplier.forms.VSM18010XSearchForm; import jp.co.tau.web7.admin.supplier.mappers.common.annotation.Layout; import jp.co.tau.web7.admin.supplier.output.VSM18010XOutput; import jp.co.tau.web7.admin.supplier.services.VSM18010XService; import jp.co.tau.web7.admin.supplier.utils.MessageUtil; import jp.co.tau.web7.admin.supplier.vo.VSM18010XVO; /** * <p> * クラス名 : VSM18010XController * </p> * <p> * 説明 : ポップアップ * </p> * * @author nv-manh * @since 2018/05/31 */ @Controller public class VSM18010XController extends PaginationController { @Autowired MessageUtil msgUtil; /** * パスワード変更サービス */ @Autowired private VSM18010XService vsm18010XService; private static final String VSM18010XLISTFORM = "VSM18010XListForm"; private static final String TOTALIMAGE = "totalImage"; private static final String VSM18010XSEARCHFORM = "VSM18010XSearchForm"; @Override public String getTitle() { // TODO Auto-generated method stub return null; } /** * <p> * 説明 : init popup VSM180101 * </p> * * @author luantx * @since 2018/05/31 * @param mav ModelAndView * @return ModelAndView */ @Layout(value = "layout/popup-layout") @RequestMapping(value = ScreenConstants.VSM180101, method = RequestMethod.POST) @ResponseWrapper public ModelAndView initVSM180101(@RequestBody VSM18010XSearchForm vsm18010XSearchForm) { ModelAndView mav = createViewNamePopupNew(ScreenConstants.VSM180101, msgUtil.getMessage(CommonConstants.VSM1180101_PAGE_TITLE)); VSM18010XSearchDTO vsm18010XSearchDTO = modelMapper.map(vsm18010XSearchForm, VSM18010XSearchDTO.class); UserInfoDTO userInfor = (UserInfoDTO) getObjectFromSession(CommonConstants.USER_LOGIN_INFO); VSM18010XOutput vsm18010XOutput = vsm18010XService.initHistory(vsm18010XSearchDTO, userInfor); vsm18010XSearchDTO.setPage(vsm18010XOutput.getPage()); if (vsm18010XSearchDTO.getLimit() > 0) { setPaginationData(mav, vsm18010XOutput.getPage(), vsm18010XOutput.getTotalRowCount()); } else { setPaginationData(mav, vsm18010XOutput.getTotalRowCount()); } VSM18010XVO baseVO = modelMapper.map(vsm18010XOutput, VSM18010XVO.class); baseVO.initHeader(); mav.addObject(VSM18010XLISTFORM, baseVO); mav.addObject(VSM18010XSEARCHFORM, vsm18010XSearchForm); return mav; } /** * <p> * 説明 : init popup VSM180103 * </p> * * @author luantx * @since 2018/05/31 * @param mav ModelAndView * @return ModelAndView */ @Layout(value = "layout/popup-layout") @RequestMapping(value = ScreenConstants.VSM180103, method = RequestMethod.POST) @ResponseWrapper public ModelAndView initVSM180103(@RequestBody VSM18010XSearchForm vsm18010XSearchForm) { ModelAndView mav = createViewNamePopupNew(ScreenConstants.VSM180103, msgUtil.getMessage(CommonConstants.VSM1180103_PAGE_TITLE)); VSM18010XSearchDTO vsm18010XSearchDTO = modelMapper.map(vsm18010XSearchForm, VSM18010XSearchDTO.class); VSM18010XOutput vsm18010XOutput = vsm18010XService.initMonthlyFee(vsm18010XSearchDTO); vsm18010XSearchDTO.setPage(vsm18010XOutput.getPage()); if (vsm18010XSearchDTO.getLimit() > 0) { setPaginationData(mav, vsm18010XOutput.getPage(), vsm18010XOutput.getTotalRowCount()); } else { setPaginationData(mav, vsm18010XOutput.getTotalRowCount()); } VSM18010XVO baseVO = modelMapper.map(vsm18010XOutput, VSM18010XVO.class); baseVO.initHeader(); mav.addObject(VSM18010XLISTFORM, baseVO); mav.addObject(VSM18010XSEARCHFORM, vsm18010XSearchForm); return mav; } /** * <p> * 説明 : init popup VSM180102 * </p> * * @author luantx * @since 2018/05/31 * @param mav ModelAndView * @return ModelAndView */ @Layout(value = "layout/popup-layout") @RequestMapping(value = ScreenConstants.VSM180102, method = RequestMethod.POST) @ResponseWrapper public ModelAndView initVSM180102(@RequestBody VSM18010XSearchForm vsm18010XSearchForm) { ModelAndView mav = createViewNamePopupNew(ScreenConstants.VSM180102, msgUtil.getMessage(CommonConstants.VSM1180102_PAGE_TITLE)); VSM18010XSearchDTO vsm18010XSearchDTO = modelMapper.map(vsm18010XSearchForm, VSM18010XSearchDTO.class); VSM18010XOutput vsm18010XOutput = vsm18010XService.initPictureList(vsm18010XSearchDTO); VSM18010XVO baseVO = modelMapper.map(vsm18010XOutput, VSM18010XVO.class); mav.addObject(VSM18010XLISTFORM, baseVO); mav.addObject(TOTALIMAGE, baseVO.getDtoList().size()); return mav; } @GetMapping("showImg") public void showImage(@RequestParam(value = "dir", required = false) String dir, @RequestParam(value = "name", required = false) String name, HttpServletResponse response) throws FileNotFoundException { vsm18010XService.showImage(dir, name, response); } }
package lintcode; import java.util.HashMap; /** * @Author: Mr.M * @Date: 2019-05-31 18:59 * @Description: **/ public class T56两数之和 { public int[] twoSum(int[] numbers, int target) { // write your code here HashMap<Integer, Integer> hashMap = new HashMap<>(); for (int i = 0; i < numbers.length; i++) { // 上面的时间复杂度更高 // if(!hashMap.containsKey(target - numbers[i])) if (hashMap.get(target - numbers[i]) == null) { hashMap.put(numbers[i], i); } else { return new int[]{hashMap.get(target - numbers[i]), i}; } } return new int[]{}; } }
package rhtn_homework; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class BOJ_1915_가장큰정사각형 { public static void main(String[] args) throws IOException{ // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int N = Integer.parseInt(st.nextToken()); int M = Integer.parseInt(st.nextToken()); int[][] DP = new int[N][M]; int ans = 0; for (int i = 0; i < N; i++) { char[] line = br.readLine().toCharArray(); for (int j = 0; j < line.length; j++) { // 만약 i가 0 이면(첫줄) j가 0이면 (맨 왼쪽), DP랑 같다 if(i == 0 || j ==0) { DP[i][j] = line[j] - '0'; ans = Math.max(ans, DP[i][j]); continue; } if(line[j] == '1') { int min = 0; min = Math.min(DP[i-1][j], DP[i][j-1]); min = Math.min(DP[i-1][j-1], min); DP[i][j] = min +1; ans = Math.max(ans, DP[i][j]); } } } System.out.println(ans*ans); } }
package domain.model; import java.math.BigDecimal; import java.util.Arrays; import java.util.Date; import java.util.List; import lombok.Data; /** * This class duplicates (to a certain extent) the model of the instrument service on purpose. * The objective being to loosen the coupling between the services. * * @author Steve.Hostettler * */ @Data public class Instrument { private String id; private String brokerLei; private String isin; private String counterpartyLei; private String originalCurrency; private BigDecimal amountInOriginalCurrency; private Date dealDate; private Date valueDate; private Date maturityDate; private BigDecimal strikeAmount; private String direction; private String tracker; private Long quantity; private String instrumentType; public INSTRUMENT_TYPE getType() { return INSTRUMENT_TYPE.getEnumFromCode(instrumentType); } public enum INSTRUMENT_TYPE { STOCK ("S", "Stock"), LOAN ("L", "Loan"), BOND ("B", "Loan"), DEPOSIT ("D", "Deposit"), WARRANT ("W", "Warrant"); private String code; private String description; INSTRUMENT_TYPE(String code, String description) { this.code = code; this.description = description; } public String getCode() { return code; } public String getDescription() { return description; } public static INSTRUMENT_TYPE getEnumFromCode(String code) { List<INSTRUMENT_TYPE> list = Arrays.asList(INSTRUMENT_TYPE.values()); return list.stream().filter(m -> m.code.equals(code)).findAny().orElse(null); } } }
package com.ifli.mbcp.common.controller; import java.util.ArrayList; import java.util.List; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import org.dozer.DozerBeanMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.Validator; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.portlet.bind.annotation.ActionMapping; import org.springframework.web.portlet.bind.annotation.RenderMapping; import com.ifli.mbcp.domain.Lead; import com.ifli.mbcp.service.LeadService; import com.ifli.mbcp.util.MBCPConstants.SearchBy; import com.ifli.mbcp.util.Views; import com.ifli.mbcp.util.WebUtil; import com.ifli.mbcp.vo.SearchCriteriaBean; import com.ifli.mbcp.vo.LeadVO; import com.ifli.mbcp.vo.SearchByVO; @Transactional @Controller("commonController") @RequestMapping(value = "VIEW") public class CommonController { @Autowired @Qualifier("leadSearchValidator") private Validator leadSearchValidator; @Autowired @Qualifier("leadService") private LeadService leadService; @Autowired @Qualifier("leadDozerMapper") private DozerBeanMapper leadDozerMapper; private static final Logger logger = LoggerFactory.getLogger(CommonController.class); @RenderMapping(params = "render=gotoNextPage") public String gotoNextPage(@RequestParam Long leadId, Model model, RenderRequest renderRequest, RenderResponse renderResponse) { logger.info("Fetching default Lead for leadId : " + leadId); model.addAttribute("leadId", leadId); populateLeadSearchModel(model); return Views.LEAD_SEARCH_PAGE; } public void populateLeadSearchModel(Model model) { List<SearchByVO> searchByList = new ArrayList<SearchByVO>(); for (SearchBy searchBy : SearchBy.values()) { searchByList.add(new SearchByVO(searchBy.getValue(), searchBy.getDisplayValue())); } model.addAttribute("searchByList", searchByList); if (!model.containsAttribute("leadSearchBean")) { model.addAttribute("leadSearchBean", new SearchCriteriaBean()); } } @RenderMapping(params = "render=searchresults") public String showsearchResults(Model model, RenderResponse renderResponse) { populateLeadSearchModel(model); return Views.LEAD_SEARCH_RESULT_PAGE; } @ActionMapping(params = "action=searchLead") public void searchLead(@ModelAttribute("leadSearchBean") SearchCriteriaBean searchCriteria, BindingResult binder, Model model, ActionRequest actionRequest, ActionResponse actionResponse) { logger.info("Search Text :" + searchCriteria.getSearchText()); logger.info("Search By : " + searchCriteria.getSearchById()); leadSearchValidator.validate(searchCriteria, binder); if (!binder.hasErrors()) { searchCriteria.setSuccess(true); try { List<Lead> searchResultList = leadService.searchLead(searchCriteria); if (searchResultList == null || searchResultList.size() == 0) { model.addAttribute("message", "No results found"); } else { List<LeadVO> leadVOList = new ArrayList<LeadVO>(searchResultList.size()); for (Lead lead : searchResultList) { LeadVO leadVO = WebUtil.copyProperties(leadDozerMapper, lead, new LeadVO(), "getUpdateLead"); leadVOList.add(leadVO); } model.addAttribute("searchResultList", leadVOList); } } catch (Exception e) { model.addAttribute("message", "Error while searching"); e.printStackTrace(); } } else { searchCriteria.setSuccess(false); } actionResponse.setRenderParameter("render", "searchresults"); } }
package com.ytt.springcoredemo.dao.mapper.base; import com.ytt.springcoredemo.dao.mapper.core.CoreMapper; import com.ytt.springcoredemo.model.po.Good; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; /** * @Author: aaron * @Descriotion: * @Date: 11:15 2019/6/20 * @Modiflid By: */ //@Mapper public interface GoodMapper extends CoreMapper<Good, Long> { @Select("SELECT count(0) FROM goods") long getCount(); }
package fr.lteconsulting.training.appengine.marvels; import com.google.gson.Gson; import fr.lteconsulting.training.appengine.marvels.model.Character; import fr.lteconsulting.training.appengine.marvels.model.CharacterDataWrapper; import fr.lteconsulting.training.appengine.marvels.tools.MD5Tools; import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class MarvelGrab { public static void main( String[] args ) { String timeStamp = "1"; String publicKey = "2c4c69c4f2c2fd59cdbe9dc9429d254e"; String privateKey = "952fb13aeeb2ea14103811d46d3f48461c161918"; String hash = MD5Tools.md5( timeStamp + privateKey + publicKey ); ResteasyClient client = new ResteasyClientBuilder().build(); ResteasyWebTarget target = client.target( "https://gateway.marvel.com:443/v1/public" ); MarvelCharactersWS service = target.proxy( MarvelCharactersWS.class ); List<Character> characters = new ArrayList<>(); int offset = 0; while( true ) { System.out.println( "offset: " + offset ); CharacterDataWrapper marvels = service.getCharacters( timeStamp, publicKey, hash, offset ); if( marvels == null || marvels.data == null || marvels.data.results == null ) break; offset += marvels.data.results.size(); if( offset >= marvels.data.total ) break; characters.addAll( marvels.data.results ); } System.out.println( "finished" ); Gson gson = new Gson(); String content = gson.toJson( characters ); System.out.println( content ); try { FileWriter writer = new FileWriter( "marvels.json" ); writer.write( content ); writer.close(); } catch( IOException e ) { e.printStackTrace(); } System.out.println( "done" ); } }
package com.tencent.mm.plugin.ipcall.ui; public interface j$a { void gc(boolean z); }
package width_calc; public enum WidthType { 사각형, 삼각형 }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; /* ACMICPC 문제 번호 : 2309 문제 제목 : 일곱 난쟁이 풀이 날짜 : 2020-09-18 Solved By Reamer */ public class acm_2309 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); List<Integer> list = new ArrayList<Integer>(); int[] dwarf = new int[9]; int heightSum = 0; for (int i = 0; i < 9; i++) { dwarf[i] = sc.nextInt(); heightSum += dwarf[i]; } es: for (int i = 0; i < 8; i++) { for (int j = i + 1; j < 9; j++) { if (heightSum - dwarf[i] - dwarf[j] == 100) { dwarf[i] = 0; dwarf[j] = 0; break es; } } } Arrays.sort(dwarf); for (int i = 2; i < dwarf.length; i++) { System.out.println(dwarf[i]); } } }
package tes.No13; public class Dosen { String nik,kodeDosen,namaDosen,alamatDosen,kodeMk; public Dosen(String nik, String kodeDosen, String namaDosen, String alamatDosen, String kodeMk) { this.namaDosen = namaDosen; this.nik = nik; this.alamatDosen = alamatDosen; this.kodeDosen = kodeDosen; this.kodeMk = kodeMk; } /** * @return the nik */ public String getNik() { return nik; } /** * @param nik the nik to set */ public void setNik(String nik) { this.nik = nik; } /** * @return the kodeDosen */ public String getKodeDosen() { return kodeDosen; } /** * @param kodeDosen the kodeDosen to set */ public void setKodeDosen(String kodeDosen) { this.kodeDosen = kodeDosen; } /** * @return the namaDosen */ public String getNamaDosen() { return namaDosen; } /** * @param namaDosen the namaDosen to set */ public void setNamaDosen(String namaDosen) { this.namaDosen = namaDosen; } /** * @return the alamatDosen */ public String getAlamatDosen() { return alamatDosen; } /** * @param alamatDosen the alamatDosen to set */ public void setAlamatDosen(String alamatDosen) { this.alamatDosen = alamatDosen; } /** * @return the kodeMk */ public String getKodeMk() { return kodeMk; } /** * @param kodeMk the kodeMk to set */ public void setKodeMk(String kodeMk) { this.kodeMk = kodeMk; } }
package tpdev.listeners; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import org.json.JSONException; import org.json.JSONObject; import tpdev.tools.Conteneur; import tpdev.tools.Tools; public class ConnexionListener implements ActionListener { public void actionPerformed(ActionEvent arg0) { String login = Conteneur.loginField.getText(); String password = Conteneur.passwordField.getText(); try { JSONObject resp = Tools.envoyerRequete("api2/user/log?name="+login+"&password="+password); int entity = resp.getInt("entity"); if (entity == -1) { Conteneur.infoLoginLabel.setText("Erreur : login ou mot de passe incorrect"); return; } Conteneur.infoLoginLabel.setText("Vous êtes connecté !"); Tools.id = entity; Conteneur.infoPostLabel.setText(""); Conteneur.infoResponseLabel.setText(""); } catch (JSONException ex) { ex.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
package pattern.factory; public class LDCheesePizza extends Pizza { @Override public void prepare() { System.out.println("伦敦奶油pizza"); } }
package rhtn_homework; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.PriorityQueue; import java.util.StringTokenizer; public class BOJ_1916_최소비용_구하기 { private static StringBuilder sb = new StringBuilder(); private static List<Edge>[] al; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; int N = Integer.parseInt(br.readLine()); int M = Integer.parseInt(br.readLine()); al = new ArrayList[N+1]; for (int i = 1; i < al.length; i++) { al[i] = new ArrayList<>(); } for (int i = 0; i < M; i++) { st = new StringTokenizer(br.readLine()); int start = Integer.parseInt(st.nextToken()); int end = Integer.parseInt(st.nextToken()); int w = Integer.parseInt(st.nextToken()); al[start].add(new Edge(end, w)); } st = new StringTokenizer(br.readLine()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); PriorityQueue<Edge> pq = new PriorityQueue<>(); Edge[] d = new Edge[N+1]; for (int i = 1; i < d.length; i++) { if(i == A) d[i] = new Edge(i, 0); else d[i] = new Edge(i, Integer.MAX_VALUE); } // for (int i = 1; i < al.length; i++) { // System.out.println(al[i]); // } // System.out.println(Arrays.toString(d)); pq.add(d[A]); while(!pq.isEmpty()) { Edge edge = pq.poll(); if(d[edge.v].weight != edge.weight) continue; for (Edge next : al[edge.v]) { if(next.weight + d[edge.v].weight < d[next.v].weight) { d[next.v].weight = next.weight + d[edge.v].weight; pq.remove(d[next.v]); pq.add(d[next.v]); } } } System.out.println(d[B].weight); } public static class Edge implements Comparable<Edge>{ int v , weight; public Edge(int v, int weight) { super(); this.v = v; this.weight = weight; } @Override public int compareTo(Edge o) { Integer w1 = this.weight; Integer w2 = o.weight; return w1.compareTo(w2); } @Override public String toString() { return "Edge [v=" + v + ", weight=" + weight + "]"; } } }
/* * created 02.06.2005 * * Copyright 2009, ByteRefinery * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * $Id: ModelReader.java 678 2008-02-17 22:52:09Z cse $ */ package com.byterefinery.rmbench.util.xml; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.eclipse.draw2d.geometry.Point; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import com.byterefinery.rmbench.RMBenchPlugin; import com.byterefinery.rmbench.exceptions.SystemException; import com.byterefinery.rmbench.extension.DatabaseExtension; import com.byterefinery.rmbench.extension.NameGeneratorExtension; import com.byterefinery.rmbench.external.IDatabaseInfo; import com.byterefinery.rmbench.external.INameGenerator; import com.byterefinery.rmbench.external.database.sql99.SQL99; import com.byterefinery.rmbench.external.model.IDataType; import com.byterefinery.rmbench.external.model.IForeignKey; import com.byterefinery.rmbench.model.Model; import com.byterefinery.rmbench.model.diagram.DForeignKey; import com.byterefinery.rmbench.model.diagram.DTable; import com.byterefinery.rmbench.model.diagram.Diagram; import com.byterefinery.rmbench.model.schema.CheckConstraint; import com.byterefinery.rmbench.model.schema.Column; import com.byterefinery.rmbench.model.schema.ForeignKey; import com.byterefinery.rmbench.model.schema.Index; import com.byterefinery.rmbench.model.schema.PrimaryKey; import com.byterefinery.rmbench.model.schema.Schema; import com.byterefinery.rmbench.model.schema.Table; import com.byterefinery.rmbench.model.schema.UniqueConstraint; import com.byterefinery.rmbench.util.IModelStorage; /** * reads a model file which was previously stored by {@link com.byterefinery.rmbench.util.xml.ModelWriter}. * <br/>Only superficial validation is done * * @author cse */ public class ModelReader implements XMLConstants { private static class Adapter { void logError(String message) { RMBenchPlugin.logError(message); } void logWarning(String message) { RMBenchPlugin.logWarning(message); } IDatabaseInfo getDatabaseInfo(String infoName) { DatabaseExtension dbext = RMBenchPlugin.getExtensionManager().getDatabaseExtension(infoName); return dbext != null ? dbext.getDatabaseInfo() : null; } IDatabaseInfo getDefaultDatabaseInfo() { return RMBenchPlugin.getStandardDatabaseInfo(); } public INameGenerator getNameGenerator(String genId) { NameGeneratorExtension genext = RMBenchPlugin.getExtensionManager().getNameGeneratorExtension(genId); return genext != null ? genext.getNameGenerator() : null; } public INameGenerator getDefaultNameGenerator() { return RMBenchPlugin.getDefaultNameGenerator(); } } /** * @param inputStream the stream to read from * @param name name used for error reporting, normally the file name * @param listener a listener for model modifications during loading * * @return a model parsed from the XML stream * * @throws SystemException */ public static Model read(InputStream inputStream, String name, IModelStorage.LoadListener listener) throws SystemException { return read(inputStream, name, new Adapter(), listener); } private static Model read(InputStream inputStream, String name, Adapter adapter, IModelStorage.LoadListener listener) throws SystemException { ModelReader reader = new ModelReader(name, adapter, listener); try { XmlPullParser xpp = setupParser(inputStream); return reader.readModel(xpp); } catch(Exception x) { throw new SystemException(x); } finally { try { inputStream.close(); } catch (IOException e) { throw new SystemException(e); } } } private final String fileName; private final Adapter adapter; private final IModelStorage.LoadListener listener; private final List<ForeignKeyBuilder> foreignKeyBuilders = new ArrayList<ForeignKeyBuilder>(); private final List<TmpDForeignKey> tmpDForeignKeyList = new ArrayList<TmpDForeignKey>(); //hide the constructor private ModelReader(String fileName, Adapter adapter, IModelStorage.LoadListener listener) { this.fileName = fileName; this.adapter = adapter; this.listener = listener; } private static XmlPullParser setupParser(InputStream inputStream) throws SystemException { XmlPullParserFactory factory; try { factory = XmlPullParserFactory.newInstance(); factory.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true); } catch (XmlPullParserException e) { throw new SystemException(e); } factory.setNamespaceAware(true); try { XmlPullParser parser = factory.newPullParser(); parser.setInput(new InputStreamReader(inputStream)); return parser; } catch (XmlPullParserException e) { throw new SystemException(e); } } public Model readModel(XmlPullParser xpp) throws Exception { assertStartTag(xpp, Elements.MODEL); String name = xpp.getAttributeValue(ATT_NAMESPACE, Attributes.NAME); String dbId = xpp.getAttributeValue(ATT_NAMESPACE, Attributes.DBINFO); String genId = xpp.getAttributeValue(ATT_NAMESPACE, Attributes.GENERATOR); IDatabaseInfo dbinfo = adapter.getDatabaseInfo(dbId); if(dbinfo == null) { adapter.logError( ParserErrors.message( fileName, xpp.getLineNumber(), ParserErrors.errorUndefinedDbInfo, new Object[]{dbId})); dbinfo = adapter.getDefaultDatabaseInfo(); } INameGenerator generator = adapter.getNameGenerator(genId); if(generator == null) { adapter.logError( ParserErrors.message( fileName, xpp.getLineNumber(), ParserErrors.errorUndefinedGenerator, new Object[]{genId})); generator = adapter.getDefaultNameGenerator(); } Model model = new Model(name, dbinfo, generator); assertStartTag(xpp, Elements.SCHEMAS); for(xpp.nextTag(); isStartTag(xpp, Elements.SCHEMA); xpp.nextTag()) { readSchema(xpp, model); } assertStartTag(xpp, Elements.DIAGRAMS); for(xpp.nextTag(); isStartTag(xpp, Elements.DIAGRAM); xpp.nextTag()) { readDiagram(xpp, model); } endTag(xpp); for (ForeignKeyBuilder builder : foreignKeyBuilders) { builder.buildForeignKey(model); } //building dforeignkeys for (TmpDForeignKey tmpDforeignKey : tmpDForeignKeyList) { ForeignKey foreignKey = null; //searching foreignKey in table for (ForeignKey fk : tmpDforeignKey.getDtable().getTable().getForeignKeys()) { if (fk.getName().equals(tmpDforeignKey.getForeignKeyName())) { foreignKey = fk; break; } } if (foreignKey != null) { DForeignKey dForeignKey = new DForeignKey(foreignKey); dForeignKey.setSourceEdge(tmpDforeignKey.getSourceEdge()); dForeignKey.setSourceSlot(tmpDforeignKey.getSourceSlot()); dForeignKey.setSourceValid(true); dForeignKey.setTargetEdge(tmpDforeignKey.getTargetEdge()); dForeignKey.setTargetSlot(tmpDforeignKey.getTargetSlot()); dForeignKey.setTargetValid(true); tmpDforeignKey.getDtable().addDForeignKey(dForeignKey); } } return model; } private void readSchema(XmlPullParser xpp, Model model) throws Exception { String catalogName = xpp.getAttributeValue(ATT_NAMESPACE, Attributes.CATALOG); String name = xpp.getAttributeValue(ATT_NAMESPACE, Attributes.NAME); Schema schema = new Schema(catalogName, name, model.getDatabaseInfo()); for(xpp.nextTag(); isStartTag(xpp, Elements.TABLE); xpp.nextTag()) { readTable(xpp, schema); } model.addSchema(schema); } private void readTable(XmlPullParser xpp, Schema schema) throws Exception { String tableName = xpp.getAttributeValue(ATT_NAMESPACE, Attributes.NAME); Table table = new Table(schema, tableName); String tableType = xpp.getAttributeValue(ATT_NAMESPACE, Attributes.TYPE); if(tableType != null) table.setType(tableType); xpp.nextTag(); while(isStartTag(xpp, Elements.COLUMN)) { readColumn(xpp, table); xpp.nextTag(); } if(isStartTag(xpp, Elements.PRIMARY_KEY)) { readPrimaryKey(xpp, table); xpp.nextTag(); } while(isStartTag(xpp, Elements.FOREIGN_KEY)) { readForeignKey(xpp, table); xpp.nextTag(); } while(isStartTag(xpp, Elements.INDEX)) { readIndex(xpp, table); xpp.nextTag(); } while(isStartTag(xpp, Elements.UNIQUE)) { readUniqueConstraint(xpp, table); xpp.nextTag(); } while(isStartTag(xpp, Elements.CHECK)) { readCheckConstraint(xpp, table); xpp.nextTag(); } if (isStartTag(xpp, Elements.COMMENT)) { xpp.next(); if (!isEndTag(xpp)) { table.setComment(xpp.getText()); xpp.getName(); endTag(xpp); } xpp.nextTag(); } if (isStartTag(xpp, Elements.DESCRIPTION)) { xpp.next(); if (!isEndTag(xpp)) { table.setDescription(xpp.getText()); endTag(xpp); } xpp.nextTag(); } } private void readCheckConstraint(XmlPullParser xpp, Table table) throws Exception { String name = xpp.getAttributeValue(ATT_NAMESPACE, Attributes.NAME); String expression = ""; assertStartTag(xpp, Elements.EXPRESSION); xpp.next(); if (!isEndTag(xpp)) { expression = xpp.getText(); endTag(xpp); } xpp.nextTag(); table.addCheckConstraint(new CheckConstraint(name, expression, table)); } private void readUniqueConstraint(XmlPullParser xpp, Table table) throws Exception { String name = xpp.getAttributeValue(ATT_NAMESPACE, Attributes.NAME); List<Column> columns = new ArrayList<Column>(); for(xpp.nextTag(); isStartTag(xpp, Elements.COLUMN_REF); xpp.nextTag()) { String colName = xpp.getAttributeValue(ATT_NAMESPACE, Attributes.NAME); Column column = table.getColumn(colName); if(colName != null) columns.add(column); endTag(xpp); } Column[] cols = (Column[])columns.toArray(new Column[columns.size()]); table.addUniqueConstraint(new UniqueConstraint(name, cols, table)); } private void readColumn(XmlPullParser xpp, Table table) throws Exception { String columnName = xpp.getAttributeValue(ATT_NAMESPACE, Attributes.NAME); String typeName = xpp.getAttributeValue(ATT_NAMESPACE, Attributes.TYPE); Boolean nullable = Boolean.valueOf(xpp.getAttributeValue(ATT_NAMESPACE, Attributes.NULLABLE)); IDataType dataType = table.getSchema().getDatabaseInfo().getDataType(typeName); if(dataType == null) { adapter.logError( ParserErrors.message( fileName, xpp.getLineNumber(), ParserErrors.errorUndefinedType, new Object[]{typeName})); dataType = table.getSchema().getDatabaseInfo().getDefaultDataType(); } String sz = xpp.getAttributeValue(ATT_NAMESPACE, Attributes.SIZE); String sc = xpp.getAttributeValue(ATT_NAMESPACE, Attributes.SCALE); String cust = xpp.getAttributeValue(ATT_NAMESPACE, Attributes.EXTRA); if(sz != null && dataType.acceptsSize()) { long size = Long.parseLong(sz); dataType.setSize(size); } if(sc != null && dataType.acceptsScale()) { int scale = Integer.parseInt(sc); dataType.setScale(scale); } if(cust != null&& dataType.hasExtra()) { dataType.setExtra(cust); } String defaultValue = null, comment = null; xpp.nextTag(); if(isStartTag(xpp, Elements.DEFAULT)) { xpp.next(); defaultValue = xpp.getText(); endTag(xpp); xpp.nextTag(); } if(isStartTag(xpp, Elements.COMMENT)) { xpp.next(); comment = xpp.getText(); endTag(xpp); xpp.nextTag(); } new Column( table, columnName, dataType, nullable.booleanValue(), defaultValue, comment); } private void readPrimaryKey(XmlPullParser xpp, Table table) throws Exception { String pkName = xpp.getAttributeValue(ATT_NAMESPACE, Attributes.NAME); List<String> colRefs = new ArrayList<String>(); for(xpp.nextTag(); isStartTag(xpp, Elements.COLUMN_REF); xpp.nextTag()) { colRefs.add(xpp.getAttributeValue(ATT_NAMESPACE, Attributes.NAME)); endTag(xpp); } new PrimaryKey( pkName, colRefs.toArray(new String[colRefs.size()]), table); } private void readForeignKey(XmlPullParser xpp, Table table) throws Exception { String fkName = xpp.getAttributeValue(ATT_NAMESPACE, Attributes.NAME); String deleteRule = xpp.getAttributeValue(ATT_NAMESPACE, Attributes.DELETE_RULE); String updateRule = xpp.getAttributeValue(ATT_NAMESPACE, Attributes.UPDATE_RULE); assertStartTag(xpp, Elements.TARGET); String schemaName = xpp.getAttributeValue(ATT_NAMESPACE, Attributes.SCHEMA); String tableName = xpp.getAttributeValue(ATT_NAMESPACE, Attributes.TABLE); endTag(xpp); List<String> colRefs = new ArrayList<String>(); for(xpp.nextTag(); isStartTag(xpp, Elements.COLUMN_REF); xpp.nextTag()) { colRefs.add(xpp.getAttributeValue(ATT_NAMESPACE, Attributes.NAME)); endTag(xpp); } foreignKeyBuilders.add(new ForeignKeyBuilder( fkName, colRefs.toArray(new String[colRefs.size()]), table, schemaName, tableName, deleteRule, updateRule)); } private void readIndex(XmlPullParser xpp, Table table) throws Exception { String indexName = xpp.getAttributeValue(ATT_NAMESPACE, Attributes.NAME); Boolean unique = Boolean.valueOf(xpp.getAttributeValue(ATT_NAMESPACE, Attributes.UNIQUE)); List<String> colRefs = new ArrayList<String>(); for(xpp.nextTag(); isStartTag(xpp, Elements.COLUMN_REF); xpp.nextTag()) { colRefs.add(xpp.getAttributeValue(ATT_NAMESPACE, Attributes.NAME)); endTag(xpp); } new Index( indexName, colRefs.toArray(new String[colRefs.size()]), table, unique.booleanValue(), null); //TODO V1: read ascdesc values } private void readDiagram(XmlPullParser xpp, Model model) throws Exception { String diagramName = xpp.getAttributeValue(ATT_NAMESPACE, Attributes.NAME); String schemaName = xpp.getAttributeValue(ATT_NAMESPACE, Attributes.SCHEMA); Schema defaultSchema = model.getSchema(schemaName); if(defaultSchema == null) { adapter.logWarning( ParserErrors.message( fileName, xpp.getLineNumber(), ParserErrors.warnUndefinedSchemaInDiagram, new Object[]{schemaName})); defaultSchema = new Schema(schemaName, model.getDatabaseInfo()); model.addSchema(defaultSchema); if(listener != null) listener.elementAdded(defaultSchema); } Diagram diagram = new Diagram(model, diagramName, defaultSchema); for(xpp.nextTag(); isStartTag(xpp, Elements.TABLE_REF); xpp.nextTag()) { readDTable(xpp, diagram); } } private void readDTable(XmlPullParser xpp, Diagram diagram) throws Exception { String schemaName = xpp.getAttributeValue(ATT_NAMESPACE, Attributes.SCHEMA); String tableName =xpp.getAttributeValue(ATT_NAMESPACE, Attributes.NAME); Boolean collapsed = Boolean.valueOf( xpp.getAttributeValue(ATT_NAMESPACE, Attributes.COLLAPSED)); xpp.nextTag(); Point location = null; if(isStartTag(xpp, Elements.LOCATION)) { int x = Integer.parseInt(xpp.getAttributeValue(ATT_NAMESPACE, Attributes.X)); int y = Integer.parseInt(xpp.getAttributeValue(ATT_NAMESPACE, Attributes.Y)); location = new Point(x, y); xpp.nextTag(); xpp.nextTag(); } Table table = null; Schema schema = diagram.getModel().getSchema(schemaName); if(schema != null) { table = schema.getTable(tableName); if(table == null) { adapter.logError( ParserErrors.message( fileName, xpp.getLineNumber(), ParserErrors.errorUndefinedTable, new Object[]{tableName})); } } else { adapter.logError( ParserErrors.message( fileName, xpp.getLineNumber(), ParserErrors.errorUndefinedSchema, new Object[]{schemaName})); } if(table != null) { DTable dtable = new DTable(table, location); dtable.setCollapsed(collapsed.booleanValue()); diagram.addTable(dtable); readDForeignKeys(xpp, dtable); } } private void readDForeignKeys (XmlPullParser xpp, DTable dtable) throws Exception{ int sourceEdge=0, sourceSlot=0; int targetEdge=0, targetSlot=0; String foreignKeyName; while (isStartTag(xpp, Elements.FOREIGN_KEY_REF)) { foreignKeyName = xpp.getAttributeValue(ATT_NAMESPACE, Attributes.NAME); xpp.nextTag(); if (isStartTag(xpp, Elements.SOURCE)) { sourceEdge = Integer.parseInt(xpp.getAttributeValue(ATT_NAMESPACE, Attributes.EDGE)); sourceSlot = Integer.parseInt(xpp.getAttributeValue(ATT_NAMESPACE, Attributes.SLOTNUMBER)); xpp.nextTag(); //endTag xpp.nextTag(); //startTag } if (isStartTag(xpp, Elements.TARGET)) { targetEdge = Integer.parseInt(xpp.getAttributeValue(ATT_NAMESPACE, Attributes.EDGE)); targetSlot = Integer.parseInt(xpp.getAttributeValue(ATT_NAMESPACE, Attributes.SLOTNUMBER)); xpp.nextTag(); xpp.nextTag(); } tmpDForeignKeyList.add(new TmpDForeignKey(dtable, foreignKeyName, sourceSlot, sourceEdge, targetSlot, targetEdge)); //read close tag of foreignkey_ref xpp.nextTag(); } } private boolean isStartTag(XmlPullParser xpp, String name) throws Exception { return xpp.getEventType() == XmlPullParser.START_TAG && isNamespace(xpp.getNamespace()) && name.equals(xpp.getName()); } private boolean isNamespace(String namespace) { return NAMESPACE.equals(namespace) || NAMESPACE_OLD.equals(namespace); } private boolean isEndTag(XmlPullParser xpp) throws Exception { return xpp.getEventType() == XmlPullParser.END_TAG; } private void endTag(XmlPullParser xpp) throws Exception { if(xpp.nextTag() != XmlPullParser.END_TAG){ throw new SystemException( ParserErrors.message( fileName, xpp.getLineNumber(), ParserErrors.endTagExpected, null)); } } private void assertStartTag(XmlPullParser xpp, String tag) throws Exception { if(xpp.nextTag() != XmlPullParser.START_TAG) throw new SystemException( ParserErrors.message( fileName, xpp.getLineNumber(), ParserErrors.startTagExpected, null)); if(!(isNamespace(xpp.getNamespace()) && tag.equals(xpp.getName()))) throw new SystemException( ParserErrors.message( fileName, xpp.getLineNumber(), ParserErrors.tagExpected, new Object[]{tag, xpp.getName()})); } private class ForeignKeyBuilder { private final String keyName; private final String[] columnNames; private final Table owningTable; private final String targetSchema; private final String targetTable; private final String deleteRule; private final String updateRule; public ForeignKeyBuilder( String name, String[] columns, Table table, String targetSchema, String targetTable, String deleteRule, String updateRule) { this.keyName = name; this.columnNames = columns; this.owningTable = table; this.targetSchema = targetSchema; this.targetTable = targetTable; this.deleteRule = deleteRule; this.updateRule = updateRule; } void buildForeignKey(Model model) { Schema schema = model.getSchema(targetSchema); if(schema == null) { RMBenchPlugin.logError("Target Schema ("+targetSchema+") does not exist"); return; } Table table = schema.getTable(targetTable); if(table == null) { RMBenchPlugin.logError("Target table ("+targetTable+") does not exist"); return; } IForeignKey.Action deleteAction = null; if(deleteRule != null) { deleteAction = model.getDatabaseInfo().getForeignKeyAction(deleteRule); if(deleteAction == null) { RMBenchPlugin.logError("delete action ("+deleteRule+"(not supported"); return; } } IForeignKey.Action updateAction = null; if(updateRule != null) { updateAction = model.getDatabaseInfo().getForeignKeyAction(updateRule); if(updateAction == null) { RMBenchPlugin.logError("update action ("+updateRule+"(not supported"); return; } } new ForeignKey(keyName, columnNames, owningTable, table, deleteAction, updateAction); } } private class TmpDForeignKey { private DTable dtable; private String foreignKeyName; private int sourceSlot; private int sourceEdge; private int targetSlot; private int targetEdge; /** * @param dtable * @param foreignKeyName * @param sourceSlot * @param sourceEdge * @param targetSlot * @param targetEdge */ public TmpDForeignKey(DTable dtable, String foreignKeyName, int sourceSlot, int sourceEdge, int targetSlot, int targetEdge) { this.dtable = dtable; this.foreignKeyName = foreignKeyName; this.sourceSlot = sourceSlot; this.sourceEdge = sourceEdge; this.targetSlot = targetSlot; this.targetEdge = targetEdge; } public DTable getDtable() { return dtable; } public String getForeignKeyName() { return foreignKeyName; } public int getSourceEdge() { return sourceEdge; } public int getSourceSlot() { return sourceSlot; } public int getTargetEdge() { return targetEdge; } public int getTargetSlot() { return targetSlot; } } public static void main(String[] args) throws Exception { InputStream inStream = new FileInputStream("test1.rbm"); Model model = ModelReader.read(inStream, "test1.rbm", new Adapter() { public IDatabaseInfo getDatabaseInfo(String infoName) { return new SQL99(); } public void logError(String message) { System.out.println(message); } public IDatabaseInfo getDefaultDatabaseInfo() { return new SQL99(); } }, null); System.out.println("done reading model "+model.getName()); } }
package com.demo.controllers; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.validation.Valid; import org.hibernate.Session; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.repository.query.Param; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.demo.entity.Product; import com.demo.entity.User; import com.demo.service.UserService; import com.sun.xml.bind.v2.runtime.Name; @Controller public class UserController { @Autowired private UserService userService; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; @RequestMapping("/registr") public String registr(Map<String, Object> model, HttpSession session) { session.removeAttribute("username"); session.removeAttribute("password"); User customer = new User(); model.put("registr", customer); return "registr"; } @RequestMapping(value = "/saveRegistr", method = RequestMethod.POST) public String saveRegistr(@Valid @ModelAttribute("registr") User user, BindingResult result, RedirectAttributes redirect) { if (result.hasErrors()) { return "registr"; } else { List<User> list = userService.listAll(); for (User x : list) { if (user.getUsername().equals(x.getUsername())) { redirect.addFlashAttribute("message", "Tài khoản này đã tồn tại"); userService.save(user); return "redirect:/registr"; } else { continue; } } user.setPassword(bCryptPasswordEncoder.encode(user.getPassword())); redirect.addFlashAttribute("message", "Đăng kí tài khoản thành công"); userService.save(user); return "redirect:/login"; } } @RequestMapping("/login") public String login() { return "login"; } @RequestMapping(value = "/checklogin", method = RequestMethod.POST) public String checklogin(ModelMap modelMap, @RequestParam("username") String username, @RequestParam("password") String password, HttpSession session) { List<User> list = userService.listAll(); for (User x : list) { if (username.equals(x.getUsername())) { if (bCryptPasswordEncoder.matches(password, x.getPassword())) { session.setAttribute("name", username); session.removeAttribute("username"); session.removeAttribute("password"); return "redirect:/listproduct"; } else { session.setAttribute("username", username); session.setAttribute("password", username); modelMap.addAttribute("message", "Bạn nhập sai mật khẩu"); return "login"; } } else { continue; } } session.setAttribute("username", username); session.setAttribute("password", username); modelMap.addAttribute("message", "Tài khoản " + username + " không tồn tại"); return "login"; } @RequestMapping("/logout") public String logout(HttpSession session) { session.removeAttribute("name"); return "redirect:/login"; } }
package com.lingnet.vocs.service.reported; import java.util.Map; import com.lingnet.common.service.BaseService; import com.lingnet.util.Pager; import com.lingnet.vocs.entity.Demand; public interface DemandService extends BaseService<Demand, String> { public String getListData(Pager pager, String status); public String saveOrUpdate(Demand demand, String griddata, String griddata2, String jbxx, Map<String, String> s,String threadId,String threadId1,String threadId2) throws Exception; public String getContactListData(String id); }
package thread_pattern.event_driven_modle.demo; import thread_pattern.event_driven_modle.EventListener; /** * @ClassName: UserLoginEventListener * @Description: 样例事件监听器(用于演示使用) * @Author: liulianglin * @DateTime 2022年4月21日 下午3:36:17 */ public class UserLoginEventListener implements EventListener<UserLoginEvent> { @Override public void handleEvent(UserLoginEvent event) { System.out.println("开始处理" + event.getEvtType() + "事件, 当前登陆用户名称=" + event.getUserName()); } }
package gdut.ff.generator; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.sql.Connection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; import gdut.ff.generator.jdbc.DataSourceConnect; import gdut.ff.generator.util.PropertyUtil; import gdut.ff.generator.util.StringUtil; /** * @author liuffei * @date 2018-03-28 * @description */ public class TestDynamicGenerator { public DataSourceConnect conn = new DataSourceConnect(); /** * 查询全部的数据库表 */ public void testQueryAllTables() { List<String> list = conn.QueryAllTable(); if(null != list && list.size() > 0) { for(int i = 0;i < list.size();i++) { System.out.println(list.get(i)); } } } @Test public void testConnection() { Connection connection = new DataSourceConnect ().getConnect(); System.out.println(connection); } /** * 查询全部的字段 */ public void testQueryColumn() { List<Map<String,Object>> list = conn.queryColumn("user","blog"); if(null != list && list.size() > 0) { for(int i = 0;i < list.size();i++) { Map<String,Object> column = list.get(i); for(Map.Entry<String, Object> entry:column.entrySet()) { System.out.print(entry.getKey()+"-->"+entry.getValue()+" "); } System.out.println(""); } } } /** * 测试生成实体 */ @Test public void testDomain() { String dataBaseName = conn.getDatabaseName(); Configuration cfg = new Configuration(); try { String path = PropertyUtil.PROJECT_PATH + PropertyUtil.BASE_PATH; cfg.setDirectoryForTemplateLoading(new File(path+PropertyUtil.BASE_TEMPLATE_PATH)); cfg.setObjectWrapper(new DefaultObjectWrapper()); //Domain Template template = cfg.getTemplate(PropertyUtil.DOMAIN_TEMPLATE_NAME); //查询出全部的表 List<String> list = conn.QueryAllTable(); if(null != list && list.size() > 0) { for(int i = 0;i < list.size();i++) { //类名 String className = StringUtil.tableNameToClassName(list.get(i)); Writer out = new OutputStreamWriter(new FileOutputStream(new File(System.getProperty("user.dir")+"/src/main/java"+"/"+StringUtil.formatPathName(PropertyUtil.DOMAIN_PACKAGE)+"/"+className+".java")),"UTF-8"); List<Map<String, Object>> columns = conn.queryColumn(list.get(i),dataBaseName); Map<String,Object> data = new HashMap<String,Object>(); data.put("columns", columns); data.put("className", className); data.put("tableName", list.get(i)); data.put("domainPackage", PropertyUtil.DOMAIN_PACKAGE); template.process(data,out); out.flush(); } } } catch (Exception e) { e.printStackTrace(); } } /** * 测试生成Repository */ @Test public void testRepositoryGenerator() { String dataBaseName = conn.getDatabaseName(); Configuration cfg = new Configuration(); try { String path = PropertyUtil.PROJECT_PATH + PropertyUtil.BASE_PATH; cfg.setDirectoryForTemplateLoading(new File(path+PropertyUtil.BASE_TEMPLATE_PATH)); cfg.setObjectWrapper(new DefaultObjectWrapper()); Template template = cfg.getTemplate(PropertyUtil.MAPPER_TEMPLATE_NAME); List<String> list = conn.QueryAllTable(); if(null != list && list.size() > 0) { for(int i = 0;i < list.size();i++) { String className = StringUtil.tableNameToClassName(list.get(i)); Writer out = new OutputStreamWriter(new FileOutputStream(new File(path+"/"+StringUtil.formatPathName(PropertyUtil.MAPPER_PACKAGE)+"/"+className+"Repository.java")),"UTF-8"); List<Map<String, Object>> columns = conn.queryColumn(list.get(i),dataBaseName); Map<String,Object> data = new HashMap<String,Object>(); data.put("columns", columns); data.put("className", className); data.put("repositoryPackage", PropertyUtil.MAPPER_PACKAGE); data.put("domainPackage", PropertyUtil.DOMAIN_PACKAGE); data.put("tableName", list.get(i)); template.process(data,out); out.flush(); } } } catch (Exception e) { e.printStackTrace(); } } /** * 测试生成Service */ @Test public void testServiceGenerator() { String dataBaseName = conn.getDatabaseName(); Configuration cfg = new Configuration(); try { String path = PropertyUtil.PROJECT_PATH + PropertyUtil.BASE_PATH; cfg.setDirectoryForTemplateLoading(new File(path+PropertyUtil.BASE_TEMPLATE_PATH)); cfg.setObjectWrapper(new DefaultObjectWrapper()); Template template = cfg.getTemplate(PropertyUtil.SERVICE_TEMPLATE_NAME); List<String> list = conn.QueryAllTable(); if(null != list && list.size() > 0) { for(int i = 0;i < list.size();i++) { String className = StringUtil.tableNameToClassName(list.get(i)); Writer out = new OutputStreamWriter(new FileOutputStream(new File(path+"/"+StringUtil.formatPathName(PropertyUtil.SERVICE_PACKAGE)+"/"+className+"Service.java")),"UTF-8"); List<Map<String, Object>> columns = conn.queryColumn(list.get(i),dataBaseName); Map<String,Object> data = new HashMap<String,Object>(); data.put("columns", columns); data.put("className", className); data.put("beanName", className.substring(0,1).toLowerCase().concat(className).substring(1)); data.put("servicePackage", PropertyUtil.SERVICE_PACKAGE); data.put("tableName", list.get(i)); data.put("repositoryPackage", PropertyUtil.MAPPER_PACKAGE); data.put("domainPackage", PropertyUtil.DOMAIN_PACKAGE); template.process(data,out); out.flush(); } } } catch (Exception e) { e.printStackTrace(); } } /** * 测试生成Controller */ @Test public void testControllerGenerator() { String dataBaseName = conn.getDatabaseName(); Configuration cfg = new Configuration(); try { String path = PropertyUtil.PROJECT_PATH + PropertyUtil.BASE_PATH; cfg.setDirectoryForTemplateLoading(new File(path+PropertyUtil.BASE_TEMPLATE_PATH)); cfg.setObjectWrapper(new DefaultObjectWrapper()); Template template = cfg.getTemplate(PropertyUtil.CONTROLLER_TEMPLATE_NAME); List<String> list = conn.QueryAllTable(); if(null != list && list.size() > 0) { for(int i = 0;i < list.size();i++) { String className = StringUtil.tableNameToClassName(list.get(i)); Writer out = new OutputStreamWriter(new FileOutputStream(new File(path+"/"+StringUtil.formatPathName(PropertyUtil.CONTROLLER_PACKAGE)+"/"+className+"RestController.java")),"UTF-8"); List<Map<String, Object>> columns = conn.queryColumn(list.get(i),dataBaseName); Map<String,Object> data = new HashMap<String,Object>(); data.put("columns", columns); data.put("className", className); data.put("beanName", className.substring(0,1).toLowerCase().concat(className).substring(1)); data.put("servicePackage", PropertyUtil.SERVICE_PACKAGE); data.put("tableName", list.get(i)); data.put("repositoryPackage", PropertyUtil.MAPPER_PACKAGE); data.put("domainPackage", PropertyUtil.DOMAIN_PACKAGE); data.put("controllerPackage", PropertyUtil.CONTROLLER_PACKAGE); data.put("application", PropertyUtil.APPLICATION); template.process(data,out); out.flush(); } } } catch (Exception e) { e.printStackTrace(); } } @Test public void testPath() throws ClassNotFoundException { String classPath = this.getClass().getResource("/").getPath(); System.out.println(System.getProperty("user.dir")); } }
package laioffer.June24th; import common.ListNode; /** * Created by mengzhou on 6/24/17. */ public class PartitionLinkedList { public static ListNode partition(ListNode head, int target) { ListNode dummy = new ListNode(-1); ListNode cur = new ListNode(-1); ListNode headA = dummy, headB = cur; while (head != null) { ListNode temp = head.next; if(head.val < target) { headA.next = head; headA = headA.next; } else { headB.next = head; headB = headB.next; } head.next = null; head = temp; } headA.next = cur.next; return dummy.next; } public static void main(String[] args) { System.out.println(Math.round(3.5)); // Utils.printListNode(partition(Utils.buildListNode(new int[]{2,4,3,4,5,1}), 4)); } }
package com.ha.cn.service.impl; import com.baomidou.mybatisplus.plugins.Page; import com.baomidou.mybatisplus.plugins.pagination.Pagination; import com.baomidou.mybatisplus.service.impl.ServiceImpl; import com.ha.cn.dao.AbVoltageMapper; import com.ha.cn.model.AbVoltage; import com.ha.cn.service.IAbVoltageService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * * AbVoltage 表数据服务层接口实现类 * */ @Service public class AbVoltageServiceImpl extends ServiceImpl<AbVoltageMapper, AbVoltage> implements IAbVoltageService { }
package com.habiture; /** * Created by Yeh on 2015/5/24. */ public class NetworkException extends RuntimeException{ public NetworkException() { } public NetworkException(String detailMessage) { super(detailMessage); } public NetworkException(String detailMessage, Throwable throwable) { super(detailMessage, throwable); } public NetworkException(Throwable throwable) { super(throwable); } }
package com.shravya.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.shravya.daoimpl.CategoryDaoImpl; import com.shravya.daoimpl.TestSessionFactory; import com.shravya.model.Category; @Controller public class AddCategory { @Autowired TestSessionFactory tsf; @Autowired CategoryDaoImpl c; @RequestMapping("/category") public ModelAndView goToCategoryForm() { ModelAndView mv=new ModelAndView("category"); mv.addObject("cat",new Category()); mv.addObject("buttonName","Add Category"); return mv; } @RequestMapping(value="/addCat",method=RequestMethod.POST) public ModelAndView recieveCategoryFormData(@ModelAttribute ("cat") Category ca) { System.out.println(ca.getCategoryName()); System.out.println(ca.getCategoryDescription()); ModelAndView modelAndView=new ModelAndView("home"); //modelAndView.addObject("cat",new Category()); //modelAndView.addObject("buttonName","Add Category"); c.saveCategory(ca); return modelAndView; } }
package com.gxuwz.attend.dao; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import org.hibernate.Query; import com.gxuwz.attend.entity.*; public class CourseDaoimp extends BaseDao implements CourseDao { /** * 查看全部 */ @Override public List<Course> findAll(String id) { List<Course> result = new ArrayList<>(); String hql="from Course where teacherId=?"; Query query=getSession().createQuery(hql); query.setString(0, id); List<Course> tempList = query.list(); tempList.forEach(v->{ Course temp = v; Query querys = getSession().createQuery("from Teacher where teaId = ?"); querys.setString(0, id); temp.setTeacher((Teacher)querys.list().get(0)); result.add(temp); }); return result; } /** * 删除 */ @Override public void delete(Course course){ getSession().delete(course);; } /*** * 查看单个 */ @Override public Course get(Course course){ String hql="from Course where courseId=? and teacherId=?"; System.out.println(course.getCourseId()); System.out.println(course.getTeacherId()); Query query=getSession().createQuery(hql); query.setString(0, course.getCourseId()); query.setString(1, course.getTeacherId()); List list= query.list(); if(!list.isEmpty()){ return (Course)list.get(0); } else{ return null;} } /** * 通过课程ID查询 * @param tid * @return */ public boolean get(String courseId){ String hql="from Course where courseId=?"; Query query=getSession().createQuery(hql); query.setString(0, courseId); List list= query.list(); if(!list.isEmpty()){ return false; } else{ return true;} } public List getbycid(String courseId){ String hql="from Course where courseId=?"; Query query=getSession().createQuery(hql); query.setString(0, courseId); return query.list(); } @Override public void update(Course course){ getSession().update(course); } @Override public void save(Course course){ getSession().save(course); } }
package VSMSICKEmbeddedFeatureVecs; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.LinkedHashMap; import VSMConstants.VSMContant; import VSMSerialization.VSMFeatureVectorBeanEmbedded; public class SerializeEmbeddedBean { public static void serializeVectorBean(EmbeddedVectorBean vectorBean, String sentence, String serName) { File file = null; file = new File(VSMContant.SICK_EMBEDDED_CHUNK_VECS + "/" + sentence + "/" + vectorBean.getLabel()); if (file != null) { if (!file.exists()) { file.mkdirs(); } String filename = file.getAbsolutePath() + "/" + serName; FileOutputStream fos = null; ObjectOutputStream out = null; try { fos = new FileOutputStream(filename, false); out = new ObjectOutputStream(fos); out.writeObject(vectorBean); out.close(); fos.close(); } catch (IOException ex) { System.err.println("***File name too large***"); } } } }
package com.dezzmeister.cryptopix.main.exceptions; /** * An exception to be thrown when a file cannot be encoded because the constructed secret package * is larger than the carrier image. * * @author Joe Desmond * @since 1.0.0 */ public class SizeLimitExceededException extends Exception { /** * Creates a SizeLimitExceededException with the given message. * * @param message message */ public SizeLimitExceededException(final String message) { super(message); } }
package pl.com.garage.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class AppController { @RequestMapping(value = "showEmployeeMenu.html") // adres taki jak jest w indexie public ModelAndView showEmployeeMenu(){ return new ModelAndView("employeeViews/employeeMenu"); //scieżka, nazwa folderu/nazwa klasy } @RequestMapping(value = "showClientMenu.html") public ModelAndView showClientMenu(){ return new ModelAndView("clientViews/clientMenu"); } }
/* * 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 proyectofinalpoo; import javax.swing.table.DefaultTableModel; /** * * @author Administrador */ public class JFMCREDITO extends javax.swing.JFrame { /** * Creates new form JFMCREDITO */ public JFMCREDITO() { initComponents(); setLocationRelativeTo(null); } /** * 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() { jLabel1 = new javax.swing.JLabel(); JLBNOMBRECLIENTE = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); JBTIPO = new javax.swing.JComboBox<>(); JLBTARJETA = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); JTTABLE = new javax.swing.JTable(); jLabel3 = new javax.swing.JLabel(); JLBTOTAL = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); JTXNUMEROTARJETA = new javax.swing.JTextField(); jButton2 = new javax.swing.JButton(); JBRegresar = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel1.setText("Nombre Cliente:"); getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 30, 117, 57)); getContentPane().add(JLBNOMBRECLIENTE, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 30, 330, 50)); jLabel2.setText("Seleccione Tipo de Tarjeta :"); getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 150, 170, 30)); JBTIPO.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Tarjeta de Debito", "Tarjeta de Credito" })); getContentPane().add(JBTIPO, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 150, 280, 30)); JLBTARJETA.setText("Numero de Tajeta de credito: "); getContentPane().add(JLBTARJETA, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 220, 170, 30)); JTTABLE.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Cliente", "Tipo Tarjeta", "Numero", "Total a Pagar" } )); jScrollPane1.setViewportView(JTTABLE); getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 260, 520, 140)); jLabel3.setText("Total a Pagar:"); getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 90, 120, 30)); getContentPane().add(JLBTOTAL, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 90, 320, 40)); jButton1.setText("Regresar "); getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 430, 120, 40)); getContentPane().add(JTXNUMEROTARJETA, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 220, 280, 30)); jButton2.setText("Agregar"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 430, 120, 40)); JBRegresar.setText("Regresar"); JBRegresar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { JBRegresarActionPerformed(evt); } }); getContentPane().add(JBRegresar, new org.netbeans.lib.awtextra.AbsoluteConstraints(380, 430, 120, 40)); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed String nombre=JLBNOMBRECLIENTE.getText(); String total=JLBTOTAL.getText(); String tipo= JBTIPO.getSelectedItem().toString(); String Numero=JTXNUMEROTARJETA.getText(); Imprimir(nombre,total,tipo,Numero); }//GEN-LAST:event_jButton2ActionPerformed private void JBRegresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBRegresarActionPerformed dispose(); }//GEN-LAST:event_JBRegresarActionPerformed private void Imprimir(String nombre,String total,String tipo,String numero){ DefaultTableModel modelo=(DefaultTableModel) JTTABLE.getModel(); //Sección 2 Object [] fila=new Object[4]; //Sección 3 fila[0]=nombre; fila[1]=total; fila[2]=tipo; fila[3]=numero; //Sección 4 modelo.addRow(fila); //Sección 5 JTTABLE.setModel(modelo); } /** * @param args the command line arguments */ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton JBRegresar; private javax.swing.JComboBox<String> JBTIPO; public static javax.swing.JLabel JLBNOMBRECLIENTE; private javax.swing.JLabel JLBTARJETA; public static javax.swing.JLabel JLBTOTAL; private javax.swing.JTable JTTABLE; private javax.swing.JTextField JTXNUMEROTARJETA; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JScrollPane jScrollPane1; // End of variables declaration//GEN-END:variables }
import java.util.*; abstract class Vehicle { protected ArrayList<ParkingSpot> parkingSpots = new ArrayList<>(); protected String licensePlate; protected int spotsNeeded; protected VehicleSize vehicleSize; public int getSpotsNeeded() { return spotsNeeded; } public VehicleSize getVehicleSize() { return vehicleSize; } public void parkInSpot(ParkingSpot parkingSpot) { parkingSpots.add(parkingSpot); } public void clearSpots() { for (ParkingSpot parkingSpot : parkingSpots) { parkingSpot.removeVehicle(); } parkingSpots.clear(); } public abstract boolean canFitInSpot(ParkingSpot parkingSpot); public abstract void print(); }
package com.example.myapplication; import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.OnConflictStrategy; import androidx.room.Query; import java.util.List; @Dao public interface TaskDao { @Insert(onConflict = OnConflictStrategy.IGNORE) void insert(Task task); @Query("DELETE FROM task_table") void deleteAll(); @Delete void deleteTask(Task task); @Query("SELECT * from task_table ORDER BY task ASC") LiveData<List<Task>> getAllTasks(); @Query("SELECT * from task_table LIMIT 1") Task[] getAnyTask(); @Query("SELECT * from task_table WHERE task IN(:taskName)") Task[] getMatchedTasksByName(String taskName); @Query("UPDATE task_table SET task = :taskName WHERE ID = :taskID") void updateName(int taskID, String taskName); @Query("UPDATE task_table SET weight = :taskWeight WHERE ID = :taskID") void updateWeight(int taskID, String taskWeight); @Query("UPDATE task_table SET type = :taskType WHERE ID = :taskID") void updateType(int taskID, String taskType); @Query("UPDATE task_table SET notes = :taskNotes WHERE ID = :taskID") void updateNotes(int taskID, String taskNotes); @Query("UPDATE task_table SET completion_status = :taskStatus where ID = :taskID") void updateCompletionStatus(int taskID, boolean taskStatus); }
package com.szcinda.express.dto; import com.szcinda.express.RoleType; import lombok.Data; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @Data public class UserIdentity implements Serializable { private String id; private String account; private String password; private String token; private RoleType role; private List<String> permissions = new ArrayList<>(); public UserIdentity(String id, String account, String password, RoleType role) { this.id = id; this.account = account; this.password = password; this.role = role; } public void setAdminPermissions() { this.permissions.addAll(Arrays.asList("feeApproval","financialReport","user")); } }
package net.coatli.java; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.runtime.RuntimeConstants; import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class VelocityJavaCodeApplication { private static final Logger LOGGER = LoggerFactory.getLogger(VelocityJavaCodeApplication.class); public static void main(final String[] args) { final StringWriter sw = new StringWriter(); LOGGER.info("Generating JavaBeans for Model with Velocity"); final VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); final VelocityContext context = new VelocityContext(); context.put("package", "net.coatli.java"); context.put("class", getJavaBeanDefinition()); ve.getTemplate("javabean.vm").merge(context, sw); LOGGER.info("Output: {}", sw); } private static Map<String, Object> getJavaBeanDefinition() { final Map<String, Object> classDefinition = new HashMap<>(); final Map<String, Object> propertiesDefinition = new HashMap<>(); final Map<String, Object> keyDefinition = new HashMap<>(); final Map<String, Object> nameDefinition = new HashMap<>(); final Map<String, Object> ageDefinition = new HashMap<>(); keyDefinition.put("name", "key"); keyDefinition.put("type", "String"); nameDefinition.put("name", "name"); nameDefinition.put("type", "String"); ageDefinition.put("name", "age"); ageDefinition.put("type", "Integer"); propertiesDefinition.put("key", keyDefinition); propertiesDefinition.put("name", nameDefinition); propertiesDefinition.put("age", ageDefinition); classDefinition.put("name", "Client"); classDefinition.put("properties", propertiesDefinition); return classDefinition; } }
public class Car { int year; String make; double gasCapacity; double gasLevel; double mpg; int speed; public Car(int year, String make, double gasCapacity, int speed, double mpg) { this.year = year; this.make = make; this.gasCapacity = gasCapacity; gasLevel = this.gasCapacity; this.mpg = mpg; this.speed = speed; } public int getYear() { return year; } public String getMake() { return make; } public double getGasCapacity() { return gasCapacity; } public double getGasLevel() { return gasLevel; } public double getMilesPerGallon() { return mpg; } public int getSpeed() { return speed; } public int accelerate() { getSpeed(); speed += 5; if (speed > 180) { speed = 180; } return speed; } public int brake() { getSpeed(); speed -= 5; if (speed < 0) { speed = 0; } return speed; } public double drive(int hours) { gasLevel -= speed * hours / mpg; return gasLevel; } public String toString() { getMake(); getYear(); getSpeed(); return make + ": " + year + ": " + speed; } }
package com.jim.multipos.ui.mainpospage.presenter; import com.jim.multipos.core.BasePresenterImpl; import com.jim.multipos.data.DatabaseManager; import com.jim.multipos.data.db.model.products.Product; import com.jim.multipos.ui.mainpospage.view.SearchModeView; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; /** * Created by Sirojiddin on 27.10.2017. */ public class SearchModePresenterImpl extends BasePresenterImpl<SearchModeView> implements SearchModePresenter { StringBuilder searchBuilder; boolean skuMode = true; boolean nameMode = true; boolean barcodeMode = true; List<Product> productList; String searchText = ""; @Inject DatabaseManager databaseManager; @Inject protected SearchModePresenterImpl(SearchModeView searchModeView) { super(searchModeView); searchBuilder = new StringBuilder(); } @Override public void setSkuSearchMode(boolean active) { skuMode = active; onSearchTextChange(searchText); onModeChange(); } @Override public void setNameSearchMode(boolean active) { nameMode = active; onSearchTextChange(searchText); onModeChange(); } @Override public void setBarcodeSearchMode(boolean active) { barcodeMode = active; onSearchTextChange(searchText); onModeChange(); } @Override public void onSearchTextChange(String s) { searchText = s; if (s.length() == 1) { databaseManager.getSearchProducts(s, skuMode, barcodeMode, nameMode).subscribe((products, throwable) -> { productList = products; view.setResultsList(productList, s); }); } else if (s.length() > 0) { List<Product> productsTemp = new ArrayList<>(); for (Product product : productList) { if (barcodeMode && product.getBarcode().toUpperCase().contains(s.toUpperCase())) { productsTemp.add(product); } else if (nameMode && product.getName().toUpperCase().contains(s.toUpperCase())) { productsTemp.add(product); } else if (skuMode && product.getSku().toUpperCase().contains(s.toUpperCase())) { productsTemp.add(product); } } view.setResultsList(productsTemp, s); }else{ List<Product> products = new ArrayList<>(); view.setResultsList(products, s); } } @Override public void onOkPressed() { view.addProductToOrderInCloseSelf(); } private void onModeChange() { if (searchText.length() > 0) databaseManager.getSearchProducts(searchText.substring(0, 1), skuMode, barcodeMode, nameMode).subscribe((products, throwable) -> { productList = products; List<Product> productsTemp = new ArrayList<>(); for (Product product : productList) { if (barcodeMode && product.getBarcode().toUpperCase().contains(searchText.toUpperCase())) { productsTemp.add(product); } else if (nameMode && product.getName().toUpperCase().contains(searchText.toUpperCase())) { productsTemp.add(product); } else if (skuMode && product.getSku().toUpperCase().contains(searchText.toUpperCase())) { productsTemp.add(product); } } view.setResultsList(productsTemp, searchText); }); } }
package br.com.helpdev.quaklog.entity.vo; import lombok.EqualsAndHashCode; import java.util.UUID; @EqualsAndHashCode public class GameUUID { private final UUID uuid; public static GameUUID of(final String uuid) { return new GameUUID(UUID.fromString(uuid)); } public static GameUUID of(final UUID uuid) { return new GameUUID(uuid); } public static GameUUID create() { return new GameUUID(); } public GameUUID(final UUID uuid) { this.uuid = uuid; } private GameUUID() { this.uuid = java.util.UUID.randomUUID(); } @Override public String toString() { return uuid.toString(); } }
package com.robotarm.core.attachable; public class Gripper implements Tool { public Gripper () { } public void activate () { } public void deactivate () { } }
package com.tencent.mm.plugin.appbrand.jsapi.bluetooth.ble.sdk.scan; import android.os.Parcel; import android.os.ParcelUuid; import android.os.Parcelable; import android.os.Parcelable.Creator; import java.util.Arrays; import java.util.UUID; public class ScanFilterCompat implements Parcelable { public static final Creator<ScanFilterCompat> CREATOR = new 1(); private static final ScanFilterCompat fNF = new a().aix(); final byte[] fNA; final byte[] fNB; final int fNC; final byte[] fND; final byte[] fNE; final String fNv; final String fNw; final ParcelUuid fNx; final ParcelUuid fNy; final ParcelUuid fNz; /* synthetic */ ScanFilterCompat(String str, String str2, ParcelUuid parcelUuid, ParcelUuid parcelUuid2, ParcelUuid parcelUuid3, byte[] bArr, byte[] bArr2, int i, byte[] bArr3, byte[] bArr4, byte b) { this(str, str2, parcelUuid, parcelUuid2, parcelUuid3, bArr, bArr2, i, bArr3, bArr4); } private ScanFilterCompat(String str, String str2, ParcelUuid parcelUuid, ParcelUuid parcelUuid2, ParcelUuid parcelUuid3, byte[] bArr, byte[] bArr2, int i, byte[] bArr3, byte[] bArr4) { this.fNv = str; this.fNx = parcelUuid; this.fNy = parcelUuid2; this.fNw = str2; this.fNz = parcelUuid3; this.fNA = bArr; this.fNB = bArr2; this.fNC = i; this.fND = bArr3; this.fNE = bArr4; } public int describeContents() { return 0; } public void writeToParcel(Parcel parcel, int i) { int i2; int i3 = 0; parcel.writeInt(this.fNv == null ? 0 : 1); if (this.fNv != null) { parcel.writeString(this.fNv); } if (this.fNw == null) { i2 = 0; } else { i2 = 1; } parcel.writeInt(i2); if (this.fNw != null) { parcel.writeString(this.fNw); } if (this.fNx == null) { i2 = 0; } else { i2 = 1; } parcel.writeInt(i2); if (this.fNx != null) { parcel.writeParcelable(this.fNx, i); if (this.fNy == null) { i2 = 0; } else { i2 = 1; } parcel.writeInt(i2); if (this.fNy != null) { parcel.writeParcelable(this.fNy, i); } } if (this.fNz == null) { i2 = 0; } else { i2 = 1; } parcel.writeInt(i2); if (this.fNz != null) { parcel.writeParcelable(this.fNz, i); if (this.fNA == null) { i2 = 0; } else { i2 = 1; } parcel.writeInt(i2); if (this.fNA != null) { parcel.writeInt(this.fNA.length); parcel.writeByteArray(this.fNA); if (this.fNB == null) { i2 = 0; } else { i2 = 1; } parcel.writeInt(i2); if (this.fNB != null) { parcel.writeInt(this.fNB.length); parcel.writeByteArray(this.fNB); } } } parcel.writeInt(this.fNC); if (this.fND == null) { i2 = 0; } else { i2 = 1; } parcel.writeInt(i2); if (this.fND != null) { parcel.writeInt(this.fND.length); parcel.writeByteArray(this.fND); if (this.fNE != null) { i3 = 1; } parcel.writeInt(i3); if (this.fNE != null) { parcel.writeInt(this.fNE.length); parcel.writeByteArray(this.fNE); } } } static boolean a(UUID uuid, UUID uuid2, UUID uuid3) { if (uuid2 == null) { return uuid.equals(uuid3); } if ((uuid.getLeastSignificantBits() & uuid2.getLeastSignificantBits()) == (uuid3.getLeastSignificantBits() & uuid2.getLeastSignificantBits()) && (uuid.getMostSignificantBits() & uuid2.getMostSignificantBits()) == (uuid3.getMostSignificantBits() & uuid2.getMostSignificantBits())) { return true; } return false; } static boolean a(byte[] bArr, byte[] bArr2, byte[] bArr3) { if (bArr3 == null || bArr3.length < bArr.length) { return false; } int i; if (bArr2 == null) { for (i = 0; i < bArr.length; i++) { if (bArr3[i] != bArr[i]) { return false; } } return true; } for (i = 0; i < bArr.length; i++) { if ((bArr2[i] & bArr3[i]) != (bArr2[i] & bArr[i])) { return false; } } return true; } public String toString() { return "BluetoothLeScanFilter [mDeviceName=" + this.fNv + ", mDeviceAddress=" + this.fNw + ", mUuid=" + this.fNx + ", mUuidMask=" + this.fNy + ", mServiceDataUuid=" + d.toString(this.fNz) + ", mServiceData=" + Arrays.toString(this.fNA) + ", mServiceDataMask=" + Arrays.toString(this.fNB) + ", mManufacturerId=" + this.fNC + ", mManufacturerData=" + Arrays.toString(this.fND) + ", mManufacturerDataMask=" + Arrays.toString(this.fNE) + "]"; } public int hashCode() { return Arrays.hashCode(new Object[]{this.fNv, this.fNw, Integer.valueOf(this.fNC), this.fND, this.fNE, this.fNz, this.fNA, this.fNB, this.fNx, this.fNy}); } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } ScanFilterCompat scanFilterCompat = (ScanFilterCompat) obj; if (d.equals(this.fNv, scanFilterCompat.fNv) && d.equals(this.fNw, scanFilterCompat.fNw) && this.fNC == scanFilterCompat.fNC && d.deepEquals(this.fND, scanFilterCompat.fND) && d.deepEquals(this.fNE, scanFilterCompat.fNE) && d.deepEquals(this.fNz, scanFilterCompat.fNz) && d.deepEquals(this.fNA, scanFilterCompat.fNA) && d.deepEquals(this.fNB, scanFilterCompat.fNB) && d.equals(this.fNx, scanFilterCompat.fNx) && d.equals(this.fNy, scanFilterCompat.fNy)) { return true; } return false; } }
package composites.EndGameComposite.entities; import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor public class Piece { private String id; private int value; private String shape; private boolean played; public Piece(int value, String shape, boolean played) { this.value = value; this.shape = shape; this.played = played; } }
package com.ebupt.portal.canyon.system.dao; import com.ebupt.portal.canyon.system.entity.Menu; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.Set; /** * 菜单管理持久层 * * @author chy * @date 2019-03-10 16:55 */ public interface MenuDao extends JpaRepository<Menu, Long> { /** * 根据menuId集合获取指定类型的菜单信息 * * @param menuIds * menuId集合 * @param type * 类型 * @return * 指定类型的菜单信息集合 */ @Query("select m from Menu m where m.menuType = :type and m.menuId in (:menuIds)") Set<Menu> findbyMenuIds(@Param("menuIds") Set<String> menuIds, @Param("type") String type); }
package com.ehootu.correct.controller; import com.ehootu.core.generic.BaseController; import com.ehootu.core.util.Query; import com.ehootu.core.util.R; import com.ehootu.correct.model.IncontrollableControlWorkEntity; import com.ehootu.correct.service.IncontrollableControlWorkService; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map; /** * 失控重点人员动态管控工作记录 * * @author yinyujun * @email * @date 2017-09-21 14:42:23 */ @RestController @RequestMapping("/app/incontrollablecontrolwork") public class IncontrollableControlWorkController extends BaseController { @Autowired private IncontrollableControlWorkService incontrollableControlWorkService; /** * 列表 * @param params policeId 警察id * @param params page 当前页码 * @param params pageSize 每页显示条数 */ @RequestMapping("/list") @ResponseBody public void list(@RequestParam Map<String, Object> params){ //查询列表数据 Query query = new Query(params,"app"); List<IncontrollableControlWorkEntity> patrolRecordList = incontrollableControlWorkService.queryList(query); resultSuccess(patrolRecordList); } /** * 根据主键 id 查询详细信息 * @param id 可防性案件巡逻防控管理表主键id */ @GetMapping("/info") public void info(String id){ IncontrollableControlWorkEntity incontrollableControlWork = incontrollableControlWorkService.queryObject(id); resultSuccess(incontrollableControlWork); } /** * 保存 */ @PostMapping("/save") public void save(IncontrollableControlWorkEntity incontrollableControlWork, String pageName){ incontrollableControlWorkService.save(incontrollableControlWork, pageName); resultSuccess(); } /** * 修改 */ @RequestMapping("/update") @RequiresPermissions("incontrollablecontrolwork:update") public R update(@RequestBody IncontrollableControlWorkEntity incontrollableControlWork){ incontrollableControlWorkService.update(incontrollableControlWork); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") @RequiresPermissions("incontrollablecontrolwork:delete") public R delete(@RequestBody Integer[] ids){ incontrollableControlWorkService.deleteBatch(ids); return R.ok(); } }
package com.yinghai.a24divine_user.module.shop.shopcar; import android.content.Context; import android.view.View; import android.widget.ImageView; import com.example.fansonlib.base.AppUtils; import com.example.fansonlib.base.BaseDataAdapter; import com.example.fansonlib.base.BaseHolder; import com.example.fansonlib.image.ImageLoaderUtils; import com.example.fansonlib.utils.ShowToast; import com.yinghai.a24divine_user.R; import com.yinghai.a24divine_user.bean.ShopCarBean; import com.yinghai.a24divine_user.callback.OnAdapterListener; import com.yinghai.a24divine_user.constant.ConHttp; import com.yinghai.a24divine_user.constant.ConstAdapter; import com.yinghai.a24divine_user.widget.ShopAmountView; import java.util.ArrayList; import java.util.List; /** * @author Created by:fanson * Created on:2017/11/13 16:17 * Description:购物车的适配器 */ public class ShopCarAdapter extends BaseDataAdapter<ShopCarBean.DataBean> { private static final String TAG = ShopCarAdapter.class.getSimpleName(); /** * 选择了的商品List */ private List<ShopCarBean.DataBean> mSelectedShopBeanList; private OnAdapterListener mOnAdapterListener; public void setOnAdapterListener(OnAdapterListener listener) { mOnAdapterListener = listener; } public ShopCarAdapter(Context context) { super(context); mSelectedShopBeanList = new ArrayList<>(); } @Override public int getLayoutRes(int i) { return R.layout.item_shop_edit; } @Override public void bindCustomViewHolder(final BaseHolder baseHolder, final int position) { if (getItem(position).getProduct() == null) { return; } final ShopAmountView shopAmountView = baseHolder.getView(R.id.shop_amount); baseHolder.setText(R.id.tv_product_name, getItem(position).getProduct().getPName()); baseHolder.setText(R.id.tv_shop_address, getItem(position).getProduct().getPAttribution()); baseHolder.setText(R.id.tv_product_price, String.format(context.getString(R.string.money_unit), getItem(position).getProduct().getPPrice() / 100)); if (getItem(position).getProduct().isPFreeShipping()) { baseHolder.getView(R.id.iv_shop_package).setVisibility(View.VISIBLE); } else { baseHolder.getView(R.id.iv_shop_package).setVisibility(View.GONE); } if (getItem(position).getProduct().getImgList().size() > 0) { ImageLoaderUtils.loadImage(AppUtils.getAppContext().getApplicationContext(), (ImageView) baseHolder.getView(R.id.iv_product), ConHttp.BASE_URL + getItem(position).getProduct().getImgList().get(0).getItUrl()); } final ImageView dotSelect = baseHolder.getView(R.id.dot_select); if (mSelectedShopBeanList.contains(getItem(position))) { dotSelect.setSelected(true); } else { dotSelect.setSelected(false); } final int goodStorageCount = getItem(position).getProduct().getPTotal(); // 进行库存判断 if (goodStorageCount <= 0) { baseHolder.setVisible(R.id.shop_has_over, true); baseHolder.setVisible(R.id.shop_amount, false); } else { baseHolder.setVisible(R.id.shop_has_over, false); baseHolder.setVisible(R.id.shop_amount, true); shopAmountView.setGoodStorage(goodStorageCount); shopAmountView.setAmount(getItem(position).getCQty()); //增减数量的监听 shopAmountView.setOnAmountChangeListener(new ShopAmountView.OnAmountChangeListener() { @Override public void onAmountChange(View view, int amount) { if (getItem(position) != null) { getItem(position).setCQty(amount); for (ShopCarBean.DataBean bean : mSelectedShopBeanList) { if (bean == getItem(position)) { bean.setCQty(amount); } } calTotalFee(); } } }); } //选中某个商品item dotSelect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (goodStorageCount <= 0) { ShowToast.singleLong(context.getString(R.string.shop_has_over)); return; } boolean isContains = false; for (ShopCarBean.DataBean bean : mSelectedShopBeanList) { if (bean == getItem(position)) { mSelectedShopBeanList.remove(getItem(position)); dotSelect.setSelected(false); isContains = true; break; } } if (!isContains) { mSelectedShopBeanList.add(getItem(position)); dotSelect.setSelected(true); } calTotalFee(); } }); baseHolder.setOnClickListener(R.id.iv_del, new View.OnClickListener() { @Override public void onClick(View view) { mOnAdapterListener.clickItem(ConstAdapter.DELETE_SHOP_CAR, getItem(position).getCarId()); } }); } /** * 计算总费用 */ private void calTotalFee() { int mTotalFee = 0; for (int i = 0; i < mSelectedShopBeanList.size(); i++) { mTotalFee = mTotalFee + mSelectedShopBeanList.get(i).getCQty() * (mSelectedShopBeanList.get(i).getProduct().getPPrice() / 100); } mOnAdapterListener.clickItem(ConstAdapter.SHOP_CAR_FEE, mTotalFee); } /** * 选择全部 * * @param isSelectAll */ public void selectAll(boolean isSelectAll) { if (isSelectAll) { mSelectedShopBeanList.clear(); for (ShopCarBean.DataBean bean : mDataList) { if (bean.getProduct().getPTotal() > 0) { mSelectedShopBeanList.add(bean); } } } else { mSelectedShopBeanList.clear(); } calTotalFee(); this.notifyDataSetChanged(); } /** * 根据判断carid,进行删除 * * @param carId */ @Override public void removeItem(int carId) { for (int i = 0; i < mDataList.size(); i++) { if (mDataList.get(i).getCarId() == carId) { mSelectedShopBeanList.remove(mDataList.get(i)); mDataList.remove(i); this.notifyItemRemoved(i); this.notifyItemRangeChanged(i, this.mDataList.size() - i); calTotalFee(); return; } } } /** * 获取被选中的项 * * @return 所有勾选的商品 */ public List<ShopCarBean.DataBean> getSelectedShopList() { return mSelectedShopBeanList; } }
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.components.devtools_bridge; import android.util.Log; import java.io.IOException; /** * Helper class which handles a client session in tests. Having direct reference to * the server it runs its client session on a dedicated thread and proxies all call * between them to satisfy theading requirements. */ public class ClientSessionTestingHost { private static final String TAG = "ClientSessionTestingHost"; private final SignalingReceiver mTarget; private final SessionBase.Executor mTargetExecutor; private final LocalSessionBridge.ThreadedExecutor mClientExecutor; private final String mSessionId; private final ClientSession mClientSession; public ClientSessionTestingHost( SessionDependencyFactory factory, SignalingReceiver target, SessionBase.Executor targetExecutor, String sessionId, String clientSocketName) throws IOException { mTarget = target; mTargetExecutor = targetExecutor; mClientExecutor = new LocalSessionBridge.ThreadedExecutor(); mSessionId = sessionId; SignalingReceiverProxy proxy = new SignalingReceiverProxy( mTargetExecutor, mClientExecutor, target, 0); mClientSession = new ClientSession( factory, mClientExecutor, proxy.asServerSession(mSessionId), clientSocketName) { @Override protected void closeSelf() { Log.d(TAG, "Closed self"); super.closeSelf(); } @Override protected void onControlChannelOpened() { Log.d(TAG, "Control channel opened"); super.onControlChannelOpened(); } @Override protected void onControlChannelClosed() { Log.d(TAG, "Control channel closed"); super.onControlChannelClosed(); } @Override protected void onFailure(String message) { Log.e(TAG, "Failure: " + message); super.onFailure(message); } }; } public void dispose() { mClientExecutor.runSynchronously(new Runnable() { @Override public void run() { mClientSession.dispose(); } }); } public void start() { start(new RTCConfiguration()); } public void start(final RTCConfiguration config) { mClientExecutor.runSynchronously(new Runnable() { @Override public void run() { mClientSession.start(config); } }); } }
package com.zhao.leetcode; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; //56 public class MergeRange { public int [][] merge(int [][] intervals){ Arrays.sort(intervals, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return o1[0]-o2[0]; } }); List<int []> result = new ArrayList<>(); int curLeft = intervals[0][0]; int curRight = intervals[0][1]; for (int i=1;i<intervals.length;++i){ if (intervals[i][0]<=curRight){ if (intervals[i][1]>curRight){ curRight=intervals[i][1]; } }else { result.add(new int[]{curLeft,curRight}); curLeft= intervals[i][0]; curRight =intervals[i][1]; } } result.add(new int[]{curLeft,curRight}); return result.toArray(new int[result.size()][]); } }
package com.app.cosmetics.core.account; import com.app.cosmetics.core.base.BaseEntity; import com.app.cosmetics.core.role.Role; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import java.util.ArrayList; import java.util.List; @Entity @Getter @Setter @NoArgsConstructor public class Account extends BaseEntity { @Column(unique = true) private String username; private String password; @Email @Column(unique = true) private String email; @NotBlank private String firstName; private String lastName; private String address; private String avatar; @ManyToMany @JoinTable( name = "account_roles", joinColumns = @JoinColumn( name = "account_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn( name = "role_id", referencedColumnName = "id")) private List<Role> roles = new ArrayList<>(); public Account(String username, String password, String email, String firstName, String lastName, String address, String avatar, List<Role> roles) { this.username = username; this.password = password; this.email = email; this.firstName = firstName; this.lastName = lastName; this.address = address; this.avatar = avatar; this.roles = roles; } public void update(String password, String email, String firstName, String lastName, String address, String avatar) { if (!"".equals(password)) { this.password = password; } if (!"".equals(email)) { this.email = email; } if (!"".equals(firstName)) { this.firstName = firstName; } if (!"".equals(lastName)) { this.lastName = lastName; } if (!"".equals(address)) { this.address = address; } if (!"".equals(avatar)) { this.avatar = avatar; } } }
package jneiva.hexbattle.componente; import java.util.List; public interface IEntidade { public List<IComponente> getComponentes(); public <T extends IComponente> T getComponente(Class<T> tipo); public void update(); public void acordar(); public void desligar(); public <T extends IComponente> T addComponente(T componente); }
package com.shidan.product.dao; import java.util.List; import java.util.Map; import com.shidan.product.annotation.MyAnnotation; import com.shidan.product.entity.Privilege; import com.shidan.product.entity.Role; import com.shidan.product.entity.page.Page; import com.shidan.product.entity.page.RolePage; @MyAnnotation public interface RoleDao { /** * 分页查询角色 * @param adminPage 分页查询条件 * @return 返回查询后的角色信息 */ public List<Role> findByPage(RolePage page); /** * 查询所有查询条件的记录数 * @param adminPage * @return */ public int findRows(Page page); /** * 查询所有的角色 * @return 返回所有的角色 */ public List<Role> findAll(); /** * 添加角色 * @param role 角色信息 */ public void addRole(Role role); /** * 添加角色相关联的权限 * @param param 添加权限的角色id 和权限id */ public void addRolePrivilege(Map<String, Object> param); /** * 删除角色 */ public void deleteRole(Integer id); /** * 删除角色相关联的角色 * @param 角色的id */ public void deleteRolePrivileges(Integer id); /** * 根据id查找响应的角色信息 * @param id */ public Role findRole(Integer id); /** * 更新角色信息 * @param role */ public void update(Role role); }
package com.iuce.control; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; public class LoginControl implements ILoginControl { private Context context; private SharedPreferences preferences; private String PASSWORD_TAG = "diaryPassword"; public LoginControl(Context context) { // TODO Auto-generated constructor stub preferences = PreferenceManager.getDefaultSharedPreferences(context); this.context = context; } @Override public boolean controlPassword(String p) { // TODO Auto-generated method stub // SharedPreferences.Editor editor = preferences.edit(); String password = preferences.getString(PASSWORD_TAG, null).toString(); if (password.equals(p)) { return true; } return false; } @Override public boolean resetPassword(String password) { // TODO Auto-generated method stub SharedPreferences.Editor editor = preferences.edit(); editor.putString(PASSWORD_TAG, password); editor.commit(); return false; } @Override public boolean savePassword(String password) { // TODO Auto-generated method stub SharedPreferences.Editor editor = preferences.edit(); editor.putString(PASSWORD_TAG, password); editor.commit(); return false; } // if program first opened by user @Override public boolean controlFirstOpen() { // TODO Auto-generated method stub try { String password = preferences.getString(PASSWORD_TAG, null).toString(); return false; } catch (Exception e) { return true; } } @Override public boolean changePassword(String currentPassword, String newPassword) { // TODO Auto-generated method stub String currentPass = preferences.getString(PASSWORD_TAG, null).toString(); if (currentPass.equals(currentPassword)) { resetPassword(newPassword); return true; } return false; } }
/** * Created by ruchi on 18/07/2017. * This class contains order information */ public class Order { private String orderId; private String status; private double value; public void setOrderId(String orderId){ this.orderId = orderId; } public String getOrderId(){ return orderId; } public void setStatus(String status){ this.status = status; } public String getStatus(){ return status; } public void setValue(double value){ this.value = value; } public double getValue(){ return value; } }
package main.java; import java.util.Iterator; import java.util.Vector; import static main.java.FF_p_norm.vector_print; public class FF_zscore_norm { public static Vector normalize(Vector in_vector){ if (in_vector.isEmpty()) { System.out.println("Empty vector!"); return null; } if(in_vector.firstElement() instanceof String||in_vector.firstElement() instanceof Character){ System.out.println("Error: Non-numeric element contained!"); return null; } Iterator iterator1 = in_vector.iterator(); Iterator iterator2 = in_vector.iterator(); Iterator iterator3 = in_vector.iterator(); Vector<Double> ret_vector = new Vector<>(in_vector.size()); double sum = 0; while(iterator1.hasNext()){ sum += Double.parseDouble(iterator1.next().toString()); } double mean_val = sum/in_vector.size(); double var_val = 0; while(iterator2.hasNext()){ var_val += Math.pow(Double.parseDouble(iterator2.next().toString())-mean_val,2); } double std_val = Math.pow(var_val/in_vector.size(),0.5); while(iterator3.hasNext()){ ret_vector.add((Double.parseDouble(iterator3.next().toString())-mean_val)/std_val); } return ret_vector; } public static void main(String[] args){ Vector<Double> test_vector = new Vector<>(); test_vector.add(1.0); test_vector.add(1.0); test_vector.add(5.0); test_vector.add(5.0); // test_vector.add(5.0); // test_vector.add(6.0); // test_vector.add(7.0); // test_vector.add(8.0); // test_vector.add(9.0); // test_vector.add(10.0); Vector<Double> ret = normalize(test_vector); vector_print(ret); } }
//这个方法很笨,DP判断每个字串是不是palindromic,耗时长 class Solution { public String longestPalindrome(String ss) { int size = ss.length(); if(size == 0){ return ""; } char[] s = ss.toCharArray(); boolean[][] isPal = new boolean[size][size]; int start = 0; int end = 0; for(int axis = 0; axis < size; axis++){ int i = axis; int j = axis; isPal[i][j] = true; i--; j++; while(i >= 0 && j < size){ isPal[i][j] = isPal[i + 1][j - 1] && s[i] == s[j]; if(isPal[i][j] && j - i > end - start){ start = i; end = j; } i--; j++; } } for(int axis = 0; axis < size - 1; axis++){ int i = axis; int j = axis + 1; isPal[i][j] = s[i] == s[j]; if(isPal[i][j] && j - i > end - start){ start = i; end = j; } i--; j++; while(i >= 0 && j < size){ isPal[i][j] = isPal[i + 1][j - 1] && s[i] == s[j]; if(isPal[i][j] && j - i > end - start){ start = i; end = j; } i--; j++; } } return ss.substring(start, end + 1); } }
package classic_algorithms; import java.util.HashMap; import java.util.Map.Entry; import java.util.stream.Stream; import entity.Edge; import entity.Graph; import entity.Vertex; import entity.VertexGroup; /** * An implentation of the Fiduccia Mattheyses Algorithm * * @author Vanesa Georgieva * */ public interface IFiducciaMattheysesAlgorithm { VertexGroup getBestPartitionA(); VertexGroup getBestPartitionB(); Graph getGraph(); void processGraph(Graph g); void setInitialPartition(Graph g); Stream<Entry<Integer, Double>> sortVerticesByCost(); void doAllSwaps() ; void setVertexToMove(); void setBestPartiton(); void setGain(final Vertex vertexToMove); void swapVertex(Vertex vertexToMove); double getVertexCost(Vertex v); }
public class HelloWorld{ public static void main(String[] args){ System.out.println("Hello World"); } } /*How to run * Open cmd * javac HelloJava.java * java HelloJava */
/** * Copyright (c) 2019 Amarone- zjlgd.cn , All rights reserved. */ package cn.amarone.model.article.service; import java.util.List; import cn.amarone.model.article.entity.ArticleType; /** * @Description: * @Author: Amarone * @Created Date: 2019年04月17日 * @LastModifyDate: * @LastModifyBy: * @Version: */ public interface IArticleTypeService { /** * 获取所有文章分类 * * @return ArticleTypes */ List<ArticleType> getAllType(); ArticleType queryById(Long id); }
package com.takshine.wxcrm.service; import com.takshine.wxcrm.base.services.EntityService; import com.takshine.wxcrm.domain.Campaigns; import com.takshine.wxcrm.message.error.CrmError; import com.takshine.wxcrm.message.sugar.CampaignsAdd; import com.takshine.wxcrm.message.sugar.CampaignsResp; /** * 市场活动接口 * @author dengbo * */ public interface Campaigns2CrmService extends EntityService{ /** * 查询 市场活动数据列表 * @return */ public CampaignsResp getCampaignsList(Campaigns sche, String source)throws Exception; /** * 查询单个市场活动数据 * @param rowid * @param crmid * @return * @throws Exception */ public CampaignsResp getCampaignsSingle(String rowid,String crmid)throws Exception; /** * 增加市场活动 * @param campaignsAdd * @return * @throws Exception */ public CrmError saveCampaigns(CampaignsAdd campaignsAdd) throws Exception; /** * 修改市场活动 * @param campaignsAdd * @return * @throws Exception */ public CrmError updateCampaigns(CampaignsAdd campaignsAdd)throws Exception; }
package com.tencent.mm.plugin.kitchen.ui; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import com.tencent.mm.bp.a; import com.tencent.mm.plugin.kitchen.b.b; import com.tencent.mm.plugin.report.service.d; import com.tencent.mm.plugin.report.service.j; import com.tencent.mm.sdk.platformtools.ac; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.MMActivity; import com.tencent.mm.ui.base.h; import com.tencent.mm.ui.widget.MMSwitchBtn; import com.tencent.mm.ui.widget.a.c; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class KvInfoUI extends MMActivity { private Button eGn; private c fad; private ArrayAdapter iIy; private EditText kAm; private Button kAn; private ListView kAo; private TextView kAp; private MMSwitchBtn kAq; private String kAr; public void onCreate(Bundle bundle) { super.onCreate(bundle); setMMTitle("Debug show kv log"); setBackBtn(new 1(this)); this.kAm = (EditText) findViewById(b.input_log); this.kAp = (TextView) findViewById(b.select_id_info); this.kAn = (Button) findViewById(b.log_picker); this.kAn.setOnClickListener(new OnClickListener() { public final void onClick(View view) { HashMap hashMap = j.brV().mFb; if (hashMap != null && hashMap.size() > 0) { ArrayList arrayList = new ArrayList(hashMap.keySet()); com.tencent.mm.ui.widget.picker.b bVar = new com.tencent.mm.ui.widget.picker.b(KvInfoUI.this.mController.tml, arrayList); bVar.GC(0); bVar.uLl = new 1(this, bVar, arrayList); bVar.GB(a.fromDPToPix(KvInfoUI.this.mController.tml, 288)); bVar.show(); } } }); this.kAq = (MMSwitchBtn) findViewById(b.debug_flag); this.kAq.setCheck(j.brV().mDt); this.kAq.setSwitchListener(new 3(this)); this.eGn = (Button) findViewById(b.confirm_btn); this.eGn.setOnClickListener(new 4(this)); this.kAo = (ListView) findViewById(b.kv_log_list); this.iIy = new 5(this, this, com.tencent.mm.plugin.kitchen.b.c.kv_info_ui_item, b.kv_info_ui_tv); this.kAo.setAdapter(this.iIy); this.kAo.setOnItemClickListener(new OnItemClickListener() { public final void onItemClick(AdapterView<?> adapterView, View view, int i, long j) { d dVar = (d) KvInfoUI.this.iIy.getItem(i); if (dVar != null) { if (dVar.bKg == null || dVar.bKg.length() <= 0) { dVar.bKg = ac.ce(dVar.value); } String str = (String) j.brV().mFc.get(dVar.bKg); if (KvInfoUI.this.fad != null) { KvInfoUI.this.fad.dismiss(); } if (!bi.oW(str)) { KvInfoUI.this.fad = h.a(KvInfoUI.this, str, "", KvInfoUI.this.getString(com.tencent.mm.plugin.kitchen.b.d.app_ok), KvInfoUI.this.getString(com.tencent.mm.plugin.kitchen.b.d.app_copy), true, new DialogInterface.OnClickListener() { public final void onClick(DialogInterface dialogInterface, int i) { dialogInterface.cancel(); } }, new 2(this, str), -1); } } } }); } protected final int getLayoutId() { return com.tencent.mm.plugin.kitchen.b.c.kv_info_ui; } private void Fy(String str) { x.i("MicroMsg.KvInfoUI", "updateData new[%s] old[%s]", new Object[]{str, this.kAr}); this.kAr = str; List list = (List) j.brV().mFb.get(this.kAr); if (list != null) { this.kAp.setText(this.kAr + ":" + list.size()); this.iIy.setNotifyOnChange(false); this.iIy.clear(); this.iIy.addAll(list); this.iIy.notifyDataSetChanged(); return; } this.kAp.setText(this.kAr + ":0"); this.iIy.clear(); } protected void onDestroy() { if (this.iIy != null) { this.iIy.setNotifyOnChange(false); this.iIy.clear(); } if (this.fad != null) { this.fad.dismiss(); } YC(); super.onDestroy(); } protected void onResume() { if (!bi.oW(this.kAr)) { Fy(this.kAr); } super.onResume(); } }
package com.tencent.mm.plugin.profile.ui; public interface NormalUserFooterPreference$e { void aJ(String str, boolean z); }
package kh.cocoa.endpoint; import javax.servlet.http.HttpSession; import javax.websocket.HandshakeResponse; import javax.websocket.server.HandshakeRequest; import javax.websocket.server.ServerEndpointConfig; // ===================== HttpSessionConfigurator ===================== public class HttpSessionConfigurator extends ServerEndpointConfig.Configurator { public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) { // Handshake request와 response는 핸드셰이크과정에서 쓰이고 버려진다. // 그래서 이거는 onMessage까지 못온다. // request안에 session이 들어있더라도 우리가 사용하지를 못한다. // 그래서 이 안의 session을 미리 변수로 빼놓는다. // EndpointConfig는 언제든 다른매서드에서 매개변수로 추가가 가능하다. HttpSession session = (HttpSession)request.getHttpSession(); sec.getUserProperties().put("hsession", session); } }
package com.example.demo; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class FlightsController { @GetMapping("/flights") public List getAllFlights(){ List<Map<String, String>> flights = new ArrayList<>(); Map<String, String> flight1 = new HashMap<>(); flight1.put("id", "AA431"); flight1.put("name", "American Airlines. From Denver to Delhi"); flights.add(flight1); Map<String, String> flight2 = new HashMap<>(); flight2.put("id", "UA101"); flight2.put("name", "United Airlines. From Denver to SFO"); flights.add(flight2); return flights; } }
/* * 2012-3 Red Hat Inc. and/or its affiliates and other contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.overlord.rtgov.internal.switchyard.bpel; import java.util.EventObject; import org.apache.ode.bpel.evt.VariableModificationEvent; import org.overlord.rtgov.internal.switchyard.AbstractEventProcessor; /** * This class provides the BPEL component implementation of the * event processor. * */ public class VariableModificationEventProcessor extends AbstractEventProcessor { /** * This is the default constructor. */ public VariableModificationEventProcessor() { super(VariableModificationEvent.class); } /** * {@inheritDoc} */ public void handleEvent(EventObject event) { VariableModificationEvent bpelEvent=(VariableModificationEvent)event; org.overlord.rtgov.activity.model.bpm.ProcessVariableSet pvs= new org.overlord.rtgov.activity.model.bpm.ProcessVariableSet(); org.w3c.dom.Node value=bpelEvent.getNewValue(); // Unwrap if single part message if (value.getLocalName().equals("message") && value.getChildNodes().getLength() == 1) { // Unwrap message and single part value = value.getFirstChild().getFirstChild(); } else if (value.getLocalName().equals("temporary-simple-type-wrapper")) { value = value.getFirstChild(); } String type=value.getLocalName(); if (value.getNamespaceURI() != null) { type = "{"+value.getNamespaceURI()+"}"+type; } pvs.setVariableName(bpelEvent.getVarName()); pvs.setVariableType(type); pvs.setVariableValue(getActivityCollector().processInformation(null, type, value, null, pvs)); pvs.setProcessType(bpelEvent.getProcessName().toString()); pvs.setInstanceId(bpelEvent.getProcessInstanceId().toString()); recordActivity(event, pvs); } }
package View; import java.util.ArrayList; import java.util.InputMismatchException; import java.util.Scanner; import controller.Controle; import model.Animal; import model.Aves; import model.Cachorro; import model.Cliente; import model.Endereco; import model.Gato; /* Trabalho de Paradigmas de Linguagens de Programação PetShop Copyright 2018 by Marcelo Henrique, Rafaela Custódio e Thiago Fiori Arquivo que permite realizar interacoes com Cliente */ public class MainCliente { private static Scanner scanner; private static Controle controle = new Controle(); public static void cadastrarCliente() throws Exception { // método que cadastra cliente System.out.println("CADASTRO DE CLIENTE"); scanner = new Scanner(System.in); ArrayList<Animal> animaisAssociados = new ArrayList<Animal>(); boolean verifica = true; int qtdAnimais = 0; int tipoAnimal = 0; System.out.println(" - Digite um Id para o Cliente - "); int cliente_id = scanner.nextInt(); scanner.nextLine(); // esvazia o buffer do teclado System.out.println(" - Digite o cpf do Cliente - "); String cpf = scanner.nextLine(); System.out.println(" - Digite o nome do Cliente - "); String nome = scanner.nextLine(); System.out.println(" - Digite a data de nascimento do Cliente - "); String dataNascimento = scanner.nextLine(); System.out.println(" - Endereco do Cliente - "); Endereco endereco = MainEndereco.cadastrarEndereco(); System.out.println(" - Observacões do Cliente - "); String obs = scanner.nextLine(); do { try { System.out.println(" - Quantos animais deseja cadastrar para o cliente ? - "); qtdAnimais = scanner.nextInt(); while(qtdAnimais <= 0) { System.out.println("NÚMEROS NEGATIVOS e ZERO NÃO SÃO VALIDOS!"); System.out.println(" - Quantos animais deseja cadastrar para o cliente ? - "); qtdAnimais = scanner.nextInt(); } verifica = false; }catch(InputMismatchException e) { scanner.nextLine(); throw new Exception("APENAS NUMEROS INTEIROS."); } }while(verifica == true); verifica = true; System.out.println(" - CADASTRO DE ANIMAIS ASSOCIADOS AO CLIENTE - "); for(int i = 1; i <= qtdAnimais; i++) { System.out.println("ANIMAL " + i + " - QUAL TIPO DE ANIMAL DESEJA CADASTRAR ?"); try { System.out.println("\n1 - Aves"); System.out.println("2 - Cachorro"); System.out.println("3 - Gato"); tipoAnimal = scanner.nextInt(); } catch (InputMismatchException e) { scanner.nextLine(); throw new Exception("\nDigite um número válido, de 1 ate 3!\n"); } switch (tipoAnimal) { case 1: System.out.println("CADASTRO AVE"); Aves ave = MainAnimais.cadastrarAves(); animaisAssociados.add(ave); break; case 2: System.out.println("CADASTRO CACHORRO"); Cachorro cachorro = MainAnimais.cadastrarCachorro(); animaisAssociados.add(cachorro); break; case 3: System.out.println("CADASTRO GATO"); Gato gato = MainAnimais.cadastrarGato(); animaisAssociados.add(gato); break; case 4 : System.exit(0); break; default: System.out.println("DIGITE UMA OPCAO VALIDA!"); break; } } Cliente newCliente = new Cliente(cliente_id, nome, cpf, dataNascimento, endereco, animaisAssociados, obs); boolean verificaAdd = false; System.out.println("Informe o nome do Arquivo que deseja salvar: "); String nomeArquivo = Main.setarNomeArquivo(); verificaAdd = controle.inserirCliente(newCliente, nomeArquivo); if(verificaAdd) { System.out.println("*Cliente cadastrado com sucesso! *"); } else { System.out.println("*** O Cliente não foi cadastrada! ***"); } } public static void imprimirClientesCadastrados() { // método que lista o cliente System.out.println("LISTAR CLIENTES CADASTRADOS"); System.out.println("Informe o nome do Arquivo que deseja ler: "); String nomeArquivo = Main.setarNomeArquivo(); ArrayList <Cliente> clientes; clientes = new ArrayList<Cliente>(); clientes = controle.listarClientes(nomeArquivo); if(clientes.size()!=0){ for(int i=0;i<clientes.size();i++){ System.out.println((i+1)+") Nome do Cliente: "+clientes.get(i).getNome() + " / ID: "+clientes.get(i).getCliente_id()); System.out.println("CPF: "+clientes.get(i).getCpf() + " / Data de Nascimento: " + clientes.get(i).getDataNascimento()) ; System.out.println("Rua: "+clientes.get(i).getEndereco().getRua() + "," +clientes.get(i).getEndereco().getNumero()); System.out.println("Complemento: "+clientes.get(i).getEndereco().getComplemento() ); System.out.println("Bairro: "+clientes.get(i).getEndereco().getBairro() +","+clientes.get(i).getEndereco().getCidade() +","+clientes.get(i).getEndereco().getEstado()+"\n"); System.out.println("ANIMAIS"); for(int j = 0; j<clientes.get(i).getAnimaisAssociados().size(); j++ ) { System.out.println("Animal: " + (j+1)); System.out.println("Tipo: "+clientes.get(i).getAnimaisAssociados().get(j).getClass().getSimpleName() ); System.out.println("Id: "+clientes.get(i).getAnimaisAssociados().get(j).getAnimal_id() ); System.out.println("Sexo: "+clientes.get(i).getAnimaisAssociados().get(j).getSexo() ); System.out.println("Peso(kg): "+clientes.get(i).getAnimaisAssociados().get(j).getPeso()); System.out.println("Obs.: "+clientes.get(i).getAnimaisAssociados().get(j).getObservacoes() + "\n" ); } } calculaTotalClientes(); }else { System.out.println("Nenhum Cliente cadastrada"); } } public static void pesquisarCliente() { // Busca um cliente System.out.println("PESQUISA DE CLIENTE"); scanner = new Scanner(System.in); System.out.println("Informe o nome do Arquivo que deseja pesquisar: "); String nomeArquivo = Main.setarNomeArquivo(); System.out.println("Digite o nome do cliente em que deseja pesquisar"); String nome = scanner.nextLine(); Cliente clienteBuscado = null; if(controle.pesquisarCliente(nome, nomeArquivo)) { clienteBuscado = controle.getCliente(nome); System.out.println(" Nome do Cliente: "+clienteBuscado.getNome() + " / ID: "+clienteBuscado.getCliente_id()); System.out.println("CPF: "+clienteBuscado.getCpf() + " / Data de Nascimento: " + clienteBuscado.getDataNascimento()) ; System.out.println("LISTAR CLIENTES CADASTRADOS"); System.out.println("CEP: "+clienteBuscado.getEndereco().getCep()); System.out.println("Rua: "+clienteBuscado.getEndereco().getRua() + "," +clienteBuscado.getEndereco().getNumero()); System.out.println("Complemento: "+clienteBuscado.getEndereco().getComplemento() ); System.out.println("Bairro: "+clienteBuscado.getEndereco().getBairro() +","+clienteBuscado.getEndereco().getCidade() +","+clienteBuscado.getEndereco().getEstado()+"\n"); System.out.println("ANIMAIS"); for(int j = 0; j<clienteBuscado.getAnimaisAssociados().size(); j++ ) { System.out.println("Animal: " + (j+1)); System.out.println("Tipo: "+clienteBuscado.getAnimaisAssociados().get(j).getClass().getSimpleName()); System.out.println("Id: "+clienteBuscado.getAnimaisAssociados().get(j).getAnimal_id() ); System.out.println("Sexo: "+clienteBuscado.getAnimaisAssociados().get(j).getSexo() ); System.out.println("Peso(kg): "+clienteBuscado.getAnimaisAssociados().get(j).getPeso()); System.out.println("Obs.: "+clienteBuscado.getAnimaisAssociados().get(j).getObservacoes() + "\n"); } }else{ System.out.println("Cliente não cadastrado"); } } public static void removerCliente() throws Exception{ // remove cliente scanner = new Scanner(System.in); System.out.println("EXCLUSÃO DE CLIENTE"); System.out.println("Digite o nome do Cliente que deseja remover"); String cliente = scanner.nextLine(); System.out.println("Informe o nome do Arquivo em que deseja remover: "); String nomeArquivo = Main.setarNomeArquivo(); if(controle.removerCliente(cliente,nomeArquivo)) { System.out.println("Cliente removido com sucesso!"); } else { System.out.println("Esse Cliente não está cadastrado!"); } calculaTotalClientes(); } public static void calculaTotalClientes(){ System.out.println("-> TOTAL DE CLIENTES CADASTRADOS: "+ controle.retornarTotalClientes()); } }
package com.mo.serialnumber.service; import org.apache.commons.lang3.StringUtils; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.SecureRandom; import java.util.Calendar; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; /** * 订单号生成 * @author MoXingwang on 2017-11-17. */ public class SerialNumberGenerator { private static final int USER_ID_LENGTH = 4; /** * 订单号生成 * @param userId * @return */ public static String generate(String userId){ if(StringUtils.isBlank(userId)){ userId = ThreadLocalRandom.current().nextLong((int)Math.pow(10, USER_ID_LENGTH - 1), (int)Math.pow(10, USER_ID_LENGTH) - 1) + ""; }else if(userId.length() < USER_ID_LENGTH){ userId = StringUtils.leftPad(userId,USER_ID_LENGTH,"0"); }else if(userId.length() > USER_ID_LENGTH){ userId = userId.substring(userId.length() - USER_ID_LENGTH,userId.length()); } Calendar can = Calendar.getInstance(); int year = can.get(Calendar.YEAR) - 2017; int days = can.get(Calendar.DAY_OF_YEAR); int hour = can.get(Calendar.HOUR_OF_DAY); int min = can.get(Calendar.MINUTE); int minutes = (hour - 8 < 0 ? 0 : hour - 8) * 60 + min; String req = (year * 366 + days) + StringUtils.leftPad(minutes + "",3,"0"); SecureRandom secureRandom = new SecureRandom(); secureRandom.nextInt(); req += StringUtils.leftPad(ThreadLocalRandom.current().nextLong(0, 999999) + "",6,"0"); return req + userId; } /** * 订单号生成 * @param prefix * @param userId * @return */ public static String generate(String prefix,String userId){ return prefix + generate(userId); } /** * 推荐不再使用前缀 * @param args */ public static void main(String[] args) { SecureRandom secureRandom = new SecureRandom(); // System.out.println(secureRandom.nextInt());; // System.out.println(secureRandom.nextInt());; try { SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN"); random.nextInt(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchProviderException e) { e.printStackTrace(); } Random random = new Random(10); Random random2 = new Random(10); for (int i = 0; i < 20; i++) { System.out.println(random.nextInt()); } System.out.println("11111111111111111111"); for (int i = 0; i < 20; i++) { System.out.println(random2.nextInt()); } } }
import java.util.Random; public class Item { private String itemName; private int atk; private int def; private int gold; public static final Object[][] itemList = new Object[][] { {"Hammer", 10, 0, 600} , {"Armor", 0, 10, 300} , {"MagicStaff", 10, 0, 600} , {"Spear", 10, 0, 600} }; public Item(String itemName) { this.itemName = itemName; for(Object[] item: itemList) { if(((String)item[0]).equals(itemName)) { this.atk = (int)item[1]; this.def = (int)item[2]; this.gold = (int)item[3]; } } } public String getItemName() { return itemName; } public int getAtk() { return atk; } public int getDef() { return def; } public int getGold() { return gold; } }
package com.speakin.recorder.ui; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.speakin.recorder.R; import com.speakin.recorder.module.control.MasterControlManager; import com.speakin.recorder.module.control.SlaveControlManager; import com.speakin.recorder.utils.IpUtil; import org.json.JSONObject; public class MainActivity extends AppCompatActivity { private TextView textView; private TextView textView2; private MasterControlManager masterControlManager; private SlaveControlManager slaveControlManager; private boolean isMaster = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initData(); initView(); refreshIP(); } private void initData() { masterControlManager = new MasterControlManager(); slaveControlManager = new SlaveControlManager(); slaveControlManager.setControlManagerCallback(new SlaveControlManager.SlaveControlManagerCallback() { @Override public void onFoundMaster(String masterIp, JSONObject masterInfo) { textView2.setText(masterIp + " " + masterInfo.toString()); } @Override public void onConnectedMaster(String masterIp, Exception ex) { textView2.setText(masterIp + " connected"); } @Override public void onDisconnectMaster(String masterIp, Exception ex) { textView2.setText(masterIp + " disconnected"); } @Override public void onReceiveMessage(String message) { textView2.setText("message: " + message); } }); masterControlManager.setControlManagerCallback(new MasterControlManager.MasterControlManagerCallback() { @Override public void onServerError(Exception ex) { textView2.setText("server error: " + ex.getLocalizedMessage()); } @Override public void onClientConnected(String clientSocket) { textView2.setText("client: " + clientSocket); } @Override public void onClientDisconnect(String clientSocket) { textView2.setText("disconnected: " + clientSocket); } @Override public void onMessageReceive(String clientSocket, String message) { textView2.setText("message: " + message); } @Override public void onReceiveFile(String clientSocket, String filePath) { Toast.makeText(MainActivity.this, "receive file" + filePath, Toast.LENGTH_SHORT).show(); } }); } private void initView() { findViewById(R.id.masterBtn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { masterControlManager.start(); isMaster = true; } }); findViewById(R.id.slaveBtn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { slaveControlManager.start(); } }); textView = (TextView) findViewById(R.id.text1); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { refreshIP(); } }); textView2 = (TextView) findViewById(R.id.text2); findViewById(R.id.sendBtn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (isMaster) { masterControlManager.send("Hello, I am server :" + System.currentTimeMillis()); } else { slaveControlManager.send("Hello, I am client :" + System.currentTimeMillis()); } } }); findViewById(R.id.stopBtn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (isMaster) { masterControlManager.stop(); } else { slaveControlManager.stop(); } } }); findViewById(R.id.sendeFile).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { slaveControlManager.sendFile("/storage/emulated/0/wakeupIn/record/detected_1505991013.wav"); } }); } private void refreshIP() { String ip1 = IpUtil.getHostIP(); textView.setText("本机IP: " + ip1 ); } @Override protected void onDestroy() { super.onDestroy(); slaveControlManager.stop(); masterControlManager.stop(); } }
package fr.royalpha.bungeeannounce.command; import fr.royalpha.bungeeannounce.BungeeAnnouncePlugin; import fr.royalpha.bungeeannounce.manager.ConfigManager; import fr.royalpha.bungeeannounce.manager.MsgManager; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; /** * @author Royalpha */ public class MsgCommand extends Command { private String[] commands; private MsgManager msgManager; public MsgCommand(BungeeAnnouncePlugin plugin, String... commands) { super("bungee:msg", "", commands); this.commands = commands; this.msgManager = new MsgManager(); plugin.getProxy().getPluginManager().registerCommand(plugin, new ReplyCommand(plugin, this.msgManager)); } public void execute(CommandSender sender, String[] args) { if (sender instanceof ProxiedPlayer) { ProxiedPlayer player = (ProxiedPlayer) sender; if (args.length == 0) { sender.sendMessage(new TextComponent(ChatColor.RED + "Usage: /" + this.commands[0] + " <player> <msg>")); return; } String name = args[0]; if (ProxyServer.getInstance().getPlayer(name) != null) { ProxiedPlayer to = ProxyServer.getInstance().getPlayer(name); StringBuilder msgBuilder = new StringBuilder(); for (int i = 1; i < args.length; i++) msgBuilder.append(args[i]).append(" "); if (msgBuilder.toString().trim() == "") return; this.msgManager.message(player, to, msgBuilder.toString()); } else { player.sendMessage(new TextComponent(ConfigManager.Field.PM_PLAYER_NOT_ONLINE.getString().replaceAll("%PLAYER%", name))); } } else { sender.sendMessage(new TextComponent(ChatColor.RED + "You need to be a proxied player !")); } } }
package com.xhpower.qianmeng.dao; import com.xhpower.qianmeng.entity.Case; import com.baomidou.mybatisplus.mapper.BaseMapper; /** * <p> * Mapper 接口 * </p> * * @author xc * @since 2018-07-27 */ public interface CaseMapper extends BaseMapper<Case> { }
package script.groovy.runtime; import groovy.lang.GroovyClassLoader; import groovy.lang.GroovyObject; import groovy.lang.GroovySystem; import groovy.lang.MetaClassRegistry; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.FileFilterUtils; import org.apache.commons.lang.StringUtils; import org.codehaus.groovy.control.CompilationFailedException; import org.codehaus.groovy.control.CompilationUnit; import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.control.Phases; import org.codehaus.groovy.tools.GroovyClass; import script.ScriptRuntime; import script.groovy.object.GroovyObjectEx; import chat.errors.ChatErrorCodes; import chat.errors.CoreException; import chat.logs.LoggerEx; public class GroovyRuntime extends ScriptRuntime{ private static final String TAG = GroovyRuntime.class.getSimpleName(); private MyGroovyClassLoader classLoader; private ConcurrentHashMap<Thread, MyGroovyClassLoader> threadClassLoaderMap = new ConcurrentHashMap<>(); private AtomicLong latestVersion = new AtomicLong(0); private ClassLoader parentClassLoader; private List<ClassAnnotationHandler> annotationHandlers; private static GroovyRuntime instance; private Class<?> groovyObjectExProxyClass; public static GroovyRuntime getInstance() { return instance; } /* public static void main(String[] args) throws Exception { String path = "/Users/aplombchen/Dev/github/scriptcore/ScriptCore/test/"; Collection<File> files = FileUtils.listFiles(new File(path), FileFilterUtils.suffixFileFilter(".groovy"), FileFilterUtils.directoryFileFilter()); // for(File file : files) { // String key = file.getAbsolutePath().substring(path.length()); // int pos = key.lastIndexOf("."); // if(pos >= 0) { // key = key.substring(0, pos); // } // key = key.replace("/", "."); // } GroovyRuntime groovyRuntime = new GroovyRuntime(); groovyRuntime.setPath(path); GroovyBeanFactory beanFactory = new GroovyBeanFactory(); beanFactory.setGroovyRuntime(groovyRuntime); groovyRuntime.addClassAnnotationHandler(beanFactory); groovyRuntime.init(); GroovyObjectFactory factory = new GroovyObjectFactory(); factory.setGroovyRuntime(groovyRuntime); // boolean bool = true; // while(bool) { // groovyRuntime.redeploy(); // GroovyObjectEx<Callable> c1 = factory.getObject(a.B.class); //// String hello = c1.getObject().hello(); // c1.getObject().call(); // System.gc(); // System.out.println("used " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 + "K"); // } while(true) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = null; try { str = br.readLine(); if(str != null && str.equals("a")) { groovyRuntime.redeploy(); } new Thread(new Runnable() { @Override public void run() { GroovyObjectEx<Callable> c1 = factory.getObject(a.B.class); // String hello = c1.getObject().hello(); try { c1.getObject().call(); } catch (Exception e) { e.printStackTrace(); } System.gc(); System.out.println("used " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 + "K"); } }).start(); // GroovyObjectEx<Callable> c1 = factory.getObject(c.C.class); // c1.getObject().call(); // // GroovyObjectEx<Callable> d1 = factory.getObject(c.D.class); // d1.getObject().call(); // c.C c = new c.C(); // c.hello(); } catch (Throwable e) { e.printStackTrace(); } } // Runtime runtime = Runtime.getRuntime(); // long time; // for (int i = 0; i < 10000; i++) { // time = System.currentTimeMillis(); // groovyRuntime.redeploy(); // time = System.currentTimeMillis() - time; // // runtime.gc(); // System.out.println("total " + (runtime.totalMemory() / 1024) // + "K - free " + (runtime.freeMemory() / 1024) + "K = " // + ((runtime.totalMemory() - runtime.freeMemory()) / 1024) // + "K takes " + time); // } } */ public MyGroovyClassLoader registerClassLoaderOnThread() { MyGroovyClassLoader loader = classLoader; if (loader == null) return null; // MyGroovyClassLoader old = threadClassLoaderMap.putIfAbsent( // Thread.currentThread(), loader); // if (old == null) // return loader; // else // return old; return loader; } public void unregisterClassLoaderOnThread() { Thread thread = Thread.currentThread(); // MyGroovyClassLoader removed = threadClassLoaderMap.remove(thread); } public class ClassHolder { private Class<?> parsedClass; private GroovyObject cachedObject; public Class<?> getParsedClass() { return parsedClass; } public GroovyObject getCachedObject() { return cachedObject; } public void setCachedObject(GroovyObject cachedObject) { this.cachedObject = cachedObject; } } /* public class MyGroovyClassLoader extends GroovyClassLoader { private long version; private HashMap<String, ClassHolder> classCache; private HashSet<String> pendingGroovyClasses; public MyGroovyClassLoader(ClassLoader parentClassLoader, CompilerConfiguration cc) { super(parentClassLoader, cc); // final GroovyResourceLoader defaultResourceLoader = super.getResourceLoader(); // LoggerEx.info(TAG, "defaultResourceLoader " + defaultResourceLoader); // super.setResourceLoader(new GroovyResourceLoader() { // @Override // public URL loadGroovySource(String path) throws MalformedURLException { // LoggerEx.info(TAG, "load groovy source " + path); // if(defaultResourceLoader != null) { // return defaultResourceLoader.loadGroovySource(path); // } // return null; // } // }); classCache = new HashMap<>(); } public Class<?> parseGroovyClass(String key, File classFile) throws CoreException { try { return parseClass(classFile); } catch (CompilationFailedException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override public Class recompile(URL source, String name, Class oldClass) { LoggerEx.info(TAG, "Recompile " + source + " name " + name + " oldClass " + oldClass); try { return super.recompile(source, name, oldClass); } catch (CompilationFailedException | IOException e) { e.printStackTrace(); } return null; } @Override protected boolean isSourceNewer(URL source, Class cls) { LoggerEx.info(TAG, "isSourceNewer " + source + " cls " + cls); return true; } public ClassHolder getClass(String classPath) { return classCache.get(classPath); } public long getVersion() { return version; } public String toString() { return MyGroovyClassLoader.class.getSimpleName() + "#" + version; } } */ public class MyGroovyClassLoader extends GroovyClassLoader { private long version; private HashMap<String, ClassHolder> myClassCache; private HashSet<String> pendingGroovyClasses; private HashSet<String> parsingGroovyClasses; public MyGroovyClassLoader(ClassLoader parentClassLoader, CompilerConfiguration cc) { super(parentClassLoader, cc); // final GroovyResourceLoader defaultResourceLoader = super.getResourceLoader(); // LoggerEx.info(TAG, "defaultResourceLoader " + defaultResourceLoader); // super.setResourceLoader(new GroovyResourceLoader() { // @Override // public URL loadGroovySource(String path) throws MalformedURLException { // LoggerEx.info(TAG, "load groovy source " + path); // if(defaultResourceLoader != null) { // return defaultResourceLoader.loadGroovySource(path); // } // return null; // } // }); myClassCache = new HashMap<>(); } public Class<?> parseGroovyClass(String key, File classFile) throws CoreException { ClassHolder holder = myClassCache.get(key); if(holder != null && holder.getParsedClass() != null) { LoggerEx.info(TAG, "Load groovy class " + key + " from cache"); return holder.getParsedClass(); } try { Class<?> parsedClass = parseClass(classFile); if (parsedClass != null) { holder = new ClassHolder(); holder.parsedClass = parsedClass; myClassCache.put(key, holder); } LoggerEx.info(TAG, "Parse groovy class " + key + " successfully"); return parsedClass; } catch (Throwable e) { e.printStackTrace(); throw new CoreException( ChatErrorCodes.ERROR_GROOVY_PARSECLASS_FAILED, "Parse class " + classFile + " failed, " + e.getMessage()); } /*ClassHolder holder = classCache.get(key); if(holder != null && holder.getParsedClass() != null) { LoggerEx.info(TAG, "Load groovy class " + key + " from cache"); return holder.getParsedClass(); } try { CompilationUnit compileUnit = new CompilationUnit(); String name = key.replace("/", "."); int pos = name.lastIndexOf("."); if(pos != -1) { name = name.substring(0, pos); } compileUnit.addSource(name, FileUtils.openInputStream(classFile)); compileUnit.compile(Phases.CLASS_GENERATION); compileUnit.setClassLoader(this); GroovyClass target = null; for (Object compileClass : compileUnit.getClasses()) { GroovyClass groovyClass = (GroovyClass) compileClass; // try { // this.defineClass(groovyClass.getName(), groovyClass.getBytes()); // } catch (LinkageError e) { //// e.printStackTrace(); // } if(groovyClass.getName().equals(name)) { target = groovyClass; } } if(target == null) throw new IllegalStateException("Could not find proper class"); Class<?> parsedClass = this.loadClass(target.getName()); if (parsedClass != null) { holder = new ClassHolder(); holder.parsedClass = parsedClass; classCache.put(key, holder); } LoggerEx.info(TAG, "Parse groovy class " + key + " successfully"); return parsedClass; } catch (Throwable e) { e.printStackTrace(); throw new CoreException( ChatErrorCodes.ERROR_GROOVY_PARSECLASS_FAILED, "Parse class " + classFile + " failed, " + e.getMessage()); }*/ } @Override public Class loadClass(String name, boolean lookupScriptFiles, boolean preferClassOverScript) throws ClassNotFoundException, CompilationFailedException { // TODO Auto-generated method stub // System.out.println("name = " + name + " lookup = " + lookupScriptFiles + " prefer = " + preferClassOverScript); Class<?> loadedClass = null; if(pendingGroovyClasses.contains(name)) { // pendingGroovyClasses.remove(name); String key = name.replace(".", "/") + ".groovy"; if(!parsingGroovyClasses.contains(name)) { parsingGroovyClasses.add(name); try { loadedClass = parseGroovyClass(key, new File(path + key)); if(loadedClass != null) return loadedClass; } catch (CoreException e) { e.printStackTrace(); LoggerEx.error(TAG, "parse groovy class failed while load class, " + e.getMessage()); } } else { ClassHolder holder = myClassCache.get(key); if(holder != null && holder.getParsedClass() != null) { LoggerEx.info(TAG, "Load groovy class " + key + " from cache to avoid loop parse"); return holder.getParsedClass(); } } } boolean bool = parsingGroovyClasses.contains(name); if(bool) { LoggerEx.warn(TAG, "Loop parse class " + name + ", may cause this class available. PLEASE BE CAUTION! " + name); } loadedClass = super.loadClass(name, lookupScriptFiles, preferClassOverScript); return loadedClass; /* int indx = name.lastIndexOf('.'); String substr = name; if (indx != -1) { substr = name.substring(indx + 1); } String groovyFileName = substr + ".groovy" ; String path = "C:\\" + groovyFileName; try { return parseClass(new File(path).toString(), groovyFileName); } catch (CompilationFailedException exception) { throw exception; }*/ } public ClassHolder getClass(String classPath) { return myClassCache.get(classPath); } public long getVersion() { return version; } public String toString() { return MyGroovyClassLoader.class.getSimpleName() + "#" + version; } } public GroovyRuntime() { // instance = this; } public synchronized void init() throws CoreException { instance = this; redeploy(); } public boolean addClassAnnotationHandler(ClassAnnotationHandler handler) { if (annotationHandlers == null) annotationHandlers = new ArrayList<ClassAnnotationHandler>(); if (handler != null && !annotationHandlers.contains(handler)) return annotationHandlers.add(handler); return false; } public boolean removeClassAnnotationHandler(ClassAnnotationHandler handler) { if (annotationHandlers == null) annotationHandlers = new ArrayList<ClassAnnotationHandler>(); if (handler != null) return annotationHandlers.remove(handler); return false; } private MyGroovyClassLoader getNewClassLoader() { CompilerConfiguration cc = new CompilerConfiguration(); // cc.setMinimumRecompilationInterval(0); // cc.setRecompileGroovySource(true); cc.setSourceEncoding("utf8"); // cc.setTargetDirectory("/home/momo/Aplomb/workspaces/workspace (server)/Group/"); cc.setClasspath(path); // cc.setDebug(true); cc.setRecompileGroovySource(false); cc.setMinimumRecompilationInterval(Integer.MAX_VALUE); cc.setVerbose(false); cc.setDebug(false); // try { // cc.setOutput(new PrintWriter(new File("/Users/aplomb/Dev/taineng/test/log.txt"))); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } if (parentClassLoader == null) parentClassLoader = GroovyRuntime.class.getClassLoader(); return new MyGroovyClassLoader(parentClassLoader, cc); } public synchronized void redeploy() throws CoreException { MyGroovyClassLoader newClassLoader = null; MyGroovyClassLoader oldClassLoader = classLoader; boolean deploySuccessfully = false; final Map<ClassAnnotationHandler, Map<String, Class<?>>> handlerMap = new LinkedHashMap<ClassAnnotationHandler, Map<String, Class<?>>>(); try { newClassLoader = getNewClassLoader(); Collection<File> files = FileUtils.listFiles(new File(path), FileFilterUtils.suffixFileFilter(".groovy"), FileFilterUtils.directoryFileFilter()); // newClassLoader // .parseClass(new File( // "/home/momo/Aplomb/workspaces/ggtsworkspaces/Admin/groovy/services/IBaihuaService.groovy")); newClassLoader.pendingGroovyClasses = new HashSet<String>(); newClassLoader.parsingGroovyClasses = new HashSet<String>(); for(File file : files) { String absolutePath = file.getAbsolutePath(); int pathPos = absolutePath.indexOf(path); if(pathPos < 0) { LoggerEx.warn(TAG, "Find path " + path + " in file " + absolutePath + " failed, " + pathPos + ". Ignore..."); continue; } String key = file.getAbsolutePath().substring(pathPos + path.length()); int pos = key.lastIndexOf("."); if(pos >= 0) { key = key.substring(0, pos); } key = key.replace("/", "."); newClassLoader.pendingGroovyClasses.add(key); } for (File file : files) { String absolutePath = file.getAbsolutePath(); String key = file.getAbsolutePath().substring(absolutePath.indexOf(path) + path.length()); // Class<?> groovyClass = groovyServlet.getGroovyClass(); Class<?> groovyClass = newClassLoader.parseGroovyClass(key, file); if (annotationHandlers != null) { for (int i = 0; i < annotationHandlers.size(); i++) { ClassAnnotationHandler handler = annotationHandlers.get(i); // handler.setGroovyRuntime(this); Class<? extends Annotation> annotationClass = handler .handleAnnotationClass(this); if (annotationClass != null) { Annotation annotation = groovyClass .getAnnotation(annotationClass); if (annotation != null) { Map<String, Class<?>> classes = handlerMap .get(handler); if (classes == null) { classes = new HashMap<>(); handlerMap.put(handler, classes); } classes.put(key, groovyClass); } } else { handlerMap.put(handler, new HashMap<String, Class<?>>()); } } } } String[] strs = new String[] { "package script.groovy.runtime;", "import script.groovy.object.GroovyObjectEx", "class GroovyObjectExProxy implements GroovyInterceptable{", "private GroovyObjectEx<?> groovyObject;", "public GroovyObjectExProxy(GroovyObjectEx<?> groovyObject) {", "this.groovyObject = groovyObject;", "}", "def invokeMethod(String name, args) {", "Class<?> groovyClass = this.groovyObject.getGroovyClass();", "def calledMethod = groovyClass.metaClass.getMetaMethod(name, args);", "def returnObj = calledMethod?.invoke(this.groovyObject.getObject(), args);", "return returnObj;", "}", "}" }; String proxyClassStr = StringUtils.join(strs, "\r\n"); groovyObjectExProxyClass = newClassLoader.parseClass(proxyClassStr, "/script/groovy/runtime/GroovyObjectExProxy.groovy"); deploySuccessfully = true; } catch (Throwable t) { t.printStackTrace(); LoggerEx.fatal(TAG, "Redeploy occur unknown error, " + t.getMessage() + " redeploy aborted!!!"); if (t instanceof CoreException) throw (CoreException) t; else throw new CoreException(ChatErrorCodes.ERROR_GROOVY_UNKNOWN, "Groovy unknown error " + t.getMessage()); } finally { if (deploySuccessfully) { if (oldClassLoader != null) { try { MetaClassRegistry metaReg = GroovySystem .getMetaClassRegistry(); Class<?>[] classes = oldClassLoader.getLoadedClasses(); for (Class<?> c : classes) { LoggerEx.info(TAG, classLoader + " remove meta class " + c); metaReg.removeMetaClass(c); } oldClassLoader.clearCache(); oldClassLoader.close(); LoggerEx.info(TAG, "oldClassLoader " + oldClassLoader + " is closed"); } catch (Exception e) { e.printStackTrace(); LoggerEx.error(TAG, oldClassLoader + " close failed, " + e.getMessage()); } } long version = latestVersion.incrementAndGet(); newClassLoader.version = version; classLoader = newClassLoader; if (handlerMap != null && !handlerMap.isEmpty()) { Thread handlerThread = new Thread(new Runnable() { @Override public void run() { for(ClassAnnotationHandler annotationHandler : annotationHandlers) { Map<String, Class<?>> values = handlerMap.get(annotationHandler); if (values != null) { try { annotationHandler.handleAnnotatedClasses(values, classLoader); } catch (Throwable t) { t.printStackTrace(); LoggerEx.fatal(TAG, "Handle annotated classes failed, " + values + " class loader " + classLoader + " the handler " + annotationHandler + " is ignored!"); } } } } }); handlerThread.start(); try { handlerThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } LoggerEx.info(TAG, "Reload groovy scripts, current version is " + version); } else { if (newClassLoader != null) { try { newClassLoader.clearCache(); newClassLoader.close(); LoggerEx.info(TAG, "newClassLoader " + newClassLoader + " is closed"); } catch (IOException e) { e.printStackTrace(); } } } } } public static String path(Class<?> c) { return c.getName().replace(".", "/") + ".groovy"; } public <T> GroovyObjectEx<T> create(Class<?> c) { return create(path(c), null); } public <T> GroovyObjectEx<T> create(String groovyPath) { return create(groovyPath, null); } public <T> GroovyObjectEx<T> create(String groovyPath, Class<? extends GroovyObjectEx<T>> groovyObjectClass) { GroovyObjectEx<T> goe = null; if (groovyObjectClass != null) { try { Constructor<? extends GroovyObjectEx<T>> constructor = groovyObjectClass .getConstructor(String.class); goe = constructor.newInstance(groovyPath); } catch (Throwable e) { e.printStackTrace(); LoggerEx.error(TAG, "Initialize customized groovyObjectClass " + groovyObjectClass + " failed, " + e.getMessage()); return null; } } else { goe = new GroovyObjectEx<T>(groovyPath); } goe.setGroovyRuntime(this); return goe; } public <T> Object newObject(Class<?> c) { return newObject(path(c), null); } public <T> Object newObject(String groovyPath) { return newObject(groovyPath, null); } public <T> Object newObject(String groovyPath, Class<? extends GroovyObjectEx<T>> groovyObjectClass) { GroovyObjectEx<T> goe = null; if (groovyObjectClass != null) { try { Constructor<? extends GroovyObjectEx<T>> constructor = groovyObjectClass .getConstructor(String.class); goe = constructor.newInstance(groovyPath); } catch (Throwable e) { e.printStackTrace(); LoggerEx.error(TAG, "Initialize customized groovyObjectClass " + groovyObjectClass + " failed, " + e.getMessage()); return null; } } else { goe = new GroovyObjectEx<T>(groovyPath); } goe.setGroovyRuntime(this); Object obj = null; try { Constructor<?> constructor = groovyObjectExProxyClass.getConstructor(GroovyObjectEx.class); obj = constructor.newInstance(goe); } catch (Throwable e) { e.printStackTrace(); LoggerEx.error(TAG, "New proxy instance " + groovyObjectClass + " failed, " + e.getMessage()); } return obj; } public Object getProxyObject(GroovyObjectEx<?> groovyObject) { Object obj = null; try { GroovyBeanFactory factory = GroovyBeanFactory.getInstance(); Class<?> proxyClass = factory.getProxyClass(groovyObject.getGroovyClass().getName()); if(proxyClass != null) { Constructor<?> constructor = proxyClass.getConstructor(GroovyObjectEx.class); obj = constructor.newInstance(groovyObject); } } catch (Throwable e) { e.printStackTrace(); LoggerEx.error(TAG, "New proxy instance(getProxyObject) " + groovyObject.getGroovyPath() + " failed, " + e.getMessage()); } return obj; } public AtomicLong getLatestVersion() { return latestVersion; } public MyGroovyClassLoader getClassLoader() { return classLoader; } public ClassLoader getParentClassLoader() { return parentClassLoader; } public void setParentClassLoader(ClassLoader parentClassLoader) { this.parentClassLoader = parentClassLoader; } public List<ClassAnnotationHandler> getAnnotationHandlers() { return annotationHandlers; } public void setAnnotationHandlers( List<ClassAnnotationHandler> annotationHandlers) { if (this.annotationHandlers != null) { this.annotationHandlers.addAll(annotationHandlers); } else { this.annotationHandlers = annotationHandlers; } } public Class<?> getClass(String classStr) { if(StringUtils.isBlank(classStr)) return null; classStr = classStr.replace(".", "/") + ".groovy"; if(classLoader != null) { ClassHolder holder = classLoader.getClass(classStr); if(holder != null) { return holder.getParsedClass(); } } return null; } }
package entity.database; import com.google.api.gax.paging.Page; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.storage.Blob; import com.google.cloud.storage.Bucket; import com.google.firebase.FirebaseApp; import com.google.firebase.FirebaseOptions; import com.google.firebase.cloud.StorageClient; import javafx.scene.image.Image; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Class Firebase * Created by Alexis on 14/01/2019 */ public class Firebase { // http://googleapis.github.io/google-cloud-java/google-cloud-clients/apidocs/com/google/cloud/storage/Bucket.html public static Bucket bucket; private static final String bucketName = "gosecuri-f61f0"; public static void connect() { if (bucket == null) { try { FileInputStream serviceAccount = new FileInputStream("src/main/resources/assets/firebase/serviceAccountKey.json"); FirebaseOptions options = new FirebaseOptions.Builder() .setCredentials(GoogleCredentials.fromStream(serviceAccount)) .setStorageBucket(bucketName + ".appspot.com") .setDatabaseUrl("https://" + bucketName + ".firebaseio.com") .build(); FirebaseApp.initializeApp(options); bucket = StorageClient.getInstance().bucket(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } public static Blob getImage( String name ) { if(bucket != null) { return bucket.get(name); } return null; } public static List<Image> getAllImage() { List<Image> images = new ArrayList<>(); if(bucket != null) { Firebase.bucket.list().iterateAll().forEach((blob) -> { String img_url = "https://firebasestorage.googleapis.com/v0/b/" + bucketName + ".appspot.com/o/" + blob.getName() + "?alt=media&token=" + blob.getMetadata().get("firebaseStorageDownloadTokens"); System.out.println(img_url); images.add(new Image(img_url)); }); } return images; } }
package com.facebook.react.modules.common; import com.facebook.common.e.a; import com.facebook.react.bridge.CatalystInstance; import com.facebook.react.bridge.NativeModule; public class ModuleDataCleaner { public static void cleanDataFromModules(CatalystInstance paramCatalystInstance) { for (NativeModule nativeModule : paramCatalystInstance.getNativeModules()) { if (nativeModule instanceof Cleanable) { StringBuilder stringBuilder = new StringBuilder("Cleaning data from "); stringBuilder.append(nativeModule.getName()); a.a("ReactNative", stringBuilder.toString()); ((Cleanable)nativeModule).clearSensitiveData(); } } } public static interface Cleanable { void clearSensitiveData(); } } /* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\modules\common\ModuleDataCleaner.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.espendwise.manta.web.forms; import com.espendwise.manta.model.view.AccountListView; import com.espendwise.manta.model.view.DistributorListView; import com.espendwise.manta.model.view.SiteListView; import com.espendwise.manta.model.view.UserListView; import com.espendwise.manta.spi.Initializable; import com.espendwise.manta.spi.Resetable; import com.espendwise.manta.util.Pair; import com.espendwise.manta.util.SelectableObjects; import com.espendwise.manta.util.Utility; import com.espendwise.manta.util.validation.Validation; import com.espendwise.manta.web.util.LocateAssistant; import com.espendwise.manta.web.validator.OrderFilterFormValidator; import java.util.ArrayList; import java.util.List; @Validation(OrderFilterFormValidator.class) public class OrderFilterForm extends WebForm implements Resetable, Initializable { private List<AccountListView> filteredAccounts; private String accountFilter; private List<DistributorListView> filteredDistributors; private String distributorFilter; private List<UserListView> filteredUsers; private String userFilter; private List<SiteListView> filteredSites; private String siteFilter; private String orderFromDate; private String orderToDate; private String outboundPONum; private String erpPONum; private String customerPONum; private String webOrderConfirmationNum; private String refOrderNum; private String orderMethod; private String siteZipCode; private String placedBy; private List<Pair<String, String>> orderSources; private SelectableObjects searchOrderStatuses; private boolean init; public OrderFilterForm() { super(); } public String getAccountFilter() { return accountFilter; } public void setAccountFilter(String accountFilter) { this.accountFilter = accountFilter; } public String getDistributorFilter() { return distributorFilter; } public void setDistributorFilter(String distributorFilter) { this.distributorFilter = distributorFilter; } public String getUserFilter() { return userFilter; } public void setUserFilter(String userFilter) { this.userFilter = userFilter; } public List<AccountListView> getFilteredAccounts() { return filteredAccounts; } public void setFilteredAccounts(List<AccountListView> filteredAccounts) { this.filteredAccounts = filteredAccounts; } public String getFilteredAccountCommaNames() { return LocateAssistant.getFilteredAccountCommaNames(getFilteredAccounts()); } public String getFilteredAccountCommaIds() { return LocateAssistant.getFilteredAccountCommaIds(getFilteredAccounts()); } public List<DistributorListView> getFilteredDistributors() { return filteredDistributors; } public void setFilteredDistributors(List<DistributorListView> filteredDistributors) { this.filteredDistributors = filteredDistributors; } public String getFilteredDistributorCommaNames() { return LocateAssistant.getFilteredDistrCommaNames(getFilteredDistributors()); } public String getFilteredDistributorCommaIds() { return LocateAssistant.getFilteredDistrCommaIds(getFilteredDistributors()); } public List<UserListView> getFilteredUsers() { return filteredUsers; } public void setFilteredUsers(List<UserListView> filteredUsers) { this.filteredUsers = filteredUsers; } public String getFilteredUserCommaNames() { StringBuilder builder = new StringBuilder(); if (Utility.isSet(filteredUsers)) { for (UserListView value : filteredUsers) { builder.append((builder.length() > 0) ? ", " + value.getUserName() : value.getUserName()); } } return builder.toString(); } public String getFilteredUserCommaIds() { return LocateAssistant.getFilteredUserCommaIds(getFilteredUsers()); } public List<SiteListView> getFilteredSites() { return filteredSites; } public void setFilteredSites(List<SiteListView> filteredSites) { this.filteredSites = filteredSites; } public String getSiteFilter() { return siteFilter; } public void setSiteFilter(String siteFilter) { this.siteFilter = siteFilter; } public String getFilteredSiteCommaNames() { return LocateAssistant.getFilteredSiteCommaNames(getFilteredSites()); } public String getFilteredSiteCommaIds() { return LocateAssistant.getFilteredSiteCommaIds(getFilteredSites()); } public String getCustomerPONum() { return customerPONum; } public void setCustomerPONum(String customerPONum) { this.customerPONum = customerPONum; } public String getErpPONum() { return erpPONum; } public void setErpPONum(String erpPONum) { this.erpPONum = erpPONum; } public String getOrderFromDate() { return orderFromDate; } public void setOrderFromDate(String orderFromDate) { this.orderFromDate = orderFromDate; } public String getOrderToDate() { return orderToDate; } public void setOrderToDate(String orderToDate) { this.orderToDate = orderToDate; } public String getOrderMethod() { return orderMethod; } public void setOrderMethod(String orderMethod) { this.orderMethod = orderMethod; } public String getOutboundPONum() { return outboundPONum; } public void setOutboundPONum(String outboundPONum) { this.outboundPONum = outboundPONum; } public String getPlacedBy() { return placedBy; } public void setPlacedBy(String placedBy) { this.placedBy = placedBy; } public String getRefOrderNum() { return refOrderNum; } public void setRefOrderNum(String refOrderNum) { this.refOrderNum = refOrderNum; } public String getSiteZipCode() { return siteZipCode; } public void setSiteZipCode(String siteZipCode) { this.siteZipCode = siteZipCode; } public String getWebOrderConfirmationNum() { return webOrderConfirmationNum; } public void setWebOrderConfirmationNum(String webOrderConfirmationNum) { this.webOrderConfirmationNum = webOrderConfirmationNum; } public SelectableObjects getSearchOrderStatuses() { return searchOrderStatuses; } public void setSearchOrderStatuses(SelectableObjects searchOrderStatuses) { this.searchOrderStatuses = searchOrderStatuses; } public List<Pair<String, String>> getOrderSources() { return orderSources; } public void setOrderSources(List<Pair<String, String>> orderSources) { this.orderSources = orderSources; } @Override public void initialize() { reset(); this.init = true; } @Override public boolean isInitialized() { return this.init; } @Override public void reset() { this.filteredAccounts = new ArrayList(); this.accountFilter = null; this.filteredDistributors = new ArrayList(); this.distributorFilter = null; this.filteredUsers = new ArrayList(); this.userFilter = null; this.filteredSites = new ArrayList(); this.siteFilter = null; this.orderFromDate = null; this.orderToDate = null; this.outboundPONum = null; this.erpPONum = null; this.customerPONum = null; this.webOrderConfirmationNum = null; this.refOrderNum = null; this.orderMethod = null; this.siteZipCode = null; this.placedBy = null; } }
package org.research.flume.sink; /** * @fileName: CustomSinkTest.java * @description: CustomSinkTest.java类说明 * @author: by echo huang * @date: 2020-08-01 15:40 */ public class CustomSinkTest { }
package com.goldgov.dygl.module.portal.webservice.studyranking; import java.net.URL; import javax.xml.namespace.QName; import javax.xml.ws.BindingProvider; import javax.xml.ws.Service; import javax.xml.ws.WebEndpoint; import javax.xml.ws.WebServiceClient; import javax.xml.ws.WebServiceException; import javax.xml.ws.WebServiceFeature; /** * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.1-b01- * Generated source version: 2.2 * */ @WebServiceClient(name = "ShellInfoWebserviceServiceService", targetNamespace = "http://server.shellinfo.webservice.eorchis.com/", wsdlLocation = "http://ol.dyglel.shenhua.cc/ol/webservice/studyRankingWebService?wsdl") public class ShellInfoWebserviceServiceService extends Service { private final static URL SHELLINFOWEBSERVICESERVICESERVICE_WSDL_LOCATION; private final static WebServiceException SHELLINFOWEBSERVICESERVICESERVICE_EXCEPTION; private final static QName SHELLINFOWEBSERVICESERVICESERVICE_QNAME = new QName("http://server.shellinfo.webservice.eorchis.com/", "ShellInfoWebserviceServiceService"); private static String WSDL_LOCATION = null; static { WebServiceException e = null; SHELLINFOWEBSERVICESERVICESERVICE_WSDL_LOCATION = ShellInfoWebserviceServiceService.class.getResource("./ShellInfoWebserviceServiceService.wsdl"); SHELLINFOWEBSERVICESERVICESERVICE_EXCEPTION = e; } public ShellInfoWebserviceServiceService() { super(__getWsdlLocation(), SHELLINFOWEBSERVICESERVICESERVICE_QNAME); } public ShellInfoWebserviceServiceService(WebServiceFeature... features) { super(__getWsdlLocation(), SHELLINFOWEBSERVICESERVICESERVICE_QNAME, features); } public ShellInfoWebserviceServiceService(URL wsdlLocation) { super(__getWsdlLocation(), SHELLINFOWEBSERVICESERVICESERVICE_QNAME); WSDL_LOCATION = wsdlLocation.toString(); } public ShellInfoWebserviceServiceService(URL wsdlLocation, WebServiceFeature... features) { super(wsdlLocation, SHELLINFOWEBSERVICESERVICESERVICE_QNAME, features); } public ShellInfoWebserviceServiceService(URL wsdlLocation, QName serviceName) { super(wsdlLocation, serviceName); } public ShellInfoWebserviceServiceService(URL wsdlLocation, QName serviceName, WebServiceFeature... features) { super(wsdlLocation, serviceName, features); } /** * * @return * returns ShellInfo */ @WebEndpoint(name = "ShellInfoPort") public ShellInfo getShellInfoPort() { ShellInfo port = super.getPort(new QName("http://server.shellinfo.webservice.eorchis.com/", "ShellInfoPort"), ShellInfo.class); ((BindingProvider) port).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "wsuser"); ((BindingProvider) port).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "12345678"); ((BindingProvider) port).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, WSDL_LOCATION); return port; //return super.getPort(new QName("http://server.shellinfo.webservice.eorchis.com/", "ShellInfoPort"), ShellInfo.class); } /** * * @param features * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values. * @return * returns ShellInfo */ @WebEndpoint(name = "ShellInfoPort") public ShellInfo getShellInfoPort(WebServiceFeature... features) { return super.getPort(new QName("http://server.shellinfo.webservice.eorchis.com/", "ShellInfoPort"), ShellInfo.class, features); } private static URL __getWsdlLocation() { if (SHELLINFOWEBSERVICESERVICESERVICE_EXCEPTION!= null) { throw SHELLINFOWEBSERVICESERVICESERVICE_EXCEPTION; } return SHELLINFOWEBSERVICESERVICESERVICE_WSDL_LOCATION; } }
package ga; import ga.crossover.Crossover; import ga.crossover.CrossoverNPoint; import ga.fitness.Fitness; import ga.fitness.FitnessDefault; import ga.initialize.Initialize; import ga.initialize.InitializeDefault; import ga.mutation.Mutate; import ga.mutation.MutateTrialVector; import ga.selection.MatingPlan; import ga.trialVector.TrialVector; import ga.trialVector.TrialVectorBest; import java.util.ArrayList; import java.util.List; import neural_net.Network; import driver.DataPoint; /** * Differential Evolution Algorithm. */ public class DE { private Population population; private double beta; private Fitness fitness; private Crossover crossover; /** * Initializes parameters. * * @param populationSize * The size of the population to construct * @param beta * The beta value for the algorithm (empirical studies * suggest 0.5) */ public DE(int populationSize, int chromosomeSize, double beta) { // initialize population to correct size Initialize init = new InitializeDefault(); this.population = init.initializePopulation(populationSize, chromosomeSize); // set the learning rate this.beta = beta; // set the fitness and crossover methods that will be used this.fitness = new FitnessDefault(); this.crossover = new CrossoverNPoint(); } /** * Runs a single generation for the differential equation algorithm. * * @param neuralNetwork The neural network that will be trained using the DE. * @param trainSet The set of training data that will be used. */ public void runGeneration(Network neuralNetwork, List<DataPoint> trainSet) { // create a new empty population and mating plan ArrayList<Individual> newPopulation = new ArrayList<Individual>(); MatingPlan plan = new MatingPlan(); // loop through every individual in the current population for (Individual individual : population.getIndividuals()) { // get the best individual in the population Individual bestInPop = population.getMostFit(); // get a random individual that has not already been chosen Individual two = population.getRandomIndividual(); while (!two.geneticallyEquals(bestInPop) && !two.geneticallyEquals(individual)) { two = population.getRandomIndividual(); } // get another random individual that has not already been chosen Individual three = population.getRandomIndividual(); while (!three.geneticallyEquals(bestInPop) && !three.geneticallyEquals(two) && !three.geneticallyEquals(individual)) { three = population.getRandomIndividual(); } // create a trial vector using the best individual and 2 random individuals TrialVector trialVector = new TrialVectorBest(bestInPop, two, three, beta); // set the current individual to breed with the new trial vector that has been created plan.add(individual, trialVector.getTrialVector()); } // need to make sure the individual objects in the population // are preserved. Population newPop = crossover.crossOver(population, plan); fitness.calculateFitness(newPop, neuralNetwork, trainSet); // loop through the new and old populations for (int i = 0; i < population.size(); i++) { // get a member from the old population and // the corresponding member from the new population Individual oldIndividual = population.getIndividuals().get(i); Individual newIndividual = newPop.getIndividuals().get(i); // add the better of the two individuals to the new population if (newIndividual.getFitness() > oldIndividual.getFitness()) { newPopulation.add(newIndividual); } else { newPopulation.add(oldIndividual); } } // move on to the next generation population = new Population(newPopulation); } /** * @return The current population of the algorithm. */ public Population getPopulation() { return population; } }
package businesscode; /** * * @Filename PerCapitaIncomeRestaurants.java * * @Version $Id: PerCapitaIncomeRestaurants.java,v 1.0 2014/02/25 09:23:00 $ * * @Revisions * Initial Revision */ import connect.JDBCMySQLMain; import gui.Graph; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * <p/> * The analysis file for determing the results * * @author Omkar Hegde */ public class PerCapitaIncomeRestaurants { String query = null; // consructor public PerCapitaIncomeRestaurants() { query = "SELECT c.county_name AS countyName," + " c.state AS state ," + " c.year AS year," + " c.per_capita_income AS perCapitaIncome," + " SUM(r.count) AS restaurantCount " + "FROM county AS c," + " restaurant AS r " + "WHERE c.county_name = r.county_name " + "AND c.state = r.state " + "AND c.year = r.year " + "GROUP BY c.county_name, " + " c.state, " + " c.year;"; } /** * getResults() * Runs query and gets results * */ public void getResults() { JDBCMySQLMain connectToDB = new JDBCMySQLMain(); ResultSet resultSet = connectToDB.executeQuery(query); HashMap<Integer, HashMap> collection = new HashMap<Integer, HashMap>(); List<String> countyStateList = new ArrayList<String>(); HashMap<String, Double> perCapitaIncome11 = new HashMap<String, Double>(); HashMap<String, Integer> numRestaurants11 = new HashMap<String, Integer>(); HashMap<String, Double> perCapitaIncome12 = new HashMap<String, Double>(); HashMap<String, Integer> numRestaurants12 = new HashMap<String, Integer>(); HashMap<String, Double> perCapitaIncome13 = new HashMap<String, Double>(); HashMap<String, Integer> numRestaurants13 = new HashMap<String, Integer>(); try { // result is iterated while (resultSet.next()) { int year = resultSet.getInt("year"); String countyState = resultSet.getString("countyName") + " " + resultSet.getString("state"); double perCapitaIncome = resultSet.getDouble("perCapitaIncome"); int restaurants = resultSet.getInt("restaurantCount"); if (!countyStateList.contains(countyState)) countyStateList.add(countyState); if (year == 2011) { perCapitaIncome11.put(countyState, perCapitaIncome); numRestaurants11.put(countyState, restaurants); } else if (year == 2012) { perCapitaIncome12.put(countyState, perCapitaIncome); numRestaurants12.put(countyState, restaurants); } else if (year == 2013) { perCapitaIncome13.put(countyState, perCapitaIncome); numRestaurants13.put(countyState, restaurants); } } } catch (SQLException exception) { exception.printStackTrace(); } collection.put(20111, perCapitaIncome11); collection.put(20112, numRestaurants11); collection.put(20121, perCapitaIncome12); collection.put(20122, numRestaurants12); collection.put(20131, perCapitaIncome13); collection.put(20132, numRestaurants13); calculate(collection, countyStateList); } /** * Analysis of the resuslts * * @param collection * @param countyStateList */ public void calculate(HashMap<Integer, HashMap> collection, List<String> countyStateList) { double totalObesityPercent = 0; int totalRestaurants = 0; HashMap<String, Double> perCapita11 = (HashMap<String, Double>) collection.get(20111); HashMap<String, Integer> numRestaurants11 = (HashMap<String, Integer>) collection.get(20112); HashMap<String, Double> perCapita12 = (HashMap<String, Double>) collection.get(20121); HashMap<String, Integer> numRestaurants12 = (HashMap<String, Integer>) collection.get(20122); HashMap<String, Double> perCapita13 = (HashMap<String, Double>) collection.get(20131); HashMap<String, Integer> numRestaurants13 = (HashMap<String, Integer>) collection.get(20132); int increasing1 = 0; int decreasing1 = 0; int incorrectCount1 = 0; int increasing2 = 0; int decreasing2 = 0; int incorrectCount2 = 0; int increasing3 = 0; int decreasing3 = 0; int incorrectCount3 = 0; for (String countyState : countyStateList) { if (numRestaurants11.get(countyState) > numRestaurants12.get(countyState)) { if (perCapita11.get(countyState) < perCapita12.get(countyState)) { increasing1++; } else { incorrectCount1++; } } else { if (perCapita11.get(countyState) > perCapita12.get(countyState)) { decreasing1++; } else { incorrectCount1++; } } } for (String countyState : countyStateList) { if (numRestaurants12.get(countyState) > numRestaurants13.get(countyState)) { if (perCapita12.get(countyState) > perCapita13.get(countyState)) { increasing2++; } else { incorrectCount2++; } } else { if (perCapita12.get(countyState) < perCapita13.get(countyState)) { decreasing2++; } else { incorrectCount2++; } } } for (String countyState : countyStateList) { if (numRestaurants11.get(countyState) > numRestaurants13.get(countyState)) { if (perCapita11.get(countyState) > perCapita13.get(countyState)) { increasing1++; } else { incorrectCount3++; } } else { if (perCapita11.get(countyState) < perCapita13.get(countyState)) { decreasing3++; } else { incorrectCount3++; } } } System.out.println("Increasing 11-12: " + increasing1); System.out.println("Decreasing 11-12: " + decreasing1); System.out.println("Incorrect 11-12: " + incorrectCount1); System.out.println(""); System.out.println(""); System.out.println("Increasing 12-13: " + increasing2); System.out.println("Decreasing 12-13: " + decreasing2); System.out.println("Incorrect 12-13: " + incorrectCount2); System.out.println(""); System.out.println(""); System.out.println("Increasing 11-13: " + increasing3); System.out.println("Decreasing 11-13: " + decreasing3); System.out.println("Incorrect 11-13: " + incorrectCount3); //FOR GRAPH ArrayList<Double> list; list = new ArrayList(); double total1 = increasing1 + decreasing1 + incorrectCount1; double total2 = increasing2 + decreasing2 + incorrectCount2; double total3 = increasing3 + decreasing3 + incorrectCount3; list.add((increasing1 / total1) * 100); list.add((increasing2 / total2) * 100); list.add((double) ((increasing3 / total3) * 100)); list.add((decreasing1 / total1) * 100); list.add((decreasing2 / total2) * 100); list.add((decreasing3 / total3) * 100); list.add((incorrectCount1 / total1) * 100); list.add((incorrectCount2 / total2) * 100); list.add((incorrectCount3 / total3) * 100); ArrayList<String> label; label = new ArrayList(); label.add("2011-2012"); label.add("2012-2013"); label.add("2011-2013"); ArrayList<String> symbRep; symbRep = new ArrayList(); symbRep.add("Increasing"); symbRep.add("Decreasing"); symbRep.add("Incorrect"); new Graph().plot(list, 3, label, symbRep, "Per Capita Income and Number of Restaurants"); } public String getQuery() { return query; } }
package com.packtpub.javaee8.tracing; import com.uber.jaeger.Configuration; import io.opentracing.util.GlobalTracer; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; @WebListener public class OpenTracingContextInitializer implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { Configuration configuration = Configuration.fromEnv(); GlobalTracer.register(configuration.getTracer()); } }
package edu.northeastern.cs5200; import java.sql.*; public class Connection { private static final String DRIVER = "com.mysql.jdbc.Driver"; private static final String URL = "jdbc:mysql://cs5200-fall2018-melacheruvu.cib6nobpgzxs.us-east-2.rds.amazonaws.com/cs5200_assignment3?useSSL=false&allowPublicKeyRetrieval=true"; private static final String USER = "Rachna"; private static final String PASSWORD = "yahoo12$34"; public static java.sql.Connection getConnection() throws ClassNotFoundException, SQLException { Class.forName(DRIVER); return DriverManager.getConnection(URL, USER, PASSWORD); } public static void closeConnection(java.sql.Connection conn) { try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package com.rednavis.application.dto; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; /** * Created by Eugene Tsydzik * on 4/14/18. */ @Data @JsonIgnoreProperties(ignoreUnknown = true) public class Baseline { private String tenantId; private String vertical; private String baselineName; private int baselineId; private int userId; private String userName; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; Baseline baseline = (Baseline) o; if (baselineId != baseline.baselineId) return false; if (userId != baseline.userId) return false; if (tenantId != null ? !tenantId.equals(baseline.tenantId) : baseline.tenantId != null) return false; if (vertical != null ? !vertical.equals(baseline.vertical) : baseline.vertical != null) return false; if (baselineName != null ? !baselineName.equals(baseline.baselineName) : baseline.baselineName != null) return false; return userName != null ? userName.equals(baseline.userName) : baseline.userName == null; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (tenantId != null ? tenantId.hashCode() : 0); result = 31 * result + (vertical != null ? vertical.hashCode() : 0); result = 31 * result + (baselineName != null ? baselineName.hashCode() : 0); result = 31 * result + baselineId; result = 31 * result + userId; result = 31 * result + (userName != null ? userName.hashCode() : 0); return result; } }
package ru.sberbank.ex2.steps; import io.qameta.allure.Step; import org.junit.jupiter.api.Assertions; import org.openqa.selenium.WebDriver; import ru.sberbank.ex2.GeneralMethods; import ru.sberbank.ex2.pageObjects.FormTravelInsurancePage; import java.util.Map; public class FormTravelInsuranceSteps { private WebDriver driver; private FormTravelInsurancePage formTravelInsurancePage; public FormTravelInsuranceSteps(WebDriver driver) { this.driver = driver; this.formTravelInsurancePage = new FormTravelInsurancePage(driver); } @Step("Заполнить поля формы") public void fillFields(String field, String value) { formTravelInsurancePage.fillFormField(field, value); } @Step("Проверить заполнение полей формы") public void checkFieldsFilling(Map<String, String> fieldsAndValues) { fieldsAndValues.forEach((key, value)-> Assertions.assertEquals( formTravelInsurancePage.getFormFieldValue(key), value ) ); GeneralMethods.getScreenshot(driver); } @Step("Нажать кнопку 'продолжить'") public void clickContinueButton() { formTravelInsurancePage.clickContinueBtn(); } @Step("Проверить собщение - {errorMessage}") public void checkErrorMessage(String errorMessage) { Assertions.assertEquals( formTravelInsurancePage.getErrorText(), errorMessage ); GeneralMethods.moveToElement(driver, formTravelInsurancePage.getErrorMessage()); GeneralMethods.getScreenshot(driver); } }
package com.example.restauth.domain; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; /** * DTO for password reset request */ public class PasswordResetRequest { private String oldPassword; private String newPassword; @JsonCreator public PasswordResetRequest(@JsonProperty("oldPassword") String oldPassword, @JsonProperty("newPassword") String newPassword) { this.oldPassword = oldPassword; this.newPassword = newPassword; } public String getOldPassword() { return this.oldPassword; } public String getNewPassword() { return this.newPassword; } }
package com.designPattern.structural.facade; import java.sql.Connection; public class MySQLHelper { public Connection getMySQLConnection() { System.out.println("getMySQLConnection"); return null; } public void generateMySQLHTMLReport(String tableName, Connection connection) { // TO DO for HTML Report by MySQL. System.out.println("generateMySQLHTMLReport Called."); } public void generateMySQLPDFReport(String tableName, Connection connection) { // TO DO for PDF Report by MySQL. System.out.println("generateMySQLPDFReport Called."); } }
package org.tit_admin_dao.core; import org.tit_admin_model.core.entity.User; /** * @author 刘晓勇 * */ public interface UserDao { /** * @return * @throws Exception */ public User insert(User u); public User findByUsername(String username); public Object findByEmail(String email); public User update(User user); }
package edu.classm8web.services; import edu.classm8web.dao.Database; import edu.classm8web.dto.M8; import edu.classm8web.exception.DatabaseException; public class SecurityService { private static SecurityService instance; public static SecurityService getInstance() { if (SecurityService.instance == null) { SecurityService.instance = new SecurityService(); } return SecurityService.instance; } public long checkLogin(String email, String password) throws DatabaseException { long ret = -1; M8 dude = null; dude = Database.getInstance().getStudentbyPasswordAndEMail(email, password); if (dude != null) ret = dude.getId(); return ret; } }
package com.lera.vehicle.reservation.service.vehicle; import com.lera.vehicle.reservation.domain.vehicle.Brand; import com.lera.vehicle.reservation.repository.vehicle.BrandRepository; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.util.Arrays; import java.util.List; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @RunWith(MockitoJUnitRunner.class) public class BrandServiceTest { @Mock private BrandRepository brandRepository; private BrandService brandService; @Before public void setUp() throws Exception { brandService = new BrandServiceImpl(brandRepository); } @Test public void testListModels() { // given given(brandService.listBrands()).willReturn(Arrays.asList(new Brand(), new Brand())); // when List<Brand> brands = brandService.listBrands(); // then assertThat(brands.size()).isEqualTo(2); verify(brandRepository, times(1)).findAll(); } @Test public void testGetVehicle() { // given given(brandRepository.findById(1L)).willReturn(Optional.of(new Brand())); // when Brand brand = brandService.getById(1L); // then assertThat(brand).isEqualTo(new Brand()); verify(brandRepository, times(1)).findById(1L); } }
package miniMipSim.pipeline.parts; public class RegisterToken implements Comparable<RegisterToken> { public int registerName; public int registerValue; /** * Constructor * * @param name * @param value */ public RegisterToken(int name, int value) { this.registerName = name; this.registerValue = value; } /** * Copies an instruction token into this. * * @param t - the register token to copy */ public void copy(RegisterToken t) { this.registerName = t.registerName; this.registerValue = t.registerValue; } /** * Comparator. */ public int compareTo(RegisterToken t) { return (registerName - t.registerName); } /** * returns a string with the register in assembler. */ public String toString() { return (new StringBuilder("<R").append(registerName).append(",") .append(registerValue).append(">")).toString(); } }
package ru.alxant.worker.model; import org.apache.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import ru.alxant.worker.view.StartDayPage; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.util.ArrayList; /** * Created by Alxan on 02.02.2017. */ public class WorkXML { private static final Logger log = Logger.getLogger(WorkXML.class); public static String[] servicesWork(String xmlName) { DocumentBuilder documentBuilder = null; try { documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException e) { log.error(e.getMessage(), e); e.printStackTrace(); } Document document = null; try { document = documentBuilder.parse(xmlName); } catch (SAXException e) { log.error(e.getMessage(), e); e.printStackTrace(); } catch (IOException e) { log.error(e.getMessage(), e); e.printStackTrace(); } Node root = document.getDocumentElement(); NodeList services = root.getChildNodes(); ArrayList<String> listTmp = new ArrayList<String>(); for (int i = 0; i < services.getLength(); i++) { Node service = services.item(i); if (service.getNodeType() != Node.TEXT_NODE) { NodeList serviceProps = service.getChildNodes(); for (int j = 0; j < serviceProps.getLength(); j++) { Node serviceProp = serviceProps.item(j); if (serviceProp.getNodeType() != Node.TEXT_NODE) { listTmp.add(serviceProp.getChildNodes().item(0).getTextContent()); } } } } String[] result = new String[listTmp.size()]; for(int i=0;i<listTmp.size();i++){ result[i] = listTmp.get(i); } return result; } }
package edu.htu.ap.lesson19.template; public class EgyptTeaMaker extends TeaMaker_V2{ public EgyptTeaMaker (int tea, int sugar, int water) { super(tea,sugar,water); } @Override public void addSugar() { System.out.println("Adding alot of sugar"); } }
package com.gikk.chat.manual; import com.gikk.ChatSingleton; import com.gikk.SchedulerSingleton; import com.gikk.SystemConfig; import com.gikk.chat.AbstractChatCommand; import com.gikk.twirk.types.emote.Emote; import com.gikk.twirk.types.users.TwitchUser; import java.util.HashSet; import java.util.List; import java.util.Set; /** * * @author Gikkman */ public class LootingCommand extends AbstractChatCommand { private final static String COMMAND = "LootTheRoom"; private final static int LOOT_TIME_MINUTES = 3; private final Set<String> commandWords = new HashSet<>(); private final Set<TwitchUser> lootingUsers = new HashSet<>(); private final String currency; private final double payout; private LootingCommand(boolean completed, long secondsPlayed) { commandWords.add(COMMAND); currency = SystemConfig.CURRENCY; payout = 30; } private static void enableLooting(boolean completed, long secondsPlayed) { LootingCommand cmd = new LootingCommand(completed, secondsPlayed); ChatSingleton.GET().addChatCommand(cmd); SchedulerSingleton.GET().executeTask(cmd::prompt); } @Override public Set<String> getCommandWords() { return commandWords; } @Override public boolean performCommand(String command, TwitchUser sender, String content, List<Emote> emotes) { lootingUsers.add(sender); return true; } private void prompt() { long payoutFormated = (long) payout; ChatSingleton.GET().broadcast("A quest is completed!" + " Hurry, join on the looting! " + "Type " + COMMAND + " to loot your share of" + " " + payoutFormated + " " + currency); SchedulerSingleton.GET().delayedTask((LOOT_TIME_MINUTES - 1) * 60 * 1000, this::latePrompt); SchedulerSingleton.GET().delayedTask((LOOT_TIME_MINUTES) * 60 * 1000, this::payout); } private void payout() { ChatSingleton.GET().removeChatCommand(this); StringBuilder b = new StringBuilder(); for (TwitchUser u : lootingUsers) { if (b.length() > 0) { b.append(", "); } b.append(u.getDisplayName()); } long payoutFormated = (long) payout; ChatSingleton.GET().broadcast("Good looting everyone! Payed out " + payoutFormated + " " + currency + " to the" + " following viewers:"); ChatSingleton.GET().broadcast(b.toString()); // Do payout } private void latePrompt() { long payoutFormatted = (long) payout; ChatSingleton.GET().broadcast("Only one minute of looting left! Hurry, or you'll" + " miss the " + payoutFormatted + " " + currency + "! Type LootTheRoom to get your share!"); } }
package classes; import java.awt.Color; import java.awt.Component; import java.io.Serializable; import java.util.Random; /** * Represents a single dot - food - on a field. */ public class Dot extends Component implements Serializable{ private int x; private int y; private Color c; private int size; public Dot(int x, int y){ this.x = x; this.y = y; Random rand = new Random(); int red = rand.nextInt(255); int green = rand.nextInt(255); int blue = rand.nextInt(255); this.c = new Color(red,green,blue); this.size = 10; } /** * Getter for dot's X-coordinate * @return dot's X-coordinate */ public int getX() { return x; } /** * Getter for dot's Y-coordinate * @return dot's Y-coordinate */ public int getY() { return y; } /** * Overridden toString method. * @return concatenated string containing dot's X- and Y-coordinates, in this order, seperated with spacebar. */ @Override public String toString() { // TODO Auto-generated method stub return getX() + ","+getY(); } }
package co.nos.noswallet.ui.settings.setRepresentative; import android.support.annotation.VisibleForTesting; import javax.inject.Inject; import co.nos.noswallet.R; import co.nos.noswallet.db.RepresentativesProvider; import co.nos.noswallet.persistance.currency.CryptoCurrency; public class SetRepresentativePresenter { private SetRepresentativeView view; private final RepresentativesProvider representativesProvider; @VisibleForTesting protected String previousRepresentative; @Inject public SetRepresentativePresenter(RepresentativesProvider representativesProvider) { this.representativesProvider = representativesProvider; } public void attachView(SetRepresentativeView view) { this.view = view; } public void requestCachedRepresentative(CryptoCurrency currency) { previousRepresentative = representativesProvider.provideRepresentative(currency); view.onRepresentativeReceived(previousRepresentative); } public void saveRepresentativeClicked(CryptoCurrency currency, String representative) { view.clearRepresentativeError(); boolean newRepresentativeInvalid = representativeEmpty(representative) || representativeWithWrongCurrency(representative, currency) || representativeHasWrongLength(representative); if (newRepresentativeInvalid) { view.showRepresentativeError(R.string.invalid_representative); } else { representativesProvider.setOwnRepresentative(currency, representative); view.showRepresentativeSavedAndExit(R.string.representative_saved); } } private boolean representativeHasWrongLength(String representative) { if (representative == null || previousRepresentative == null) { return false; } return previousRepresentative.length() != representative.length(); } private boolean representativeWithWrongCurrency(String representative, CryptoCurrency currency) { return !representative.startsWith(currency.getPrefix()); } private boolean representativeEmpty(String representative) { return representative == null || representative.isEmpty(); } }
package core; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URLEncoder; import java.util.ArrayList; import com.sun.org.apache.xpath.internal.SourceTree; import org.json.JSONException; import org.json.JSONObject; public class QuizListCreator { public static ArrayList<String> artistsListRussian = new ArrayList<String>(); static { try { artistsListRussian.add(URLEncoder.encode("Ария", "UTF-8")); artistsListRussian.add(URLEncoder.encode("Ария", "UTF-8")); artistsListRussian.add(URLEncoder.encode("Ария", "UTF-8")); artistsListRussian.add(URLEncoder.encode("Ария", "UTF-8")); artistsListRussian.add(URLEncoder.encode("Ария", "UTF-8")); artistsListRussian.add(URLEncoder.encode("Ария", "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } public static ArrayList<String> artistsListEnglish = new ArrayList<String>(); static { try { artistsListEnglish.add(URLEncoder.encode("Adele", "UTF-8")); artistsListEnglish.add(URLEncoder.encode("Adele", "UTF-8")); artistsListEnglish.add(URLEncoder.encode("Adele", "UTF-8")); artistsListEnglish.add(URLEncoder.encode("Adele", "UTF-8")); artistsListEnglish.add(URLEncoder.encode("Adele", "UTF-8")); artistsListEnglish.add(URLEncoder.encode("Adele", "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } public String artistRandomChooser(String language) { if(language.equals("english")){ String artist = artistsListEnglish.get((int) (Math.random() * 5)); String URL = "https://itunes.apple.com/ru/search?term=" + artist + "&limit=10"; return URL; }else{ String artist = artistsListRussian.get((int) (Math.random() * 5)); String URL = "https://itunes.apple.com/ru/search?term=" + artist + "&limit=10"; return URL; } } public ArrayList songRandomChooser(JSONObject jo) throws JSONException { int randomNum = (int) (Math.random() * 9); String song = jo.getJSONArray("results").getJSONObject(randomNum).getString("trackName"); String imageURL = jo.getJSONArray("results").getJSONObject(randomNum).getString("artworkUrl100"); ArrayList songParams = new ArrayList(); songParams.add(song); songParams.add(imageURL); return songParams; } public JavaRoundBean RoundCreator(String URL) throws MalformedURLException, IOException, JSONException { JSONReader jr = new JSONReader(); JSONObject JSONsongs = jr.readJsonFromURL(URL); String artist = JSONsongs.getJSONArray("results").getJSONObject(0).getString("artistName"); String firstSong = (String) songRandomChooser(JSONsongs).get(0); String secondSong; String thirdSong; String imageURL; do{ secondSong = (String) songRandomChooser(JSONsongs).get(0); }while(secondSong.equals(firstSong)); do{ ArrayList songParams = songRandomChooser(JSONsongs); thirdSong = (String) songParams.get(0); imageURL = (String) songParams.get(1); }while(thirdSong.equals(firstSong) || (thirdSong.equals(secondSong))); JavaRoundBean round = new JavaRoundBean(); round.setArtistName(artist); round.setFirstSong(firstSong); round.setSecondSong(secondSong); round.setThirdSong(thirdSong); round.setImageURL(imageURL); return round; } }
package ru.job4j.servlets.webarchitecturejsp.logic; import ru.job4j.servlets.webarchitecturejsp.model.User; import java.util.List; public interface Store { public boolean addUser(User user); public boolean updateUser(int id, User user); public boolean deleteUser(int id); public List<User> findAll(); public User findById(int id); public User findByLogin(String login); /** * Метод используется для авторизации. После введения логина-пароля, происходит проверка их * идентичности с уже ствующими в базе логином и паролем. Если совпало, то return true * @param login * @param password * @return */ public boolean isCredentional(String login, String password); }
package p3.control; import p3.factory.PlantFactory; import p3.logic.game.Game; public class ListCommand extends NoParamsCommand{ public static final String symbol = "l"; public static final String name = "list"; public static final String help = "Lists the avaliable plants."; public ListCommand() { super(ListCommand.symbol, ListCommand.name, ListCommand.help); } public void execute(Game game) { System.out.println(PlantFactory.listAvaliablePlants()); game.list(); } }
package com.tencent.mm.wallet_core.c; public interface g$a { void bQG(); }
package com.days.moment.member.controller; import com.days.moment.common.dto.PageMaker; import com.days.moment.common.dto.PageRequestDTO; import com.days.moment.common.dto.PageResponseDTO; import com.days.moment.member.domain.Member; import com.days.moment.member.dto.JoinDTO; import com.days.moment.member.dto.MemberDTO; import com.days.moment.member.service.CustomUserDetailsService; import lombok.RequiredArgsConstructor; import lombok.extern.log4j.Log4j2; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.mvc.support.RedirectAttributes; @Controller @RequestMapping("/member/*") @Log4j2 @RequiredArgsConstructor public class MemberController { private final CustomUserDetailsService customUserDetailsService; @PreAuthorize("permitAll()") @GetMapping("/join") public void joinGet(){ } @PreAuthorize("permitAll()") @PostMapping("/doblock") public String blockingPost(String memId){ log.info("---blockingPost controller---"); log.info(memId); customUserDetailsService.blockUser(memId); log.info("-----blockingPost c after blockUser "); log.info(memId); return "redirect:/member/list"; } @PreAuthorize("permitAll()") @PostMapping("/dounblock") public String unBlockingPost(String memId){ log.info("---unblockingPost controller---"); log.info(memId); customUserDetailsService.unBlockUser(memId); log.info("-----unblockingPost c after blockUser "); log.info(memId); return "redirect:/member/list"; } @PreAuthorize("hasRole('ROLE_ADMIN')") @GetMapping("/list") public void getList(PageRequestDTO pageRequestDTO, Model model){ log.info("c getList...." + pageRequestDTO); log.info("=============="); log.info(customUserDetailsService); log.info(customUserDetailsService.getClass().getName()); PageResponseDTO<JoinDTO> responseDTO = customUserDetailsService.getDTOList(pageRequestDTO); model.addAttribute("dtoList", responseDTO.getDtoList()); int total = responseDTO.getCount(); int page = pageRequestDTO.getPage(); int size = pageRequestDTO.getSize(); model.addAttribute("pageMaker", new PageMaker(page,size,total)); } @PreAuthorize("permitAll()") @PostMapping("/join") public String joinPost(JoinDTO joinDTO, RedirectAttributes redirectAttributes){ log.info("---joinPost---"); log.info("---joinPost---"); log.info("---joinPost---"); log.info(joinDTO); //String memId, String memPwd, String memNick, String memName, String memSex, // log.info(memId); // log.info(memPwd); // log.info(memNick); // log.info(memName); // log.info(memSex); // // MemberDTO memberDTO = MemberDTO.builder() // .memId(memId) // .memPwd(memPwd) // .memName(memName) // .enabled(enabled) // .memNick(memNick) // .memBirthday(memBirthday) // .memAnniversary(memAnniversary) // .memEmailCert(memEmailCert) // .memSex(memSex) // .lastLogin(lastLogin) // .memRegister(memRegister) // .memDormant(memDormant) // .memDenied(memDenied) // .build(); // //// // customUserDetailsService.register(joinDTO); redirectAttributes.addFlashAttribute("result", joinDTO.getMemId()); return "redirect:/member/joinsuccess"; } @PreAuthorize("permitAll()") @GetMapping("/joinsuccess") public void joinSuccessGet(){ } }
package com.southwind.aop; import org.springframework.stereotype.Component; @Component public class CalImpl implements Cal { public int add(int num1, int num2) { int result= num1+num2; return result; } public int sub(int num1, int num2) { int result=num1-num2; return result; } public int mul(int num1, int num2) { int result=num1*num2; return result; } public int div(int num1, int num2) { int result=num1/num2; return result; } }
/** * */ package taller; /** * @author agonzalez * */ public enum TReparacion { NORMAL, PRIORITARIA }
package binaryHeap; public class Heap { public int array[]; public int count; public int capacity; public int heap_type; public Heap(int capacity, int heap_type) { this.heap_type = heap_type; this.count = 0; this.capacity = capacity; this.array = new int[capacity]; } public int parent(int i) { if(i <= 0 || i >= this.count) { return -1; } return (i - i) / 2; } public int leftChild(int i) { int left = (2 * i) + 1; if(left >= this.count) { return -1; } return left; } public int rightChild(int i) { int right = (2 * i) + 2; if(right >= this.count) { return -1; } return right; } public int getMaximum() { if(this.count == 0) { return -1; } return this.array[0]; } public void percolateDown(int i) { int left = leftChild(i); int right = rightChild(i); int max; if(left != -1 && this.array[left] > this.array[i]) { max = left; } else { max = i; } if(right != -1 && this.array[right] > this.array[max]) { max = right; } if(max != i) { int temp = this.array[i]; this.array[i] = this.array[max]; this.array[max] = temp; percolateDown(max); } } public int deleteMax() { if(this.count == 0) { return -1; } int data = this.array[0]; this.array[0] = this.array[this.count - 1]; this.count--; percolateDown(0); return data; } public void insert(int data) { if(this.count == this.capacity) { resizeHeap(); } this.count++; int i = this.count - 1; while(i >= 0 && data > this.array[(i - 1) / 2]) { this.array[i] = this.array[(i - 1) / 2]; i = i - 1 / 2; } this.array[i] = data; } public void resizeHeap() { int array_old[] = new int[this.capacity]; System.arraycopy(this.array, 0, array_old, 0, this.count - 1); this.array = new int[this.capacity * 2]; if(this.array == null) { System.out.println("Memeory Error"); return; } for(int i = 0; i< this.capacity; i++) { this.array[i] = array_old[i]; } this.capacity *= 2; array_old = null; } public void destoryHeap() { this.count = 0; this.array = null; } public void buildHeap(Heap h, int a[], int n) { if(h == null) { return; } while(n > this.capacity) { h.resizeHeap(); } for(int i = 0; i<n; i++) { h.array[i] = a[i]; } this.count = n; for(int i = (n - 1) / 2; i >= 0; i--) { h.percolateDown(i); } } public void print() { for (int i = 0; i < this.count / 2; i++) { System.out.print(" PARENT : " + this.array[i] + " LEFT CHILD : " + this.array[2 * i + 1] + " RIGHT CHILD :" + this.array[2 * i + 2]); System.out.println(); } } public static void main(String[] args) { Heap h = new Heap(12, 0); h.insert(12); h.insert(14); h.insert(22); h.insert(17); h.insert(95); h.insert(45); System.out.println("worked"); } }
package com.tkb.elearning.action.admin; import java.io.IOException; import java.util.List; import com.tkb.elearning.model.CramMember; import com.tkb.elearning.service.CramMemberService; import com.tkb.elearning.util.VerifyBaseAction; public class CramMemberAction extends VerifyBaseAction{ private static final long serialVersionUID = 1L; private CramMemberService cramMemberService; //最新消息服務 private List<CramMember> cramMemberList; //最新消息清單 private CramMember cramMember; //最新消息資料 private int pageNo; //頁碼 private int[] deleteList; //刪除的會員清單 /** * 清單頁面 * @return */ public String index() { if(cramMember == null) { cramMember = new CramMember(); } pageTotalCount = cramMemberService.getCount(cramMember); pageNo = super.pageSetting(pageNo); cramMemberList = cramMemberService.getList(pageCount, pageStart, cramMember); return "list"; } /** * 新增頁面 * @return * **/ public String add(){ cramMember = new CramMember(); return "form"; } /** * 新增資料 * @return * @throws IOExcetpion * **/ public String addSubmit() throws IOException{ cramMemberService.add(cramMember); return "index"; } /** * 修改頁面 * @return */ public String update(){ cramMember = cramMemberService.getData(cramMember); return "form"; } /** * 修改會員資料 * @return * @throws IOException */ public String updateSubmit() throws IOException{ cramMemberService.update(cramMember); return "index"; } /** * 刪除會員資料 * @return **/ public String delete() throws IOException { for(int id : deleteList) { cramMember.setId(id); cramMember = cramMemberService.getData(cramMember); cramMemberService.delete(id); } return "index"; } /** * 瀏覽頁面 * @return */ public String view(){ cramMember = cramMemberService.getData(cramMember); return "view"; } public CramMemberService getCramMemberService() { return cramMemberService; } public void setCramMemberService(CramMemberService cramMemberService) { this.cramMemberService = cramMemberService; } public int[] getDeleteList() { return deleteList; } public void setDeleteList(int[] deleteList) { this.deleteList = deleteList; } public List<CramMember> getCramMemberList() { return cramMemberList; } public void setCramMemberList(List<CramMember> cramMemberList) { this.cramMemberList = cramMemberList; } public CramMember getCramMember() { return cramMember; } public void setCramMember(CramMember cramMember) { this.cramMember = cramMember; } public int getPageNo() { return pageNo; } public void setPageNo(int pageNo) { this.pageNo = pageNo; } }
#30DaysOfCode on HACKERRANK #task Given a base-10 integer,n , convert it to binary (base-2). Then find and print the base-10 integer denoting the maximum number of consecutive 1's in n's binary representation. When working with different bases, it is common to show the base as a subscript. Example n=125 The binary representation of (125) to base 10 is (1111101) to the base 2 . In base 10, there are 5 and 1 consecutive ones in two groups. Print the maximum,5 . #Input Format A single integer, n . #Output Format Print a single base-10 integer that denotes the maximum number of consecutive 1's in the binary representation of n. Sample Input 1 5 Sample Output 1 1 Sample Input 2 13 Sample Output 2 2 #Solution public static void main(String[] args) { int n = scanner.nextInt(); int count=0; int min=0; scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); while(n > 0){ if(n%2==1) { count ++; if(count>=min) min= count; } else count=0; n=n/2; } System.out.println(min); scanner.close(); }