text
stringlengths
10
2.72M
package com.getkhaki.api.bff.persistence.models; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; import javax.persistence.Entity; @Entity @Getter @Setter @Accessors(chain = true) public class SalaryGroupDao extends EntityBaseDao { Double salary; String role; }
package org.kuali.ole.describe.bo; import org.apache.commons.lang.StringEscapeUtils; import org.kuali.ole.OLEConstants; import org.kuali.ole.docstore.model.bo.*; import org.kuali.ole.docstore.model.enums.DocType; import java.util.Map; /** * Created with IntelliJ IDEA. * User: Sreekanth * Date: 12/20/12 * Time: 10:57 AM * To change this template use File | Settings | File Templates. */ public class DocumentTreeNode { private String title; private String uuid; private boolean select; private boolean returnCheck; private OleDocument oleDocument; private String selectedInstance; private Map<String, String> selectionMap; private String holdingLocation; public DocumentTreeNode() { } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public void setWorkBibDocument(WorkBibDocument workBibDocument) { this.oleDocument = workBibDocument; StringBuilder titleBuilder = new StringBuilder(); if (workBibDocument != null) { if (workBibDocument.getTitle() != null) { titleBuilder.append(workBibDocument.getTitle()); } if (titleBuilder.length() > 0) { titleBuilder.append(" / "); } if (workBibDocument.getAuthor() != null) { titleBuilder.append(workBibDocument.getAuthor()); } setTitle(StringEscapeUtils.escapeHtml(titleBuilder.toString())); } else { setTitle("Bibliographic Title"); } setUuid(workBibDocument.getId()); } public void setWorkInstanceDocument(WorkInstanceDocument workInstanceDocument) { this.oleDocument = workInstanceDocument; if (workInstanceDocument.getHoldingsDocument() != null) { setTitle(buildTreeDataForHoldings(workInstanceDocument)); } else { setTitle("Holdings"); } setUuid(workInstanceDocument.getInstanceIdentifier()); } public void setWorkItemDocument(WorkItemDocument workItemDocument) { this.oleDocument = workItemDocument; if (workItemDocument != null) { setTitle(buildTreeDataForItem(workItemDocument)); } else { setTitle("Item"); } setUuid(workItemDocument.getItemIdentifier()); } public void setWorkHoldingsDocument(WorkItemDocument workItemDocument, WorkHoldingsDocument workHoldingsDocument) { this.oleDocument = workItemDocument; if (workItemDocument != null) { setTitle(buildTreeDataForItem(workItemDocument, workHoldingsDocument)); } else { setTitle("Item"); } setUuid(workItemDocument.getItemIdentifier()); } public void setWorkEInstanceDocument(WorkEInstanceDocument workEInstanceDocument) { this.oleDocument = workEInstanceDocument; String eHoldingsTitle = OLEConstants.E_HOLDINGS_DOC_TYPE; StringBuffer stringBuffer = new StringBuffer(); if (workEInstanceDocument != null && workEInstanceDocument.getWorkEHoldingsDocument() != null) { if (workEInstanceDocument.getWorkEHoldingsDocument() != null) { if (workEInstanceDocument.getWorkEHoldingsDocument().getLocation() != null && workEInstanceDocument.getWorkEHoldingsDocument().getLocation().length() > 0) { stringBuffer.append(workEInstanceDocument.getWorkEHoldingsDocument().getLocation()); } if (stringBuffer.length() > 0 && workEInstanceDocument.getWorkEHoldingsDocument().geteResourceName() != null && workEInstanceDocument.getWorkEHoldingsDocument().geteResourceName().length() > 0) { stringBuffer.append("-"); } if (workEInstanceDocument.getWorkEHoldingsDocument().geteResourceName() != null) { stringBuffer.append(workEInstanceDocument.getWorkEHoldingsDocument().geteResourceName()); } } if (stringBuffer.length() > 0) { setTitle(stringBuffer.toString()); } else { setTitle(eHoldingsTitle); } } setUuid(workEInstanceDocument.getInstanceIdentifier() + " " + DocType.EINSTANCE.getCode()); } public OleDocument getWorkBibDocument() { getTitle(); getUuid(); return oleDocument = new WorkBibDocument(); } public OleDocument getWorkInstanceDocument() { /* getTitle(); getUuid();*/ return oleDocument = new WorkInstanceDocument(); } public OleDocument getWorkItemDocument() { getTitle(); getUuid(); return oleDocument = new WorkItemDocument(); } public OleDocument getWorkEInstanceDocument() { getTitle(); getUuid(); return oleDocument = new WorkEInstanceDocument(); } public String getSelectedInstance() { return selectedInstance; } public void setSelectedInstance(String selectedInstance) { this.selectedInstance = selectedInstance; } public boolean isSelect() { return select; } public void setSelect(boolean select) { this.select = select; } public Map<String, String> getSelectionMap() { return selectionMap; } public void setSelectionMap(Map<String, String> selectionMap) { this.selectionMap = selectionMap; } public boolean isReturnCheck() { return returnCheck; } public void setReturnCheck(boolean returnCheck) { this.returnCheck = returnCheck; } public String buildTreeDataForHoldings(WorkInstanceDocument workInstanceDocument) { StringBuffer holdingsLabelBufferForStaffOnly = new StringBuffer(); WorkHoldingsDocument workHoldingsDocument = workInstanceDocument.getHoldingsDocument(); return new EditorFormDataHandler().getHoldingsLabel(workHoldingsDocument); } public String buildTreeDataForItem(WorkItemDocument workItemDocument, WorkHoldingsDocument workHoldingsDocument) { return new EditorFormDataHandler().getItemLabel(workHoldingsDocument, workItemDocument); } public String buildTreeDataForItem(WorkItemDocument workItemDocument) { String itemLevelContent = null; StringBuilder treeBuilder = new StringBuilder(); String locationName = this.getHoldingLocation(); // if (workItemDocument.getLocation() != null) { // treeBuilder.append(workItemDocument.getLocation()); // } StringBuffer removeFromCallNumber = new StringBuffer(); String callNumberPrefix = null; String itemLocation = null; if (workItemDocument.getLocation() != null) { itemLocation = workItemDocument.getLocation(); if (!(itemLocation).equalsIgnoreCase(locationName)) { treeBuilder.append(itemLocation); } } if (workItemDocument.getCallNumberPrefix() != null && workItemDocument.getCallNumberPrefix().length() > 0) { callNumberPrefix = workItemDocument.getCallNumberPrefix(); } if (callNumberPrefix != null) { if (treeBuilder.length() > 0) { treeBuilder.append("-").append(callNumberPrefix); } else { treeBuilder.append(callNumberPrefix); } } if (workItemDocument.getCallNumber() != null && workItemDocument.getCallNumber().length() > 0) { if (treeBuilder.length() > 0) { treeBuilder.append("-"); } treeBuilder.append(workItemDocument.getCallNumber()); } if (workItemDocument.getEnumeration() != null && workItemDocument.getEnumeration().length() > 0) { if (treeBuilder.length() > 0) { treeBuilder.append("-"); } treeBuilder.append(workItemDocument.getEnumeration()); removeFromCallNumber.append(" " + workItemDocument.getEnumeration()); } if (workItemDocument.getChronology() != null && workItemDocument.getChronology().length() > 0) { if (treeBuilder.length() > 0) { treeBuilder.append("-"); } treeBuilder.append(workItemDocument.getChronology()); removeFromCallNumber.append(" " + workItemDocument.getChronology()); } if (workItemDocument.getCopyNumber() != null && workItemDocument.getCopyNumber().length() > 0) { if (treeBuilder.length() > 0) { treeBuilder.append("-"); } treeBuilder.append(workItemDocument.getCopyNumber()); removeFromCallNumber.append(" " + workItemDocument.getCopyNumber()); } if (workItemDocument.getBarcode() != null && workItemDocument.getBarcode().length() > 0) { if (treeBuilder.length() > 0) { treeBuilder.append("-"); } treeBuilder.append(workItemDocument.getBarcode()); } if (treeBuilder.length() == 0) { if (workItemDocument.getVolumeNumber() != null) { treeBuilder.append(workItemDocument.getVolumeNumber()); } else { treeBuilder.append("Item"); } } itemLevelContent = treeBuilder.toString().replaceAll(removeFromCallNumber.toString(), ""); return itemLevelContent; } public String getHoldingLocation() { return holdingLocation; } public void setHoldingLocation(String holdingLocation) { this.holdingLocation = holdingLocation; } }
package com.pky.smartselling.controller.api.dto; import io.swagger.annotations.ApiModel; import lombok.AllArgsConstructor; import lombok.Data; public class SignInDto { @ApiModel("SignInDto") @Data public static class Request { String email; String password; } @ApiModel("SignInDto") @AllArgsConstructor @Data public static class Response { String token; } }
package net.lantrack.framework.core.importexport.excel.reader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import com.alibaba.excel.EasyExcelFactory; import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.event.AnalysisEventListener; import com.alibaba.excel.metadata.Sheet; /** * Excel数据解析处理 * * @date 2019年5月11日 */ public class ExcelObserverHandler extends AnalysisEventListener<Object>{ /** * 初始化观察者数量 */ private volatile List<ExcelObServer > observers = new ArrayList<>(1); private static volatile ExcelObserverHandler handler = null; /** * Excel数据转换的对象类型 */ private Class<?> clazz; // private Class<? extends Excel> clazz; private ExcelObserverHandler() {} public static ExcelObserverHandler getInstance(){ if(handler==null) { synchronized(ExcelObserverHandler.class) { if(handler==null) { handler = new ExcelObserverHandler(); } } } return handler; } /** * 注册 * @param os * @return * @date 2019年5月11日 */ protected ExcelObserverHandler registObserver(ExcelObServer os) { if(os==null) { throw new NullPointerException("ExcelObServer Can't be null"); } synchronized(observers) { if(!observers.contains(os)) { observers.add(os); } } return this; } /** * 注销 * @param os * @return * @date 2019年5月11日 */ protected ExcelObserverHandler removeObserver(ExcelObServer os) { if(os==null) { throw new NullPointerException("ExcelObServer Can't be null"); } synchronized(observers) { if(observers.contains(os)) { observers.remove(os); } } return this; } private void notifyAllObserver(ExcelInfo obj) { for(ExcelObServer os:observers) { os.excute(obj); } } protected int countObserver() { synchronized(observers) { return observers.size(); } } protected ExcelObserverHandler clearObserver() { synchronized(observers) { observers.clear(); } return this; } public List<ExcelObServer> getObservers() { return observers; } @SuppressWarnings({"deprecation","unchecked"}) @Override public void invoke(Object object, AnalysisContext context) { if(clazz==null) { throw new NullPointerException("excel convert clazz can't be null"); } Integer currentRowNum = context.getCurrentRowNum(); Integer totalCount = context.getTotalCount(); ExcelInfo info = new ExcelInfo(clazz,currentRowNum,totalCount,(List<Object>) object); notifyAllObserver(info); } @Override public void doAfterAllAnalysed(AnalysisContext context) { System.out.println(context.getTotalCount()); } protected void handlerExcelByTemplate(File excel,Class<?> clazz,int heardrIndex,int dataIndex) throws FileNotFoundException { if(clazz==null) { throw new NullPointerException("excel convert clazz can't be null"); } this.clazz = clazz; InputStream inputStream = new FileInputStream(excel); EasyExcelFactory.readBySax(inputStream, new Sheet(1,0), this); } protected void handlerExcelByIndex(File excel,Class<?> clazz,int dataIndex) throws FileNotFoundException { if(clazz==null) { throw new NullPointerException("excel convert clazz can't be null"); } this.clazz = clazz; InputStream inputStream = new FileInputStream(excel); EasyExcelFactory.readBySax(inputStream, new Sheet(1,0), this); } /** * 解析数据 * @param rowData * @date 2019年5月13日 */ private void paserData(List<Object> rowData) { } }
package sorting; public class SortingDriver { /** * generates random numbers * @param size how many numbers to generate * @return the array containing the randomly generated numbers */ public static double[] generateRandomArray(int size){ double[] array = new double[size]; for(int i =0; i<array.length; i++){ array[i] = Math.random() * 100.0; } return array; } public static void main(String[] args) { double[]array1 = generateRandomArray(100000); double[]array2 = array1.clone(); //algorithm #1 Sorter insertion = new InsertionSort(); insertion.sort(array1); System.out.println("Insertion sort Operation: " + insertion.getOpCount()); //algorithm #2 Sorter merge = new MergeSort(); merge.sort(array2); System.out.println("Merge sort Operation: " + merge.getOpCount()); } }
package com.novakivska.app.classwork.lesson15; /** * Created by Tas_ka on 5/5/2017. */ public abstract class AbstractHouse { private String name; private int floorsNumbers; public AbstractHouse(String name){ this.name = name; } public AbstractHouse(int floorsNumber){ this.floorsNumbers = floorsNumber; } public abstract void build(); public void showHouseNumber(String number){ System.out.println("Number: " + number); } public void showHouseFloorsNumber(int floorsNumbers){ System.out.println(floorsNumbers + " floors"); } }
package com.datalinks.rsstool.controller; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; 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.servlet.ModelAndView; import com.datalinks.rsstool.model.xml.Item; import com.datalinks.rsstool.model.RssFile; import com.datalinks.rsstool.model.RssFileModel; import com.datalinks.rsstool.model.xml.Channel; import com.datalinks.rsstool.model.xml.Image; import com.datalinks.rsstool.model.xml.Rss; import com.datalinks.rsstool.util.RssUtil; @Controller @RequestMapping("/") public class RssController implements RssTool_Variables{ public final static Logger LOGGER = Logger.getLogger(RssController.class.getName()); /* * LOGIN page */ @RequestMapping(value = "login") public ModelAndView goLoginPage() { return new ModelAndView("login"); } /* * DELETE RSS FIlE */ @RequestMapping(value = "deleterssfileConfirm", method = RequestMethod.POST) public String deleteRssFileConfirm( @ModelAttribute("deleteModel") RssFileModel deleteModel) { if (deleteModel.isDoDelete()) { File file = new File(RssUtil.getProp(INSTALL_DIRECTORY) + deleteModel.getFileName()); file.delete(); } return "redirect:/rssfile"; } /* * EDIT RSS FIlE; CANCEL action * */ @RequestMapping(params = "cancel", value = "editFile", method = RequestMethod.POST) public String editRssFileCancel(@ModelAttribute("editModel") RssFileModel editModel) { return "redirect:/rssfile"; } /* * EDIT RSS FIlE; * Actually we delete and recreate the file */ @RequestMapping(params = "save", value = "editFile", method = RequestMethod.POST ) public String editRssFile(@ModelAttribute("editModel") RssFileModel editModel ) { LOGGER.info("editing file now...."); try { createRssFile(editModel, false, getLoggedInUser()); } catch (JAXBException e) { LOGGER.severe("Exception creating the jaxb file in editRssFile, exception: "+e.getMessage()); } return "redirect:/rssfile"; } /* * EDIT RSS FIlE; adding Item * Actually we delete and recreate the file */ @RequestMapping(params = "add_item", value = "editFile", method = RequestMethod.POST) public ModelAndView editRssFileAddItem(@ModelAttribute("editModel") RssFileModel editModel) { LOGGER.info("editing file now...."); ModelMap model = null; try { model = createSelectedRssModel(editModel.getFileName()); createRssFile(editModel, true, getLoggedInUser()); } catch (JAXBException e) { LOGGER.severe("Exception creating the jaxb file in editRssFileAddItem, exception: "+e.getMessage()); } return new ModelAndView("editrssfile", model); } /* * SHOW RSS File */ @RequestMapping(value = "rssfile") public ModelAndView selectedRssFile(HttpServletRequest request) { String fileName = request.getParameter("rssFilez"); // TRUE = Delete or FALSE = Edit if (Boolean.valueOf(request.getParameter("doDelete"))) { ModelMap model = new ModelMap(); model.addAttribute("selectedFileName", fileName); model.addAttribute("deleteModel", new RssFileModel()); return new ModelAndView("deleterssfile", model); } else { try { ModelMap model = createSelectedRssModel(fileName); return new ModelAndView("editrssfile", model); } catch (JAXBException e) { LOGGER.severe("Exception creating the jaxb file in selectedRssFile, exception: "+e.getMessage()); } } // This should not happen return null; } private ModelMap createSelectedRssModel(String fileName) throws JAXBException{ ModelMap model = new ModelMap(); Rss rssFile = getRssFile(fileName,getLoggedInUser()); model.addAttribute("selectedItems", rssFile.getChannel().getItem()); RssFileModel rsMod = new RssFileModel(); rsMod.setRssItems(rssFile.getChannel().getItem()); rsMod.setChannel(rssFile.getChannel()); rsMod.setFileName(fileName); model.addAttribute("editModel", rsMod); return model; } /* * SHOW RSS File */ @RequestMapping(value = "rssfile", method = RequestMethod.GET) public ModelAndView showForm( @ModelAttribute("rssFileModel") RssFileModel rssFileModel) { ModelAndView modelAndView = new ModelAndView("rssfile"); modelAndView.addObject("rssFilez", getRssFilez(getLoggedInUser())); return modelAndView; } /* * CREATE RSS File */ @RequestMapping(value = "/createRssFile", method = RequestMethod.GET) public ModelAndView createRssFile() { return new ModelAndView("createrssfile", "command", new RssFile()); } /* * CREATE RSS File */ @RequestMapping(value = "/createRssFile", method = RequestMethod.POST) public String rssfile(@ModelAttribute("rssfile") RssFile rssFile, ModelMap model, HttpServletRequest request) { try { createDummyRssFile(rssFile.getFileName(),getLoggedInUser(),request); } catch (JAXBException e) { LOGGER.severe("Exception creating the jaxb file in createRssFile, exception: "+e.getMessage()); } return "redirect:/rssfile"; } /* * * Private methods go here * */ /* * * Get Logged in User * */ private String getLoggedInUser(){ Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String name = auth.getName(); return name; } /* * GET aLL RSS Files * */ private List<RssFile> getRssFilez(String username) { List<RssFile> result = new ArrayList<RssFile>(); // Read complete directory with rss files (if any available) String fileName; File folder = new File(RssUtil.getProp(INSTALL_DIRECTORY)+username); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile() && listOfFiles[i].canRead()) { fileName = listOfFiles[i].getName(); if (fileName.endsWith(".xml")) { RssFile tmp = new RssFile(); tmp.setFileName(fileName); result.add(tmp); } } } return result; } /* * Get an existing RSS File * */ private Rss getRssFile(String fileName, String username) throws JAXBException { File file = new File(RssUtil.getProp(INSTALL_DIRECTORY) + username+File.separator+fileName); JAXBContext jaxbContext = JAXBContext.newInstance(Rss.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Rss rssXmlFile = (Rss) jaxbUnmarshaller.unmarshal(file); Channel channel = rssXmlFile.getChannel(); Image plaatje = channel.getImage(); if (plaatje != null) LOGGER.info("plaatje: " + plaatje.getTitle()); return rssXmlFile; } /* * Delete and create the New RSS File * */ private void createRssFile(RssFileModel editFileModel, boolean addItem, String username) throws JAXBException { String fileName = editFileModel.getFileName(); File file_del = new File(RssUtil.getProp(INSTALL_DIRECTORY) +username+File.separator+ fileName); // Only create the new File is delete of the OLD has succeeded if(file_del.delete()){ File file_new = new File(RssUtil.getProp(INSTALL_DIRECTORY) +username+File.separator+ fileName); JAXBContext jaxbContext_new = JAXBContext.newInstance(Rss.class); Marshaller jaxbMarshaller = jaxbContext_new.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); Rss rssX = new Rss(); rssX.setVersion(RSS_VERSION); Channel channelX = editFileModel.getChannel(); List<Item> itemXList = editFileModel.getRssItems(); if(addItem){ Item itemX = new Item(); itemX.setTitle("edit title here"); itemX.setLink("edit link here"); itemX.setDescription("edit description here"); itemXList.add(itemX); } channelX.setItem(itemXList); rssX.setChannel(channelX); jaxbMarshaller.marshal(rssX, file_new); } } /* * Creates the initial dummy file */ private void createDummyRssFile(String fileNaam, String username, HttpServletRequest request) throws JAXBException { // Filename should end with .xml if(!fileNaam.endsWith(".xml") ) fileNaam = fileNaam+".xml"; File file_new = new File(RssUtil.getProp(INSTALL_DIRECTORY) +username+File.separator+ fileNaam); JAXBContext jaxbContext_new = JAXBContext.newInstance(Rss.class); Marshaller jaxbMarshaller = jaxbContext_new.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); Rss rssX = new Rss(); rssX.setVersion(RSS_VERSION); Channel channelX = new Channel(); channelX.setTitle("edit title"); String link = request.getLocalName()+":"+request.getLocalPort()+"/rss/"+username+"/"+fileNaam; channelX.setLink(link); channelX.setDescription("edit description"); Item itemX = new Item(); itemX.setTitle("e.g. google"); itemX.setLink("e.g. http://www.google.com"); itemX.setDescription("e.g. great search engine"); List<Item> itemXList = new ArrayList<Item>(); itemXList.add(itemX); channelX.setItem(itemXList); rssX.setChannel(channelX); jaxbMarshaller.marshal(rssX, file_new); } }
package com.prakash.shopapi.io.utils; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import com.prakash.shopapi.io.model.Shop; /** * This class <code> Utility.java</code> provides the generic method to sort the * Map by value * * @author Prakash Gour */ public class Utility { public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) { List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<K, V>>() { public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) { return (o1.getValue()).compareTo(o2.getValue()); } }); Map<K, V> result = new LinkedHashMap<K, V>(); for (Map.Entry<K, V> entry : list) { result.put(entry.getKey(), entry.getValue()); } return result; } public static boolean isContainNullValue(Shop shop) { if(shop.getShopStreet()==null||shop.getShopCity()==null||shop.getShopCountry()==null||shop.getShopDistrict()==null||shop.getShopDistrict()==null||shop.getShopName()==null ||shop.getShopPincode()==null){ return true; } return false; } }
package com.union.express.web.stowagecore.agingcycle.model; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import java.util.Date; /** * Created by Administrator on 2016/11/15 0015. */ /* 时效折扣表 */ @Entity @Table(name = "discount") public class Discount { //id private String id; //时效类型ID private String agingCycleId; //折扣 private double discount; //折扣日期 private Date startTime; @Id @GeneratedValue(generator = "system-uuid") @GenericGenerator(name = "system-uuid", strategy = "uuid") @Column(name = "id", unique = true, nullable = false) public String getId() { return id; } public void setId(String id) { this.id = id; } @Column(name = "aging_cycle_id") public String getAgingCycleId() { return agingCycleId; } public void setAgingCycleId(String agingCycleId) { this.agingCycleId = agingCycleId; } @Column(name = "discount") public double getDiscount() { return discount; } public void setDiscount(double discount) { this.discount = discount; } @Column(name = "start_time") public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } }
package net.awesomekorean.podo.lesson.lessons; import net.awesomekorean.podo.R; import java.io.Serializable; public class Lesson13 extends LessonInit_Lock implements Lesson, LessonItem, Serializable { private String lessonId = "L_13"; private String lessonTitle = "before"; private String lessonSubTitle = "~전에"; private String[] wordFront = {"감기에 걸리다", "먹다", "약", "밥", "전"}; private String[] wordBack = {"catch a cold / get a cold", "eat", "medicine", "rice / meal", "before"}; private String[] wordPronunciation = {"-", "[먹따]", "-", "-", "-"}; private String[] sentenceFront = { "감기에 걸리다", "감기에 걸렸어요.", "먹다", "먹어요", "이 약을 먹어요.", "어떻게 먹어요?", "밥을 먹다", "밥을 먹기", "밥을 먹기 전에 먹어요.", "밥을 먹기 30분 전에 먹어요." }; private String[] sentenceBack = { "get a cold", "I've got a cold.", "eat", "eat.", "Take this medicine.", "How do I take it?", "have a meal", "having a meal", "Take this medicine before meals.", "Take this medicine 30 minutes before meals." }; private String[] sentenceExplain = { "'감기' and '걸리다' is commonly used, so better memorize it together.", "-", "-", "-", "-", "-", "-", "-", "You can also use 'N + 전에' instead of saying 'V + 기 전에'\nHowever, only specific nouns which can be used in 'N + 하다' form(related to the action) can be used as 'N + 전에' form. \n\nex)\n'식사' + '하다' = '식사하다' (o)\n'식사 하기 전에~'\n'식사 전에~'\n'쇼핑' + '하다' = '쇼핑하다' (o)\n쇼핑 하기 전에~'\n'쇼핑 전에 ~'", "-" }; private String[] dialog = { "감기에 걸렸어요.", "이 약을 먹어요.", "어떻게 먹어요?", "밥을 먹기 30분 전에 먹어요." }; private int[] peopleImage = {R.drawable.male_b,R.drawable.female_p}; private int[] reviewId = {1,9}; @Override public String getLessonSubTitle() { return lessonSubTitle; } @Override public String getLessonId() { return lessonId; } @Override public String[] getWordFront() { return wordFront; } @Override public String[] getWordPronunciation() { return wordPronunciation; } @Override public String[] getSentenceFront() { return sentenceFront; } @Override public String[] getDialog() { return dialog; } @Override public int[] getPeopleImage() { return peopleImage; } @Override public String[] getWordBack() { return wordBack; } @Override public String[] getSentenceBack() { return sentenceBack; } @Override public String[] getSentenceExplain() { return sentenceExplain; } @Override public int[] getReviewId() { return reviewId; } // 레슨어뎁터 아이템 @Override public String getLessonTitle() { return lessonTitle; } }
package com.firstexercises; import java.util.Scanner; public class First { private static final float PRICE_SUPER_E5 = 1.189F; private static final float PRICE_SUPER_E10 = 1.139F; private static final float PRICE_DIESEL = 0.989F; private static final float PERCENT_SALE = 0.95F; private static final byte LITER_BEFORE_SALE = 100; public static void main(String[] Args) { System.out.println("You have to pay: " + (float)getPrice() + "€"); } public static double getPrice() { Scanner scanner = new Scanner(System.in); double priceToPay = 0; int operationNumber = 0; double literAmount = 0; while (true) { try { System.out.print("Do you want to pay for Diezel(1), Super E5(2) or Super E10 (3): "); operationNumber = scanner.nextInt(); System.out.print("How much liter: "); literAmount = scanner.nextDouble(); break; } catch (Exception e) { System.out.println("Something went wrong"); scanner.next(); } } if (operationNumber == 1) { priceToPay = literAmount * PRICE_DIESEL; } else if (operationNumber == 2) { priceToPay = literAmount * PRICE_SUPER_E5; } else if (operationNumber == 3) { priceToPay = literAmount * PRICE_SUPER_E10; } else { System.out.println("This number of liquid doesn't exist!"); System.exit(0); } if (literAmount >= LITER_BEFORE_SALE) { priceToPay *= PERCENT_SALE; } return priceToPay; } }
package com.designurway.idlidosa.ui.home_page.fragments; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.navigation.NavDirections; import androidx.navigation.Navigation; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.designurway.idlidosa.R; import com.designurway.idlidosa.databinding.FragmentServiceNotAvailableBinding; public class ServiceNotAvailableFragment extends Fragment { FragmentServiceNotAvailableBinding binding; ServiceNotAvailableFragmentArgs args; String addrss; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment binding = FragmentServiceNotAvailableBinding.inflate(inflater,container,false); return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); args = ServiceNotAvailableFragmentArgs.fromBundle(getArguments()); binding.txtAdd.setText(args.getAddress()); binding.gotToHome.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { NavDirections navDirections = ServiceNotAvailableFragmentDirections.actionServiceNotAvailableFragmentToHomeFragment(); Navigation.findNavController(getView()).navigate(navDirections); } }); } }
package be.presis; import org.dom4j.Element; public class CoverageAuthorization { private IdList ids = new IdList(); private double authorizezdAmount; public String toXml() { StringBuffer sb = new StringBuffer(); sb.append("<authorization>"); sb.append(ids.toXml()); sb.append("<authorizedamount>"+authorizezdAmount+"</authorizedamount>"); sb.append("</authorization>"); return sb.toString(); } public void toXml(Element e) { Element eAuthorization = e.addElement("authorization"); ids.toXml(eAuthorization); eAuthorization.addElement("authorizedamount").setText(authorizezdAmount+""); } public static CoverageAuthorization fromXml(Element e) { CoverageAuthorization authorization = new CoverageAuthorization(); if(e!=null) { authorization.setIds(IdList.fromXml(e.element("ids"))); try { authorization.setAuthorizezdAmount(Double.parseDouble(e.elementText("authorizedamount"))); } catch(Exception e2) {} } return authorization; } public IdList getIds() { return ids; } public void setIds(IdList ids) { this.ids = ids; } public double getAuthorizezdAmount() { return authorizezdAmount; } public void setAuthorizezdAmount(double authorizezdAmount) { this.authorizezdAmount = authorizezdAmount; } }
package cdp.controllers; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.Serializable; import java.text.ParseException; import java.util.Iterator; import java.util.Set; import java.util.TreeSet; import cdp.exception.CadastroException; import cdp.exception.DataException; import cdp.exception.ValidacaoException; import cdp.factorys.FactoryDeProjeto; import cdp.participacao.Participacao; import cdp.projetos.CategoriaPED; import cdp.projetos.Extensao; import cdp.projetos.Monitoria; import cdp.projetos.PED; import cdp.projetos.PET; import cdp.projetos.Projeto; import cdp.utils.Validacao; /** * Classe responsavel por fazer a gerencia de projetos no sistema. * * @author Yuri Silva * @author Tiberio Gadelha * @author Matheus Henrique * @author Gustavo Victor */ public class ProjetoController implements Serializable{ private Set<Projeto> projetosCadastrados; private FactoryDeProjeto factoryProjeto; private int codigosProjeto; private String historicoColaboracaoUasc; private static final String FIM_DE_LINHA = System.lineSeparator(); private static final String NOME = "nome"; private static final String OBJETIVO = "objetivo"; private static final String DISCIPLINA = "disciplina"; private static final String RENDIMENTO = "rendimento"; private static final String PERIODO = "periodo"; private static final String DATAINICIO = "data de inicio"; private static final String DURACAO = "duracao"; private static final String IMPACTO = "impacto"; private static final String PRODTECNICA = "producao tecnica"; private static final String PRODACADEMICA = "producao academica"; private static final String PATENTES = "patentes"; private static final String CATEGORIA = "categoria"; private static final String PARTICIPACOES = "participacoes"; public ProjetoController(){ this.projetosCadastrados = new TreeSet<>(); factoryProjeto = new FactoryDeProjeto(); this.historicoColaboracaoUasc = ""; } /** * O metodo vai primeiro validar os parametros para criar um projeto do tipo Monitoria, * depois, atraves da factoryProjeto, criar uma monitoria. * @param nome Nome da monitoria * @param disciplina A disciplina da monitoria * @param rendimento Taxa de rendimento esperada dos alunos * @param objetivo Objetivo da monitoria * @param periodo Periodo em que a monitoria se iniciou. * @param dataInicio Data de inicio da monitoria * @param duracao Tempo de duracao * @return Retorna o codigo do projeto como int. * @throws ValidacaoException Lanca uma excecao se ocorrer um erro na validacao das strings. * @throws ParseException Lanca uma excecao se ocorrer um erro na validacao da data. * @throws DataException Caso a data nao seja uma data valida no calendario. */ public int adicionaMonitoria(String nome, String disciplina, int rendimento, String objetivo, String periodo, String dataInicio, int duracao) throws ValidacaoException, ParseException, CadastroException, DataException{ Validacao.validaString(nome, "Nome nulo ou vazio"); Validacao.validaString(disciplina,"Disciplina nulo ou vazio"); Validacao.validaInt(rendimento,"Rendimento invalido"); Validacao.validaString(objetivo, "Objetivo nulo ou vazio"); Validacao.validaString(periodo,"Periodo nulo ou vazio"); Validacao.validaData(dataInicio); Validacao.validaIntSemZero(duracao,"Duracao Invalida"); this.codigosProjeto++; projetosCadastrados.add(factoryProjeto.criaMonitoria(nome, disciplina, rendimento, objetivo, periodo, dataInicio, duracao, codigosProjeto)); return codigosProjeto; } /** * O metodo vai validar os parametros para criar um projeto do tipo PET, * depois, atraves da factoryProjeto, vai crirar um Pet. * @param nome O nome do Pet * @param objetivo Objetivo do Pet * @param impacto O impacto que o projeto ira trazer a sociedade * @param rendimento Taxa de rendimento esperada dos alunos * @param prodTecnica O numero de producoes tecnicas produzidas * @param prodAcademica O numero de producoes academicas produzidas * @param patentes O numero de patentes do projeto * @param dataInicio A data que o projeto iniciou * @param duracao A duracao total do projeto * @return Retorna um inteiro que representa o codigo do projeto. * @throws ValidacaoException Lanca uma excecao se ocorrer um erro na validacao das strings. * @throws ParseException Lanca uma excecao se ocorrer um erro na validacao da data. * @throws DataException Caso a data nao seja uma data valida no calendario. */ public int adicionaPET(String nome, String objetivo, int impacto, int rendimento, int prodTecnica, int prodAcademica, int patentes, String dataInicio, int duracao) throws ValidacaoException, ParseException, DataException{ Validacao.validaString(nome,"Nome nulo ou vazio" ); Validacao.validaString(objetivo,"Objetivo nulo ou vazio"); Validacao.validaInt(impacto, "Impacto invalido"); Validacao.validaInt(rendimento,"Rendimento invalido"); Validacao.validaInt(prodTecnica, "Numero de producoes tecnicas invalido"); Validacao.validaInt(prodAcademica, "Numero de producoes academicas invalido"); Validacao.validaInt(patentes, "Numero de patentes invalido"); Validacao.validaData(dataInicio); Validacao.validaIntSemZero(duracao,"Duracao invalida"); this.codigosProjeto++; projetosCadastrados.add(factoryProjeto.criaPET(nome, objetivo, impacto, rendimento, prodTecnica, prodAcademica, patentes, dataInicio, duracao, codigosProjeto)); return codigosProjeto; } /** * O metodo vai validar os parametros para a criacao de um projeto de tipo Extensao, * depois, atraves da factoryProjeto, criar uma Extensao. * @param nome O nome do projeto * @param objetivo O objetivo do projeto * @param impacto O impacto social que o projeto ira trazer. * @param dataInicio A data que o projeto iniciou * @param duracao A duracao total do projeto. * @return Retorna um inteiro que representa seu codigo. * @throws ValidacaoException Lanca uma excecao se ocorrer um erro na validacao das strings. * @throws ParseException Lanca uma excecao se ocorrer um erro na validacao da data. * @throws DataException Caso a data nao seja uma data valida no calendario. */ public int adicionaExtensao(String nome, String objetivo, int impacto, String dataInicio, int duracao) throws ValidacaoException, ParseException, DataException{ Validacao.validaString(nome,"Nome nulo ou vazio" ); Validacao.validaString(objetivo,"Objetivo nulo ou vazio"); Validacao.validaInt(impacto, "Impacto invalido"); Validacao.validaData(dataInicio); Validacao.validaIntSemZero(duracao,"Duracao invalida"); Validacao.validaImpactoSocial(impacto, "Impacto invalido"); this.codigosProjeto++; projetosCadastrados.add(factoryProjeto.criaExtensao(nome, objetivo, impacto, dataInicio, duracao, codigosProjeto)); return codigosProjeto; } /** * O metodo vai validar os parametros para criar um projeto do tipo PED, * depois, atraves da factoryProjeto, ira criar um PED. * @param nome Nome do projeto * @param categoria A categoria do PED. * @param prodTecnica O numero de producoes tecnicas do projeto. * @param prodAcademica O numero de producoes academicas do projeto. * @param patentes O numero de patentes do projeto. * @param objetivo O objetivo do projeto * @param dataInicio Data de inicio do projeto * @param duracao A duracao total do projeto. * @return Retorna um inteiro que representa eu codigo. * @throws ValidacaoException Lanca uma excecao se ocorrer um erro na validacao das strings. * @throws ParseException Lanca uma excecao se ocorrer um erro na validacao da data. * @throws DataException Caso a data nao seja uma data valida no calendario. */ public int adicionaPED(String nome, String categoria, int prodTecnica, int prodAcademica, int patentes, String objetivo, String dataInicio, int duracao) throws ValidacaoException, ParseException, DataException{ Validacao.validaString(nome,"Nome nulo ou vazio" ); Validacao.validaString(categoria, "Categoria invalida"); Validacao.validaString(objetivo,"Objetivo nulo ou vazio"); Validacao.validaInt(prodTecnica, "Numero de producoes tecnicas invalido"); Validacao.validaInt(prodAcademica, "Numero de producoes academicas invalido"); Validacao.validaInt(patentes, "Numero de patentes invalido"); Validacao.validaData(dataInicio); Validacao.validaIntSemZero(duracao,"Duracao invalida"); this.codigosProjeto++; projetosCadastrados.add(factoryProjeto.criaPED(nome, categoria, prodTecnica, prodAcademica, patentes, objetivo, dataInicio, duracao, codigosProjeto)); return codigosProjeto; } /** * O metodo busca determinada infomacao sobre um projeto, atraves do seu codigo e do atributo desejado. * @param codigoProjeto O codigo do projeto * @param atributo A informacao desejada. * @return Retorna a informacao em forma de string. * @throws ValidacaoException Lanca uma excecao se ocorrer um erro na validacao das strings. * @throws ParseException Lanca uma excecao se ocorrer um erro na validacao da data. */ public String getInfoProjeto(int codigoProjeto, String atributo) throws CadastroException, ValidacaoException{ Validacao.validaInt(codigoProjeto,"Codigo invalido"); Validacao.validaString(atributo, "Atributo nulo ou invalido"); Projeto projetoASerConsultado = getProjetos(codigoProjeto); switch (atributo.toLowerCase()) { case NOME: return projetoASerConsultado.getNome(); case OBJETIVO: return projetoASerConsultado.getObjetivo(); case DATAINICIO: return projetoASerConsultado.getDataInicio(); case DISCIPLINA: if(ehMonitoria(projetoASerConsultado, atributo)){ return ((Monitoria) projetoASerConsultado).getDisciplina(); } case RENDIMENTO: if(ehMonitoria(projetoASerConsultado, atributo)){ return ((Monitoria) projetoASerConsultado).getRepresentacaoRendimento(); } else if(ehPET(projetoASerConsultado, atributo)){ return ((PET) projetoASerConsultado).getRepresentacaoRendimento(); } case PERIODO: if(ehMonitoria(projetoASerConsultado, atributo)){ return ((Monitoria) projetoASerConsultado).getPeriodo(); } case DURACAO: return projetoASerConsultado.getRepresentacaoDuracao(); case IMPACTO: if(ehPET(projetoASerConsultado, atributo)){ return ((PET) projetoASerConsultado).getImpactoSocial().getImpactoSocial(); } else if(ehExtensao(projetoASerConsultado, atributo)){ return ((Extensao) projetoASerConsultado).getImpacto().getImpactoSocial(); } case PRODTECNICA: if(ehPET(projetoASerConsultado, atributo)){ return ((PET) projetoASerConsultado).getProdutividade(PRODTECNICA); } else if(ehPED(projetoASerConsultado, atributo)){ return ((PED) projetoASerConsultado).getProdutividade(PRODTECNICA); } case PRODACADEMICA: if(ehPET(projetoASerConsultado, atributo)){ return ((PET) projetoASerConsultado).getProdutividade(PRODACADEMICA); } else if(ehPED(projetoASerConsultado, atributo)){ return ((PED) projetoASerConsultado).getProdutividade(PRODACADEMICA); } case PATENTES: if(ehPET(projetoASerConsultado, atributo)){ return ((PET) projetoASerConsultado).getProdutividade(PATENTES); } else if(ehPED(projetoASerConsultado, atributo)){ return ((PED) projetoASerConsultado).getProdutividade(PATENTES); } case CATEGORIA: if(ehPED(projetoASerConsultado, atributo)) { return ((PED) projetoASerConsultado).getCategoria().getValor(); } case PARTICIPACOES: return projetoASerConsultado.mostraPessoasAssociadas(); default: throw new ValidacaoException("Atributo nulo ou invalido"); } } /** * Verifica se o projeto eh do tipo Monitoria. * @param projeto O projeto que sera verificado * @param atributo O atributo que sera verificado. * @return Retorna true, se for do tipo monitoria, e false, se nao for. * @throws ValidacaoException */ private boolean ehMonitoria(Projeto projeto, String atributo) throws ValidacaoException{ if(projeto instanceof Monitoria){ return true; } else if(projeto instanceof PED){ throw new ValidacaoException("PED nao possui " + atributo); } else if (projeto instanceof Extensao){ throw new ValidacaoException("Extensao nao possui " + atributo); } else if (projeto instanceof PET){ if(atributo.equalsIgnoreCase(RENDIMENTO)){ return false; } throw new ValidacaoException("PET nao possui " + atributo); } return false; } /** * Verifica se o projeto eh do tipo Extensao * @param projeto O projeto que sera verificado * @param atributo O atributo que sera verificado. * @return Retorna true, se for do tipo Extensao, e false, se nao for. * @throws ValidacaoException */ private boolean ehExtensao(Projeto projeto,String atributo) throws ValidacaoException{ if(projeto instanceof Extensao){ return true; } else if(projeto instanceof PED){ throw new ValidacaoException("PED nao possui " + atributo); } else if (projeto instanceof PET){ if(atributo.equalsIgnoreCase(IMPACTO)){ return false; } throw new ValidacaoException("PET nao possui " + atributo); } else if (projeto instanceof Monitoria){ throw new ValidacaoException("Monitoria nao possui " + atributo); } return false; } /** * Verifica se o projeto eh do tipo PED. * @param projeto O projeto que sera verificado * @param atributo O atributo que sera verificado. * @return Retorna true, se for do tipo PED, e false, se nao for. * @throws ValidacaoException */ private boolean ehPED(Projeto projeto,String atributo) throws ValidacaoException{ if(projeto instanceof PED){ return true; } else if(projeto instanceof PET){ if(atributo.equals(PRODTECNICA)){ return false; } else if(atributo.equalsIgnoreCase(PRODACADEMICA)){ return false; } else if(atributo.equalsIgnoreCase(PATENTES)){ return false; } throw new ValidacaoException("PET nao possui " + atributo); } else if (projeto instanceof Extensao){ if(atributo.equalsIgnoreCase(IMPACTO)){ return false; } throw new ValidacaoException("Extensao nao possui " + atributo); } else if (projeto instanceof Monitoria){ if(atributo.equalsIgnoreCase(RENDIMENTO)){ return false; } throw new ValidacaoException("Monitoria nao possui " + atributo); } return false; } /** * Verifica se o projeto eh do tipo PET. * @param projeto O projeto que sera verificado * @param atributo O atributo que sera verificado. * @return Retorna true, se for do tipo PET, e false, se nao for. * @throws ValidacaoException */ private boolean ehPET(Projeto projeto,String atributo) throws ValidacaoException{ if(projeto instanceof PET){ return true; } else if(projeto instanceof PED){ if(atributo.equalsIgnoreCase(PRODTECNICA)){ return false; } else if(atributo.equalsIgnoreCase(PRODACADEMICA)){ return false; } else if(atributo.equalsIgnoreCase(PATENTES)){ return false; } throw new ValidacaoException("PED nao possui " + atributo); } else if (projeto instanceof Extensao){ if(atributo.equalsIgnoreCase(IMPACTO)){ return false; } throw new ValidacaoException("Extensao nao possui " + atributo); } else if (projeto instanceof Monitoria){ if(atributo.equalsIgnoreCase(RENDIMENTO)){ return false; } throw new ValidacaoException("Monitoria nao possui " + atributo); } return false; } public Projeto getProjetos(int codigoProjeto) throws CadastroException { for(Projeto projetoAserEncontrado: projetosCadastrados){ if(projetoAserEncontrado.getCodigo() == codigoProjeto){ return projetoAserEncontrado; } } throw new CadastroException("Projeto nao encontrado"); } /** * O metodo ira modificar algum atributo de um projeto. * @param codigoDoProjeto O codigo do projeto que sera modificado. * @param atributo O atributo que sera modificado. * @param novoValor O novo valor dado ao atributo. * @throws ValidacaoException Lanca uma excecao, se ocorrer um erro na validacao das strings. * @throws ParseException Lanca uma excecao, se ocorrer um erro na validacao da data * @throws DataException Caso a data nao seja uma data valida no calendario. */ public void editaProjeto(int codigoDoProjeto, String atributo, String novoValor) throws CadastroException, ValidacaoException, ParseException, DataException{ Validacao.validaString(atributo, "Atributo nao pode ser vazio ou invalido"); Validacao.validaInt(codigoDoProjeto, "Codigo invalido"); Validacao.validaString(novoValor, atributo + " nulo ou vazio"); Projeto projetoAserAlterado = getProjetos(codigoDoProjeto); switch (atributo.toLowerCase()) { case NOME: projetoAserAlterado.setNome(novoValor); break; case OBJETIVO: projetoAserAlterado.setObjetivo(novoValor); break; case DISCIPLINA: if(ehMonitoria(projetoAserAlterado, DISCIPLINA)){ ((Monitoria) projetoAserAlterado).setDisciplina(novoValor); } break; case PERIODO: if(ehMonitoria(projetoAserAlterado, PERIODO)){ ((Monitoria) projetoAserAlterado).setPeriodo(novoValor); } break; case DATAINICIO: Validacao.validaData(novoValor, "Formato de data invalido"); projetoAserAlterado.setDataInicio(novoValor); break; case CATEGORIA: if(ehPED(projetoAserAlterado, CATEGORIA)){ ((PED) projetoAserAlterado).setCategoria(novoValor); } break; case DURACAO: int novaDuracao = Integer.parseInt(novoValor); projetoAserAlterado.setDuracao(novaDuracao); break; case IMPACTO: int novoImpacto = Integer.parseInt(novoValor); if(ehPET(projetoAserAlterado, IMPACTO)){ ((PET) projetoAserAlterado).setImpacto(novoImpacto); } else if(ehExtensao(projetoAserAlterado, IMPACTO)){ ((Extensao) projetoAserAlterado).setImpacto(novoImpacto); } break; case PRODTECNICA: int novaProd = Integer.parseInt(novoValor); if(ehPET(projetoAserAlterado, PRODTECNICA)){ ((PET) projetoAserAlterado).adicionaProdutividade(PRODTECNICA, novaProd); } else if(ehPED(projetoAserAlterado, PRODTECNICA)){ ((PED) projetoAserAlterado).adicionaProdutividade(PRODTECNICA, novaProd); } break; case PRODACADEMICA: int novaProda = Integer.parseInt(novoValor); if(ehPET(projetoAserAlterado, PRODACADEMICA)){ ((PET) projetoAserAlterado).adicionaProdutividade(PRODACADEMICA, novaProda); } else if(ehPED(projetoAserAlterado, PRODACADEMICA)){ ((PED) projetoAserAlterado).adicionaProdutividade(PRODACADEMICA, novaProda); } break; case PATENTES: int novaPatente = Integer.parseInt(novoValor); if(ehPET(projetoAserAlterado, PATENTES)){ ((PET) projetoAserAlterado).adicionaProdutividade(PATENTES, novaPatente); } else if(ehPED(projetoAserAlterado, PATENTES)){ ((PED) projetoAserAlterado).adicionaProdutividade(PATENTES, novaPatente); } break; default: throw new ValidacaoException("Atributo invalido"); } } /** * Remove um projeto do banco de projetos, atraves do seu codigo. * @param codigoDoProjeto O codigo do projeto que sera removido * @throws CadastroException Retorna uma excecao, se o projeto nao for cadastrado no sistema. * @throws ValidacaoException Caso o codigo do projeto seja invalido. */ public void removeProjeto(int codigoDoProjeto) throws CadastroException, ValidacaoException{ Validacao.validaInt(codigoDoProjeto, "Codigo invalido"); Iterator<Projeto> it = projetosCadastrados.iterator(); while(it.hasNext()) { Projeto projetoProcurado = it.next(); if(projetoProcurado.getCodigo() == codigoDoProjeto) { it.remove(); } } } /** * O metodo vai retornar o codigo de um projeto, atraves do seu nome. * @param nome O nome do projeto que sera procurado. * @return Retorna o inteiro que representa o codigo * @throws CadastroException Retorna uma excecao, se o projeto nao for cadastrado no sistema. * @throws ValidacaoException Caso o nome seja nulo/vazio */ public int getCodigoProjeto(String nome) throws CadastroException, ValidacaoException { Validacao.validaString(nome, "Nome nulo ou vazio"); Iterator<Projeto> it = this.projetosCadastrados.iterator(); while(it.hasNext()) { Projeto projetoProcurado = it.next(); if(projetoProcurado.getNome().equals(nome)) { return projetoProcurado.getCodigo(); } } throw new CadastroException("Projeto nao encontrado"); } /** * Associa uma participacao a um projeto. * Dada uma participacao, adiciona um projeto nesta participacao. * @param participacao Participacao a ser adicionada o projeto. * @param codigoProjeto Codigo do projeto. * @return True se bem sucedido. * @throws CadastroException Caso o projeto nao esteja cadastrado. */ public boolean associaProjeto(Participacao participacao, int codigoProjeto) throws CadastroException { Projeto projeto = this.getProjetos(codigoProjeto); participacao.setProjeto(projeto); return true; } /** * Dada uma participacao com Pessoa e Projeto ja incluso, adiciona em projeto a participacao dada. * * @param participacao Participacao a ser armazenada. * @param codigoProjeto Codigo do projeto. * @throws CadastroException Caso o projeto nao esteja cadastrado. * @throws ValidacaoException Caso os parametros passados sejam nulo/vazio */ public void adicionaParticipacao(Participacao participacao, int codigoProjeto) throws CadastroException, ValidacaoException { Projeto projeto = this.getProjetos(codigoProjeto); projeto.adicionaParticipacao(participacao); } /** * Remove uma participacao que o projeto tem no sistema. * Como projeto tem suas participacoes, ele pode remover a pessoa do projeto explicitado, causando assim a quebra da participacao. * @param participacao Participacao a ser removida. * @param codigoProjeto Codigo do projeto a ser removido. * @throws CadastroException Caso o projeto nao esteja cadastrado. * @throws ValidacaoException Caso os parametros passados sejam nulo/vazios */ public void removeParticipacao(Participacao participacao, int codigoProjeto) throws CadastroException, ValidacaoException { Projeto projeto = this.getProjetos(codigoProjeto); projeto.removeParticipacao(participacao); } /** * Pesquisa um projeto no sistema. * @param codigoProjeto Codigo do projeto a ser procurado. * @return True se bem sucedido. * @throws CadastroException Caso o projeto nao seja encontrado. */ public boolean pesquisaProjeto(int codigoProjeto) throws CadastroException { Iterator<Projeto> it = this.projetosCadastrados.iterator(); while(it.hasNext()) { Projeto projetoProcurado = it.next(); if(projetoProcurado.getCodigo() == codigoProjeto) { return true; } } throw new CadastroException("Projeto nao encontrado"); } @Override public String toString() { String toString = ""; for(Projeto projeto: this.projetosCadastrados) { toString += projeto + FIM_DE_LINHA; } return toString; } /** * Verifica a logica por tras, para um dado professor verificar seu valorHora. * @param valorHora Valor da hora do professor. * @param codigoProjeto Codigo do projeto a ser procurado. * @return True se bem sucedido. False caso contrario. * @throws CadastroException Caso o projeto nao esteja cadastrado. * @throws ValidacaoException Caso o valorHora do professor seja invalido para o projeto em questao. */ public boolean validaHoraProfessor(double valorHora, int codigoProjeto) throws CadastroException, ValidacaoException { Projeto projeto = this.getProjetos(codigoProjeto); if(projeto instanceof Monitoria) { if(valorHora > 0) { throw new ValidacaoException("Valor da hora de um professor da monitoria deve ser zero"); } return true; } Validacao.validaDoubleSemZero(valorHora, "Valor da hora invalido"); return false; } public String geraRelatorioCadProjetos() throws IOException { String relatorio = "Cadastro de Projetos: " + this.projetosCadastrados.size() + " projetos registrados" + FIM_DE_LINHA; int contProjetos = 1; double totalParticipantesProjeto = 0; int totalParticipantesGraduacao = 0; int totalParticipantesPosGraduando = 0; int totalParticipantesProfissionais = 0; int totalProjetosConcluidos = 0; for(Projeto projeto: this.projetosCadastrados) { relatorio += "==> Projeto " + contProjetos + ":" + FIM_DE_LINHA; relatorio += projeto.toString() + FIM_DE_LINHA + FIM_DE_LINHA; // depois resolver totalParticipantesProjeto += projeto.getTotalParticipantes(); totalParticipantesGraduacao += projeto.getTotalParticipantes("Aluno Graduando"); totalParticipantesPosGraduando += projeto.getTotalParticipantes("Aluno Pos Graduando"); totalParticipantesProfissionais += projeto.getTotalParticipantes("Profissional"); if(projeto.getProjetoConcluido()) { totalProjetosConcluidos ++; } } relatorio += "Total de projetos concluidos: " + totalProjetosConcluidos + FIM_DE_LINHA; // porcentagem participantes double porcentagemGraduacao = (totalParticipantesGraduacao / totalParticipantesProjeto) * 100; double porcentagemPosGraduacao = (totalParticipantesPosGraduando / totalParticipantesProjeto ) * 100; double porcentagemProfissionais = (totalParticipantesProfissionais / totalParticipantesProjeto) * 100; int parteInteiraG = (int) porcentagemGraduacao; int parteInteiraPG = (int) porcentagemPosGraduacao; int parteInteiraPR = (int) porcentagemProfissionais; if((porcentagemGraduacao - parteInteiraG) >= 0.5) { porcentagemGraduacao = Math.ceil(porcentagemGraduacao); } if((porcentagemPosGraduacao - parteInteiraPG) >= 0.5) { porcentagemPosGraduacao = Math.ceil(porcentagemPosGraduacao); } if((porcentagemProfissionais - parteInteiraPR) >= 0.5) { porcentagemProfissionais = Math.ceil(porcentagemProfissionais); } relatorio += "%" + String.format(" Participacao da graduacao: %d %.1f", totalParticipantesGraduacao, porcentagemGraduacao) + " %" + FIM_DE_LINHA; relatorio += "%" + String.format(" Participacao da pos-graduacao: %d %.1f", totalParticipantesPosGraduando, porcentagemPosGraduacao) + " %" + FIM_DE_LINHA;; relatorio += "%" + String.format(" Participacao de profissionais: %d %.1f", totalParticipantesProfissionais, porcentagemProfissionais) + " %" + FIM_DE_LINHA;; this.salvaRelatorio(relatorio); return relatorio; } private void salvaRelatorio(String relatorio) throws IOException { PrintWriter arquivo = null; try { arquivo = new PrintWriter(new BufferedWriter(new FileWriter("arquivos_sistema/relatorios/cad_projetos.txt"))); arquivo.println(relatorio); } finally { if(arquivo != null) { arquivo.close(); } } } /** * Atualiza todas as despesas de um projeto, atraves do codigo. * @param codigoProjeto O codigo do projeto. * @param montanteBolsas O valor do montante das Bolsas. * @param montanteCusteio O valor do montante do Custeio. * @param montanteCapital O valor do montante do Capital. * @throws ValidacaoException Lanca uma excecao, se algum dos parametros for invalido. * @throws CadastroException Lanca uma excecao, se o codigo do projeto ainda nao existir no sistema. */ public void atualizaDespesasProjeto(String codigoProjeto, double montanteBolsas, double montanteCusteio, double montanteCapital) throws ValidacaoException, CadastroException { Validacao.validaRepresentacaoCodigoProjeto(codigoProjeto, "codigo nulo ou vazio"); Validacao.validaDouble(montanteBolsas, "valor negativo"); Validacao.validaDouble(montanteCusteio, "valor negativo"); Validacao.validaDouble(montanteCapital, "valor negativo"); Projeto projeto = this.getProjetos(Integer.parseInt(codigoProjeto)); projeto.atualizaDespesasProjeto(montanteBolsas, montanteCusteio, montanteCapital); } /** * Calcula a colaboracao de um projeto para a UASC. * @param codigoProjeto O codigo do projeto * @return Retorna o valor da contribuicao do projeto para a UASC. * @throws CadastroException Se o codigo do projeto nao existir no sistema, uma excecao eh lancada. * @throws ValidacaoException */ public double calculaColaboracaoUASC(int codigoProjeto) throws CadastroException, ValidacaoException { Projeto projeto = this.getProjetos(codigoProjeto); double colaboracao = projeto.geraContribuicao(); this.geraHistoricoColaboracaoUasc(projeto.getData(), projeto.getNome(), colaboracao); return colaboracao; } private void geraHistoricoColaboracaoUasc(String data, String nome, double colaboracao) { this.historicoColaboracaoUasc += "==> Nome: " + nome + " Data de inicio: " + data + " Valor colaborado: R$ " + colaboracao + FIM_DE_LINHA; } public String getHistoricoColaboracaoUasc() { return this.historicoColaboracaoUasc; } }
/* * ThreeAndFive.java * * Copyright 2014 * * Michael Funk * mafunk92@gamail.com * @mafunk92 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * */ import java.util.*; import java.io.*; public class ThreeAndFive { // Global Variables private ArrayList<Integer> array = new ArrayList<Integer>(); private int length = 0; private int sum =0; // Constructors public ThreeAndFive(){ array = null; } // End Constructor public ThreeAndFive(int max){ // System.out.println("In Constructor"); for( int i = 0; i < max; i++){ if( (i % 3 == 0 ) || (i % 5 == 0) ){ array.add(i); sum += i; length++; } // End If } // End For Loop // for(int j=0; j< length; j++){ //debug: what is in arraylist // System.out.print(" ," + array.get(j)); // } // End For Loop // System.out.println(""); // System.out.println( "length: " + length + ", sum: " + sum); } // End Constructor // Methods public int getSum(){ return sum; } // End getSum() public void print(int max){ System.out.println("Numbers divisible by 3 or 5 under " + max + " :"); //print array for( int i=0; i<length;i++){ System.out.print( array.get(i) + " "); } // End For Loop System.out.println(""); System.out.println(""); //print sum of arary System.out.println("Sum of 3 and 5's under " + max + " is: " + sum ); System.out.println(""); } // End print() // Main public static void main (String args[]) { int max = 1000; ThreeAndFive obj = new ThreeAndFive(max); obj.print(max); } // End Main }
package holder; import java.util.*; public class SolverPFour { public static void main(String[] args) { String str = "PWWKEW"; longestStringNoRepeat(str); int[] numArr = {1, 1, 3, 1, 2, 1, 3, 3, 3, 3}; ArrayList<Integer> nums = new ArrayList<>(); for(int i =0; i<numArr.length ;i++) { nums.add(numArr[i]); } // System.out.println(numberOfSocks(10, nums)); int[] num1 = {1,2,3,4,5}; System.out.println(Arrays.toString(rotLeft(num1,1))); } public static int[] rotLeft(int[] a, int d) { int[] aShifted = new int[a.length]; Stack<Integer> aStack = new Stack<>(); Queue<Integer> aQueue = new LinkedList(); // for(int i =0;i <d/2;i++) { // int firInt = a[i]; // int secInt = a[a.length-i]; // a[i] = secInt; // a[a.length-i] = firInt; // } for(int i =0; i <a.length;i++) { int newLocation = (i + (a.length - d)) % a.length; a[newLocation]= a[i]; } return a; } //Done public static int numberOfSocks(int nlenght, List<Integer>nums) { int numberOfPairs =0; HashMap<Integer,Integer> socksMap = new HashMap<>(); for(int i=0;i<nlenght ;i++) { int sockAtIndex = nums.get(i); int numOfcurrentSocks = socksMap.getOrDefault(sockAtIndex, 0); socksMap.put(sockAtIndex, numOfcurrentSocks+1); } for(int j=0;j<nlenght;j++) { int sockAtIndexTwo = nums.get(j); if(socksMap.get(sockAtIndexTwo) != null && socksMap.get(sockAtIndexTwo) > 1) { numberOfPairs+= socksMap.get(sockAtIndexTwo) /2; socksMap.remove(sockAtIndexTwo); } } return numberOfPairs; } public static int[] runningSum(int[] nums) { int[] runningSumArr = new int[nums.length]; int currentSum=0; for(int i =0;i<nums.length;i++) { currentSum+=nums[i]; runningSumArr[i] = currentSum; } return runningSumArr; } public static String shortestSubString(String s, String t) { StringBuilder shortestSubString = new StringBuilder(); HashMap<Character,Integer> tHashMap= new HashMap<>(); int windowStartIndex=0; int windowEndIndex =0; int windowMinSize= Integer.MAX_VALUE; int counter=0; int[] windowSizeArr= new int[2]; for(int i =0;i<t.length();i++) tHashMap.put(t.charAt(i), i); for(int j = 0 ; j<s.length();j++) { windowStartIndex=j; // while(counter <t.length()) { for(int k=j;k<s.length();k++) { if(tHashMap.containsKey(s.charAt(k))) { counter++; } windowEndIndex+=1; } // windowMinSize=Math.max(windowMinSize, windowEndIndex-windowStartIndex); if(windowEndIndex-windowStartIndex <= windowMinSize) { windowSizeArr[0]=windowStartIndex; windowSizeArr[1] = windowEndIndex; } } // for(int g =window) return shortestSubString.toString(); } public static void longestStringNoRepeat(String str) { Queue<Character> subStringQueue = new LinkedList<>(); HashMap<Character,Integer> subStringMap = new HashMap<>(); int windowStartIndex=0; int windowEndIndex=0; int maxWindowSize=0; for(int i=0;i<str.length();i++) { windowEndIndex+=1; subStringMap.put(str.charAt(i), subStringMap.getOrDefault(str.charAt(i), 0) + 1); subStringQueue.add(str.charAt(i)); // while(subStringMap.containsKey(str.charAt(i)) ) { if(subStringMap.containsKey(str.charAt(i)) && subStringMap.get(str.charAt(i)) > 1) { subStringMap.remove(str.charAt(windowStartIndex)); windowStartIndex+=1; while(subStringMap.getOrDefault((str.charAt(i)),0) > 1) { subStringQueue.remove(str.charAt(windowStartIndex)); subStringMap.remove(windowStartIndex-1); windowStartIndex+=1; subStringMap.put(str.charAt(i), subStringMap.getOrDefault(str.charAt(i), 0) -1); if(subStringMap.get(str.charAt(i)) <1) { subStringMap.remove(str.charAt(i)); } } } // if(!subStringMap.containsKey(str.charAt(i))) { // } maxWindowSize =Math.max(maxWindowSize, windowEndIndex-windowStartIndex); } // return maxWindowSize; System.out.println( maxWindowSize + " " + subStringMap.toString()); } }
package com.santos.android.evenlychallenge.API; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonSetter; /** * Created by Abel Cruz dos Santos on 16.08.2017. */ @JsonIgnoreProperties(ignoreUnknown=true) public class Location { private String mAddress; private String mCrossStreet; private double mLat; private double mLon; private int mDistance; private String[] mFormattedAddress; public String getAddress() { return mAddress; } @JsonSetter("address") public void setAddress(String address) { mAddress = address; } public String getCrossStreet() { return mCrossStreet; } @JsonSetter("crossStreet") public void setCrossStreet(String crossStreet) { mCrossStreet = crossStreet; } public double getLat() { return mLat; } @JsonSetter("lat") public void setLat(double lat) { mLat = lat; } public double getLon() { return mLon; } @JsonSetter("lng") public void setLon(double lon) { mLon = lon; } public int getDistance() { return mDistance; } @JsonSetter("distance") public void setDistance(int distance) { mDistance = distance; } public String[] getFormattedAddress() { return mFormattedAddress; } @JsonSetter("formattedAddress") public void setFormattedAddress(String[] formattedAddress) { mFormattedAddress = formattedAddress; } }
package com.esum.framework.core.component.listener.channel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.esum.framework.core.component.code.ComponentCode; import com.esum.framework.core.component.handler.OutboundHandler; import com.esum.framework.core.event.log.ErrorInfo; import com.esum.framework.core.event.message.MessageEvent; import com.esum.framework.core.event.message.RoutingInfo; import com.esum.framework.core.exception.SystemException; public class ChannelMessageListenerAdapter extends ChannelMessageListener<MessageEvent> { private Logger logger = LoggerFactory.getLogger(ChannelMessageListenerAdapter.class); private OutboundHandler outboundHandler; public ChannelMessageListenerAdapter(String componentId, String channelName) throws SystemException { super(componentId, channelName); } @Override public MessageEvent onEvent(MessageEvent messageEvent) { traceId = "[" + messageEvent.getMessageControlId() + "] "; logger.info(traceId + "Recevied MessageEvent...."); try { if(outboundHandler==null) throw new Exception("OutboundHandler is not set."); outboundHandler.process(messageEvent); if(messageEvent.getRoutingInfo().getRouteType().equals(RoutingInfo.SYNC_ROUTING)) return outboundHandler.processResponse(messageEvent); } catch (Exception e) { logger.error(traceId + "onMessageEvent()", e); ErrorInfo errorInfo = new ErrorInfo(ComponentCode.ERROR_UNDEFINED, "onMessageEvent()", e.getMessage()); messageEvent.getMessage().getHeader().setErrorInfo(errorInfo); if(messageEvent.getRoutingInfo().getRouteType().equals(RoutingInfo.SYNC_ROUTING)) return messageEvent; } return null; } public OutboundHandler getOutboundHandler() { return outboundHandler; } public void setOutboundHandler(OutboundHandler outboundHandler) { this.outboundHandler = outboundHandler; } }
package com.study.dynamic; /** * Created by sandy on 8/8/2015. */ public class ZeroOneKnapsackProblem { public static void main(String[] args) { int maxWeight = 7; int[] weight = {1,3,4,5}; int[] val = {1,4,5,7}; int[][] dp = new int[weight.length+1][maxWeight+1]; //initialize the function for(int i = 0 ; i < weight.length ; i++) dp[i][0] = 0; for (int i = dp[0].length - 1; i >= 0; i--) { dp[0][i] = 0; } //Populate the dp table for(int i = 1 ; i <= weight.length; i++ ){ for(int j = 1 ; j <= maxWeight; j++ ){ if( j < weight[i-1] ) dp[i][j] = dp[i-1][j]; else { int maxWithItemI = 0; if( j - weight[i-1] >= 0 ) maxWithItemI = val[i-1] + dp[i-1][j-weight[i-1]]; dp[i][j] = Math.max(dp[i - 1][j], maxWithItemI); } } } System.out.println("Max weight that can be taken is:"+dp[weight.length][maxWeight]); } }
package com.akanar.model; import java.text.NumberFormat; import java.util.Date; public class AccountInfo { private long account_id; private UserInfo userinfo; private String account_type; private double balance; private float interest; private Date joindate; public AccountInfo() { // TODO Auto-generated constructor stub } public AccountInfo(long account_id, UserInfo userinfo, String account_type, double balance, float interest, Date joindate) { super(); this.account_id = account_id; this.userinfo = userinfo; this.account_type = account_type; this.balance = balance; this.interest = interest; this.joindate = joindate; } public long getAccount_id() { return account_id; } public void setAccount_id(long account_id) { this.account_id = account_id; } public UserInfo getUserinfo() { return userinfo; } public void setUserinfo(UserInfo userinfo) { this.userinfo = userinfo; } public String getAccount_type() { return account_type; } public void setAccount_type(String account_type) { this.account_type = account_type; } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } public float getInterest() { return interest; } public void setInterest(float interest) { this.interest = interest; } public Date getJoindate() { return joindate; } public void setJoindate(Date joindate) { this.joindate = joindate; } @Override public String toString() { String display = account_type.toUpperCase() + " ACCOUNT " + account_id + "\n" + "=================================\n" + "Available Balance | " + NumberFormat.getCurrencyInstance().format(balance); return display; } }
/* * (C) Copyright 2018 Florian Bernard. * 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.elasticsearch.plugin.keycloak; import org.elasticsearch.plugin.keycloak.realm.BearerToken; import org.elasticsearch.plugins.ActionPlugin; import org.elasticsearch.plugins.Plugin; import java.util.Collection; import java.util.Collections; public class KeycloakSecurityPlugin extends Plugin implements ActionPlugin { @Override public Collection<String> getRestHeaders() { return Collections.singletonList(BearerToken.BEARER_AUTH_HEADER); } }
package com.infoworks.lab.components.db.source; import com.infoworks.lab.components.crud.components.datasource.GridDataSource; import com.infoworks.lab.jsql.DataSourceKey; import com.infoworks.lab.jsql.ExecutorType; import com.infoworks.lab.jsql.JsqlConfig; import com.it.soul.lab.sql.QueryExecutor; import com.it.soul.lab.sql.entity.EntityInterface; import com.it.soul.lab.sql.query.SQLSelectQuery; import com.vaadin.flow.data.provider.Query; public interface JsqlDataSource<T extends EntityInterface> extends GridDataSource<T> { QueryExecutor getExecutor(); JsqlDataSource setExecutor(QueryExecutor executor); SQLSelectQuery getSelectQuery(Query<T, String> query); SQLSelectQuery getSearchQuery(Query<T, String> query); int getRowCount(); static <GDS extends GridDataSource> GDS createDataSource(Class<GDS> type, ExecutorType executorType, DataSourceKey container) throws RuntimeException { JsqlConfig config = new JsqlConfig(); GDS source = null; try { source = type.newInstance(); if (JsqlDataSource.class.isAssignableFrom(type)){ QueryExecutor executor = config.create(executorType, container.get(DataSourceKey.Keys.NAME), container); ((JsqlDataSource<EntityInterface>)source).setExecutor(executor); } } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(e.getMessage()); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } return source; } static <GDS extends GridDataSource> GDS createDataSource(Class<GDS> type, ExecutorType executorType){ return createDataSource(type, executorType, DataSourceKey.createDataSourceKey("app.db")); } }
package com.SearchHouse.pojo; import java.util.Set; public class Fitment { private Integer fitmentId; private String fitmentName; public Integer getFitmentId() { return fitmentId; } public void setFitmentId(Integer fitmentId) { this.fitmentId = fitmentId; } public String getFitmentName() { return fitmentName; } public void setFitmentName(String fitmentName) { this.fitmentName = fitmentName; } public Fitment(Integer fitmentId, String fitmentName) { super(); this.fitmentId = fitmentId; this.fitmentName = fitmentName; } public Fitment() { } @Override public String toString() { return "Fitment [fitmentId=" + fitmentId + ", fitmentName=" + fitmentName + "]"; } }
public class ArrayListOfStrings2 implements ListOfStrings { /** * Implémentation par un tableau * que l'on redimensionnera à chaque ajout si il est plein * (en doublant sa taille) */ private static final int MINIMAL_SIZE = 4; private String[] array; int nbElements; public ArrayListOfStrings2() { array = new String[MINIMAL_SIZE]; nbElements = 0; } @Override public void add(String s) { // faut il agrandir ? if (nbElements == array.length) { String[] tmp = new String[array.length * 2]; // on double for(int i=0; i < array.length; i++) { tmp[i] = array[i]; } array = tmp; } // ajouter array[nbElements] = s; nbElements += 1; } @Override public int size() { return nbElements; } @Override public void set(int i, String s) { array[i] = s; } @Override public String get(int i) { return array[i]; } }
package uk.ac.ebi.intact.view.webapp.controller.application; import java.text.SimpleDateFormat; import java.util.Date; /** * Entry containing stats information * * @author Rafael C Jimenez (rafael@ebi.ac.uk) * @version $Id$ * @since 4.0.2-SNAPSHOT */ public class StatsEntry { Integer ac; Date timestamp; Integer proteinNumber; Integer interactionNumber; Integer binaryInteractions; Integer complexInteractions; Integer experimentNumber; Integer termNumber; Integer publicationCount; public StatsEntry(Integer ac, Date timestamp, Integer proteinNumber, Integer interactionNumber, Integer binaryInteractions, Integer complexInteractions, Integer experimentNumber, Integer termNumber, Integer publicationCount) { this.ac = ac; this.timestamp = timestamp; this.proteinNumber = proteinNumber; this.interactionNumber = interactionNumber; this.binaryInteractions = binaryInteractions; this.complexInteractions = complexInteractions; this.experimentNumber = experimentNumber; this.termNumber = termNumber; this.publicationCount = publicationCount; } public Integer getAc() { return ac; } public Date getTimestamp() { return timestamp; } public int getTimestampYear(){ SimpleDateFormat simpleDateformat =new SimpleDateFormat("yyyy"); return Integer.parseInt(simpleDateformat.format(timestamp)); } public int getTimestampMonth(){ SimpleDateFormat simpleDateformat =new SimpleDateFormat("M"); return Integer.parseInt(simpleDateformat.format(timestamp)); } public int getTimestampDay(){ SimpleDateFormat simpleDateformat =new SimpleDateFormat("d"); return Integer.parseInt(simpleDateformat.format(timestamp)); } public String getTimestampJavaScript(){ String jsT = "Date.UTC("; jsT += getTimestampYear() + ","; /* months start at 0 for January, 1 for February etc. */ jsT += getTimestampMonth()-1 + ","; jsT += getTimestampDay(); jsT += ")"; return jsT; } public Integer getProteinNumber() { return proteinNumber; } public Integer getInteractionNumber() { return interactionNumber; } public Integer getBinaryInteractions() { return binaryInteractions; } public Integer getComplexInteractions() { return complexInteractions; } public Integer getExperimentNumber() { return experimentNumber; } public Integer getTermNumber() { return termNumber; } public Integer getPublicationCount() { return publicationCount; } }
/* * 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 view; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import model.Object_model1; /** * * @author students */ public class Macros extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pageTitle="FractalGeometry"; response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<html>"); out.println("<head>"); out.println("<title>"+pageTitle+"</title>"); out.println("</head>"); out.println("<body bgcolor='white'>"); out.println("<table border='1' cellpadding= '5' cellspacing='0' width='400'>"); out.println("<tr bgcolor='#CCCCFF' align='center' valign= 'center' height='20'> <td><h3>Duke's Soccer League: HOme</h3></td>"); out.println("</tr>"); out.println("</p> "); out.println("<h3>Players</h3>"); out.println("</tr>"); out.println("</table>"); out.println("<p>"); out.println("The set of Soccer Leagues are:"); out.println("</p>"); out.println("<ul>"); Object_model1 ob; ob = new Object_model1(); out.println("<li>"+ob.zoomin()+"</li>"); out.println("</ul>"); out.println("</body>"); out.println("</html>"); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
package org.exoplatform.management.content.operations.site.seo; import java.util.ArrayList; import java.util.List; import org.exoplatform.commons.utils.LazyPageList; import org.exoplatform.portal.config.DataStorage; import org.exoplatform.portal.config.Query; import org.exoplatform.portal.config.model.Page; import org.exoplatform.portal.mop.SiteType; import org.exoplatform.services.seo.PageMetadataModel; import org.exoplatform.services.seo.SEOService; import org.gatein.management.api.PathAddress; import org.gatein.management.api.exceptions.OperationException; import org.gatein.management.api.operation.OperationContext; import org.gatein.management.api.operation.OperationHandler; import org.gatein.management.api.operation.OperationNames; import org.gatein.management.api.operation.ResultHandler; import org.gatein.management.api.operation.model.ExportResourceModel; /** * @author <a href="mailto:thomas.delhomenie@exoplatform.com">Thomas * Delhoménie</a> * @version $Revision$ */ public class SiteSEOExportResource implements OperationHandler { @Override public void execute(OperationContext operationContext, ResultHandler resultHandler) throws OperationException { try { String operationName = operationContext.getOperationName(); PathAddress address = operationContext.getAddress(); String siteName = address.resolvePathTemplate("site-name"); if (siteName == null) { throw new OperationException(operationName, "No site name specified."); } resultHandler.completed(new ExportResourceModel(getSEOExportTask(operationContext, siteName))); } catch (Exception e) { throw new OperationException(OperationNames.EXPORT_RESOURCE, "Unable to retrieve the list of the contents sites : " + e.getMessage()); } } @SuppressWarnings("unused") private SiteSEOExportTask getSEOExportTask(OperationContext operationContext, String siteName) throws Exception { DataStorage dataStorage = operationContext.getRuntimeContext().getRuntimeComponent(DataStorage.class); LazyPageList<Page> pagLazyList = dataStorage.find(new Query<Page>(SiteType.PORTAL.getName(), siteName, Page.class)); SEOService seoService = operationContext.getRuntimeContext().getRuntimeComponent(SEOService.class); List<Page> pageList = pagLazyList.getAll(); List<PageMetadataModel> pageMetadataModels = new ArrayList<PageMetadataModel>(); for (Page page : pageList) { PageMetadataModel pageMetadataModel = null;// TODO ECMS-4030 -> // seoService.getPageMetadata(page.getPageId()); if (pageMetadataModel != null && pageMetadataModel.getKeywords() != null && !pageMetadataModel.getKeywords().isEmpty()) { pageMetadataModels.add(pageMetadataModel); } } return new SiteSEOExportTask(pageMetadataModels, siteName); } }
package king.echomood.compition.Question; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.util.Random; import io.realm.Realm; import io.realm.RealmConfiguration; import io.realm.RealmResults; import king.echomood.compition.Question_list; import king.echomood.compition.R; import king.echomood.compition.adding_Question; import king.echomood.compition.classes.Create_Question; import king.echomood.compition.classes.Question; public class Four extends AppCompatActivity { TextView question, type ,score_Text, stage , generate; Button Answ1_Btn , Answ2_Btn , Answ3_Btn , Answ4_Btn ; int[] num ; ImageView adding , next; int locat =0 ,test_Answ, real_Answer; int i ; String chi; private RealmConfiguration realmConfiguration; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); question = (TextView) findViewById(R.id.questText); score_Text = (TextView) findViewById(R.id.pointText); type = (TextView) findViewById(R.id.stage); realmConfiguration = new RealmConfiguration.Builder(Four.this).build(); Realm.setDefaultConfiguration(realmConfiguration); Answ1_Btn = (Button) findViewById(R.id.answ1Btn); Answ2_Btn = (Button) findViewById(R.id.answ2Btn); Answ3_Btn = (Button) findViewById(R.id.answ3Btn); Answ4_Btn = (Button) findViewById(R.id.answ4Btn); generate = (TextView) findViewById(R.id.generateTaxt); adding = (ImageView) findViewById(R.id.nextBtn); next = (ImageView) findViewById(R.id.prevwBtn); generate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { setQuestion_Classic(); } }); } @Override protected void onResume() { super.onResume(); setQuestion_Classic(); Answ1_Btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { check_Answer(1); } }); Answ2_Btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { check_Answer(2); } }); Answ3_Btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { check_Answer(3); } }); Answ4_Btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { check_Answer(4); } }); next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(Four.this, Question_list.class)); } }); question.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { question.setText(chi); } }); adding.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(Four.this , adding_Question.class)); } }); } Realm realm; public void setQuestion_Classic() { try { realm = Realm.getDefaultInstance(); realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { RealmResults<Question> r1 = realm.where(Question.class).findAll(); String[] size_Check = new String[r1.size()]; int db_size = 0; for (int j = 0; j < size_Check.length; j++) { db_size = j; } num = new int[db_size]; Random r = new Random(); i = r.nextInt(db_size); Toast.makeText(getApplication(), i + "" , Toast.LENGTH_SHORT).show(); num[locat] = i; chi += i + ""; locat++; final Question questio1 = r1.get(i); real_Answer = questio1.getReal_answer(); question.setText(questio1.getQuestion().toString()); Answ1_Btn.setText(questio1.getAnsw1().toString()); Answ2_Btn.setText(questio1.getAnsw2().toString()); Answ3_Btn.setText(questio1.getAnsw3().toString()); Answ4_Btn.setText(questio1.getAnsw4().toString()); } }); } catch (Exception e) { Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG).show(); } } void check_Answer (int answ) { if (real_Answer == answ) { Toast.makeText(getApplicationContext(), " wow ", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), " Bad ", Toast.LENGTH_SHORT).show(); } setQuestion_Classic(); } }
package com.cbs.edu.jdbc.examples.dao; import com.cbs.edu.jdbc.objects.User; public interface UserDAO extends DAO<User> { User getByUsername (String username); }
package com.bfwg.repository; import com.bfwg.model.PrimaryAccount; import org.springframework.transaction.annotation.Transactional; @Transactional public interface PrimaryAccountRepo extends AccountBaseRepo<PrimaryAccount> { }
package com.share.template; import org.hibernate.Session; public interface CallBackObject { public Object doSomeThing(Session session); }
package com.emg.projectsmanage.dao.task; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.dbcp.BasicDataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; import com.emg.projectsmanage.common.Common; import com.emg.projectsmanage.pojo.ConfigDBModel; @Component public class TaskLinkErrorModelDao { private static final Logger logger = LoggerFactory.getLogger(TaskLinkErrorModelDao.class); public List<Map<String, Object>> groupTaskLinkErrorByTime(ConfigDBModel configDBModel, String time) { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); BasicDataSource dataSource = null; try { if (time == null || time.isEmpty()) return list; String startTime = time; String endTime = String.format("%s 23:59:59", time); StringBuffer sql = new StringBuffer(); sql.append(" SELECT"); sql.append(" taskid,"); sql.append(" COUNT ( 1 ) AS count,"); sql.append(" SUM( CASE WHEN errortype BETWEEN 10000000000 AND 19999999999 THEN 1 ELSE 0 END ) AS errorcount,"); sql.append(" SUM( CASE WHEN errortype BETWEEN 20000000000 AND 29999999999 THEN 1 ELSE 0 END ) AS visualerrorcount"); sql.append(" FROM "); sql.append(configDBModel.getDbschema()).append("."); sql.append(" tb_task_link_error "); sql.append(" WHERE pstate = 2 "); sql.append(" AND updatetime BETWEEN '" + startTime + "' AND '" + endTime + "' "); sql.append(" GROUP BY taskid"); dataSource = Common.getDataSource(configDBModel); list = new JdbcTemplate(dataSource).queryForList(sql.toString()); } catch (Exception e) { logger.error(e.getMessage(), e); list = new ArrayList<Map<String, Object>>(); } finally { if (dataSource != null) { try { dataSource.close(); } catch (SQLException e) { logger.error(e.getMessage(), e); } } } return list; } }
package net; import tree.Person; /** * Created by samosbor on 5/18/18. */ public class PersonResult { /** * An array of person objects to return */ Person[] data; String message; /** * The constructor for the person result object * * @param data */ public PersonResult(Person[] data) { this.data = data; } public PersonResult(String message) { this.message = message; } public Person[] getData() { return data; } public void setData(Person[] data) { this.data = data; } }
package p.a.task; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by Huynh Thanh Long. * Date: 7/9/17. */ final class SchedulerList extends AbstractList<Contract.Runnable> { /** Dummy value to associate with an Object in the backing Map */ private static final Object PRESENT = new Object(); /** Contract.Runnable Map */ private final Map<Contract.Runnable, Object> mSchedulerMap = new HashMap<>(); /** Contract.Runnable List */ private final List<Contract.Runnable> mSchedulerList = new ArrayList<>(); /** * Find Insert Position * @param scheduler Contract.Runnable * @param start Start * @param end End * @return Position */ private int findInsertPosition(Contract.Runnable scheduler, int start, int end) { if (start > end) { return start; } int mid = (start + end) / 2; Contract.Runnable pivot = mSchedulerList.get(mid); if (start == end) { if (pivot.getPriority() < scheduler.getPriority()) { return start; } else { return start + 1; } } else { if (pivot.getPriority() < scheduler.getPriority()) { return findInsertPosition(scheduler, start, mid); } else { return findInsertPosition(scheduler, mid + 1, end); } } } /** * Find Insert Position * @param scheduler Contract.Runnable * @return Position */ private int findInsertPosition(Contract.Runnable scheduler, int size) { return findInsertPosition(scheduler, 0, size - 1); } /** * Appends the specified element to the end of this list (optional * operation). * <p> * <p>Lists that support this operation may place limitations on what * elements may be added to this list. In particular, some * lists will refuse to add null elements, and others will impose * restrictions on the type of elements that may be added. List * classes should clearly specify in their documentation any restrictions * on what elements may be added. * <p> * <p>This implementation calls {@code add(size(), e)}. * <p> * <p>Note that this implementation throws an * {@code UnsupportedOperationException} unless * {@link #add(int, Object) add(int, E)} is overridden. * * @param scheduler element to be appended to this list * @return {@code true} (as specified by {@link Collection#add}) * @throws UnsupportedOperationException if the {@code add} operation * is not supported by this list * @throws ClassCastException if the class of the specified element * prevents it from being added to this list * @throws NullPointerException if the specified element is null and this * list does not permit null elements * @throws IllegalArgumentException if some property of this element * prevents it from being added to this list */ @Override public boolean add(Contract.Runnable scheduler) { if (mSchedulerMap.put(scheduler, PRESENT) != null) { return false; } int size = mSchedulerList.size(); int index = findInsertPosition(scheduler, size); if (index >= size) { mSchedulerList.add(scheduler); } else { mSchedulerList.add(index, scheduler); } return true; } /** * {@inheritDoc} * * @param index * @throws IndexOutOfBoundsException {@inheritDoc} */ @Override public Contract.Runnable get(int index) { return mSchedulerList.get(index); } /** * Returns the number of elements in this list. If this list contains * more than <tt>Integer.MAX_VALUE</tt> elements, returns * <tt>Integer.MAX_VALUE</tt>. * * @return the number of elements in this list */ @Override public int size() { return mSchedulerList.size(); } /** * {@inheritDoc} * <p> * <p>This implementation first gets a list iterator (with * {@code listIterator()}). Then, it iterates over the list until the * specified element is found or the end of the list is reached. * * @param o * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ @Override public int indexOf(Object o) { return mSchedulerList.indexOf(o); } /** * {@inheritDoc} * <p> * <p>This implementation always throws an * {@code UnsupportedOperationException}. * * @param index * @throws UnsupportedOperationException {@inheritDoc} * @throws IndexOutOfBoundsException {@inheritDoc} */ @Override public Contract.Runnable remove(int index) { Contract.Runnable scheduler = mSchedulerList.remove(index); mSchedulerMap.remove(scheduler); return scheduler; } }
package com.kh.jd.comment; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class CommentController { @Autowired CommentService cService; // 댓글 리스트 @RequestMapping(value = "/listNotice/commentList/{notice_no}", method = RequestMethod.GET) @ResponseBody public List<Comment> getNoticeCommentList(@PathVariable("notice_no") int notice_no) { System.out.println("List"); List<Comment> commentList = cService.getCommentList(notice_no); System.out.println(notice_no); return commentList; } // 댓글 등록 @RequestMapping(value = "/listNotice/writeComment", method = RequestMethod.POST) @ResponseBody public int writeNoticeComment( @RequestParam("writer_number") int writer_number, Comment comment) { if (writer_number == 20001) { comment.setManager_number(writer_number); } else if (writer_number < 20001) { comment.setStudent_number(writer_number); } else { comment.setTeacher_number(writer_number); } System.out.println("댓글 등록"); System.out.println(comment); System.out.println(writer_number); System.out.println(comment.getVideo_no()); System.out.println(comment.getComment_number()); System.out.println(comment.getTeacher_name()); System.out.println(comment.getStudent_number()); return cService.writeNoticeComment(comment); } // 댓글 카운트 @RequestMapping(value = "/listNotice/countComment/{notice_no}") @ResponseBody public int getNoticeCountComment(@PathVariable("notice_no") int notice_no) { return cService.countNoticeComment(notice_no); } // 댓글 수정 @RequestMapping(value = "/listNotice/updateComment", method = RequestMethod.GET) @ResponseBody public int updateNoticeComment(Comment vo) { String comment_con = vo.getComment_con(); System.out.println(vo.getComment_con() + "dff"); System.out.println(vo.getComment_number() + "ddd"); int comment_number = vo.getComment_number(); return cService.updateNoticeComment(comment_con, comment_number); } // 댓글 삭제 @RequestMapping(value = "/listNotice/deleteComment/{comment_number}", method = RequestMethod.DELETE) @ResponseBody public int deleteVideoComment(@PathVariable("comment_number") int comment_number) { System.out.println(comment_number); return cService.deleteNoticeComment(comment_number); } // 비디오 댓글 리스트 @RequestMapping(value = "/listVideo/commentList/{video_no}", method = RequestMethod.GET) @ResponseBody public List<Comment> getCommentList(@PathVariable("video_no") int video_no) { System.out.println("List"); List<Comment> commentList = cService.getVideoCommentList(video_no); System.out.println(video_no); return commentList; } //비디오 댓글 등록 @RequestMapping(value = "/listVideo/writeComment", method = RequestMethod.POST) @ResponseBody public int writeVideoComment( @RequestParam("writer_number") int writer_number, Comment comment) { if (writer_number == 20001) { comment.setManager_number(writer_number); } else if (writer_number < 20001) { comment.setStudent_number(writer_number); } else { comment.setTeacher_number(writer_number); } System.out.println("댓글 등록"); System.out.println(comment); System.out.println(writer_number); System.out.println(comment.getVideo_no()); System.out.println(comment.getComment_number()); System.out.println(comment.getTeacher_name()); System.out.println(comment.getStudent_number()); return cService.writeVideoComment(comment); } //비디오 댓글 카운트 @RequestMapping(value = "/listVideo/countComment/{video_no}") @ResponseBody public int getVideoComment(@PathVariable("video_no") int video_no) { return cService.countVideoComment(video_no); } //비디오 댓글 수정 @RequestMapping(value = "/listVideo/updateComment", method = RequestMethod.GET) @ResponseBody public int updateStudentComment(Comment vo) { String comment_con = vo.getComment_con(); System.out.println(vo.getComment_con() + "dff"); System.out.println(vo.getComment_number() + "ddd"); int comment_number = vo.getComment_number(); return cService.updateVideoComment(comment_con, comment_number); } //비디오 댓글 삭제 @RequestMapping(value = "/listVideo/deleteComment/{comment_number}", method = RequestMethod.DELETE) @ResponseBody public int deleteStudentComment(@PathVariable("comment_number") int comment_number) { System.out.println(comment_number); return cService.deleteVideoComment(comment_number); } }
package ru.avokin.highlighting.impl; import ru.avokin.highlighting.CodeHighlighter; import java.awt.*; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * User: Andrey Vokin * Date: 06.10.2010 */ public abstract class AbstractCodeHighlighter implements CodeHighlighter { protected Map<String, Color> schema; protected AbstractCodeHighlighter() { Properties properties; try { properties = new Properties(); properties.load(AbstractCodeHighlighter.class.getResourceAsStream(getPropertyFilePath())); } catch (IOException e) { throw new RuntimeException("Couldn't initialize java plugin", e); } schema = new HashMap<String, Color>(); for (Object o : properties.keySet()) { String key = (String) o; String value = properties.getProperty(key); int[] rgb = getRGB(value); Color c = new Color(rgb[0], rgb[1], rgb[2]); schema.put(key, c); } } protected int[] getRGB(String s) { if (s.length() != 6) { throw new IllegalArgumentException("Invalid color RGB representation"); } return new int[] {Integer.parseInt(s.substring(0, 2), 16), Integer.parseInt(s.substring(2, 4), 16), Integer.parseInt(s.substring(4, 6), 16)}; } protected abstract String getPropertyFilePath(); }
package kr.co.hangsho.sliders.vo; public class Slider { }
package codemoi.exercices.fizzbuzz.nghesquier; public class FizzBuzz { public static void main(String[] args) { for (int i = 1; i <= 100; i++) { String output; if (i % 15 == 0) output = "FizzBuzz"; else if (i % 3 == 0) output = "Fizz"; else if (i % 5 == 0) output = "Buzz"; else output = String.valueOf(i); System.out.println(output); } } }
package me.ninabernick.cookingapplication.ShareRecipe; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.ImageButton; import android.widget.Toast; import com.facebook.share.model.SharePhoto; import com.facebook.share.model.SharePhotoContent; import com.facebook.share.widget.ShareDialog; import com.parse.FindCallback; import com.parse.ParseException; import com.parse.ParseFile; import com.parse.ParseQuery; import com.parse.ParseUser; import java.util.ArrayList; import java.util.List; import me.ninabernick.cookingapplication.R; import me.ninabernick.cookingapplication.RecipeDetailViewActivity; import me.ninabernick.cookingapplication.models.Recipe; import me.ninabernick.cookingapplication.models.SharedRecipe; import me.ninabernick.cookingapplication.profile.FriendImageAdapter; public class ShareRecipeDialog extends DialogFragment { private static final int SHARE_TO_FACEBOOK = 3201; private ParseUser user; private RecyclerView recycler_friends; private ImageButton fb_share; private ArrayList<String> friends = new ArrayList<>(); private ArrayList<String> savedRecipes; private ArrayList<ParseUser> friendUsers = new ArrayList<>(); private FriendImageAdapter adapter; FriendImageAdapter.FriendProfileListener friendListener = new FriendImageAdapter.FriendProfileListener() { @Override public void thumbnailClicked(ParseUser friend) { SharedRecipe recipe_to_be_shared = new SharedRecipe(); recipe_to_be_shared.setSharedUser(friend); recipe_to_be_shared.setSharingUser(ParseUser.getCurrentUser()); RecipeDetailViewActivity recipe_details = (RecipeDetailViewActivity) getActivity(); recipe_to_be_shared.setRecipe(recipe_details.getRecipeShown()); recipe_to_be_shared.saveInBackground(); dismiss(); Toast.makeText(getContext(), "Recipe Shared with " + friend.getString("name"), Toast.LENGTH_SHORT).show(); } }; public ShareRecipeDialog(){} @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_share_dialog, container); // Not exactly sure why, but this code is required to get the dialog to have rounded corners if (getDialog() != null && getDialog().getWindow() != null) { getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE); } user = ParseUser.getCurrentUser(); recycler_friends = (RecyclerView) view.findViewById(R.id.RecyclerView); //fb_share = (ImageButton) view.findViewById(R.id.fb_share); friends.clear(); friends.addAll(user.<String>getList("friends")); findFriends(); adapter = new FriendImageAdapter(friendUsers, friendListener); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); recycler_friends.setAdapter(adapter); LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false); recycler_friends.setLayoutManager(layoutManager); // fb_share.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // // RecipeDetailViewActivity recipeDetails = (RecipeDetailViewActivity) getActivity(); // // Recipe recipe = recipeDetails.getRecipeShown(); // // ParseFile parseFile = recipe.getParseFile("recipeImage"); // byte[] parse_data = new byte[0]; // try { // parse_data = parseFile.getData(); // } catch (ParseException e) { // e.printStackTrace(); // } // Bitmap image = BitmapFactory.decodeByteArray(parse_data, 0, parse_data.length); // SharePhoto photo = new SharePhoto.Builder() // .setBitmap(image) // .build(); // SharePhotoContent content = new SharePhotoContent.Builder() // .addPhoto(photo) // .build(); // // ShareDialog.show(getActivity(), content); // // dismiss(); // } // }); } // copied from profile fragment since retrieving friends is necessary here as well public void findFriends() { ParseQuery<ParseUser> query = ParseUser.getQuery(); query.whereContainedIn("name", friends); query.findInBackground(new FindCallback<ParseUser>() { public void done(List<ParseUser> objects, ParseException e) { if (e == null) { adapter.clear(); adapter.addAll(objects); adapter.notifyDataSetChanged(); } else { Log.d("friends", "query failed"); } } }); } }
package com.auro.scholr.home.presentation.view.fragment; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.res.Resources; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; import androidx.databinding.DataBindingUtil; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import androidx.lifecycle.ViewModelProviders; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.auro.scholr.R; import com.auro.scholr.core.application.AuroApp; import com.auro.scholr.core.application.base_component.BaseFragment; import com.auro.scholr.core.application.di.component.ViewModelFactory; import com.auro.scholr.core.common.AppConstant; import com.auro.scholr.core.common.CommonCallBackListner; import com.auro.scholr.core.common.CommonDataModel; import com.auro.scholr.core.database.AppPref; import com.auro.scholr.core.database.PrefModel; import com.auro.scholr.databinding.KycFragmentLayoutBinding; import com.auro.scholr.home.data.model.AssignmentReqModel; import com.auro.scholr.home.data.model.DashboardResModel; import com.auro.scholr.home.data.model.KYCDocumentDatamodel; import com.auro.scholr.home.presentation.view.activity.newDashboard.StudentMainDashboardActivity; import com.auro.scholr.home.presentation.view.adapter.KYCViewDocAdapter; import com.auro.scholr.home.presentation.viewmodel.KYCViewModel; import com.auro.scholr.payment.presentation.view.fragment.SendMoneyFragment; import com.auro.scholr.util.AppLogger; import com.auro.scholr.util.ConversionUtil; import com.auro.scholr.util.TextUtil; import com.auro.scholr.util.ViewUtil; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import static com.auro.scholr.core.common.Status.AZURE_API; public class KYCViewFragment extends BaseFragment implements View.OnClickListener , CommonCallBackListner { @Inject @Named("KYCViewFragment") ViewModelFactory viewModelFactory; KycFragmentLayoutBinding binding; KYCViewModel kycViewModel; KYCViewDocAdapter kycViewDocAdapter; private DashboardResModel dashboardResModel; ArrayList<KYCDocumentDatamodel> kycDocumentDatamodelArrayList; Resources resources; /*Face Image Params*/ List<AssignmentReqModel> faceModelList; int faceCounter = 0; @Override public void onAttach(Context context) { super.onAttach(context); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = DataBindingUtil.inflate(inflater, getLayout(), container, false); AuroApp.getAppComponent().doInjection(this); AuroApp.getAppContext().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); kycViewModel = ViewModelProviders.of(this, viewModelFactory).get(KYCViewModel.class); binding.setLifecycleOwner(this); setRetainInstance(true); AppLogger.v("newbranch","Step 1"); ViewUtil.setLanguageonUi(getActivity()); return binding.getRoot(); } public void setAdapter() { this.kycDocumentDatamodelArrayList = kycViewModel.homeUseCase.makeAdapterDocumentList(dashboardResModel); binding.documentUploadRecyclerview.setLayoutManager(new LinearLayoutManager(getActivity())); binding.documentUploadRecyclerview.setHasFixedSize(true); kycViewDocAdapter = new KYCViewDocAdapter(getActivity(), kycViewModel.homeUseCase.makeAdapterDocumentList(dashboardResModel)); binding.documentUploadRecyclerview.setAdapter(kycViewDocAdapter); } @Override protected void init() { if (getArguments() != null) { dashboardResModel = getArguments().getParcelable(AppConstant.DASHBOARD_RES_MODEL); } binding.btUploadAll.setVisibility(View.GONE); binding.btModifyAll.setVisibility(View.VISIBLE); setDataonFragment(); } private void setDataOnUi() { if (dashboardResModel != null) { if (!TextUtil.isEmpty(dashboardResModel.getWalletbalance())) { //binding.walletBalText.setText(getString(R.string.rs) + " " + dashboardResModel.getWalletbalance()); binding.walletBalText.setText(getString(R.string.rs) + " " + kycViewModel.homeUseCase.getWalletBalance(dashboardResModel)); } setDataStepsOfVerifications(); } PrefModel prefModel = AppPref.INSTANCE.getModelInstance(); if (prefModel.getUserLanguage().equalsIgnoreCase(AppConstant.LANGUAGE_EN)) { setLanguageText(AppConstant.HINDI); } else { setLanguageText(AppConstant.ENGLISH); } } private void setLanguageText(String text) { // binding.toolbarLayout.langEng.setText(text); } @Override protected void setToolbar() { /*Do code here*/ } @Override protected void setListener() { ((StudentMainDashboardActivity) getActivity()).setListingActiveFragment(StudentMainDashboardActivity.KYC_VIEW_FRAGMENT); /*Do code here*/ binding.btModifyAll.setOnClickListener(this); binding.walletInfo.setOnClickListener(this); if (kycViewModel != null && kycViewModel.serviceLiveData().hasObservers()) { kycViewModel.serviceLiveData().removeObservers(this); } else { observeServiceResponse(); } binding.backButton.setOnClickListener(this); // binding.swipeRefreshLayout.setOnRefreshListener(this); binding.swipeRefreshLayout.setEnabled(false); } @Override protected int getLayout() { return R.layout.kyc_fragment_layout; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); init(); } private void setDataonFragment() { setDataOnUi(); setToolbar(); setToolbar(); setListener(); setAdapter(); /*Check for face image is Exist Or Not*/ checkForFaceImage(); } private void checkForFaceImage() { PrefModel prefModel = AppPref.INSTANCE.getModelInstance(); if (prefModel != null && !TextUtil.checkListIsEmpty(prefModel.getListAzureImageList()) && prefModel.getListAzureImageList().size() > 0) { faceModelList = prefModel.getListAzureImageList(); if (faceModelList.get(0) != null) { // kycViewModel.sendAzureImageData(faceModelList.get(0)); } } } @Override public void onResume() { super.onResume(); } @Override public void onClick(View v) { if (v.getId() == R.id.bt_modify_all) { openKYCFragment(); } else if (v.getId() == R.id.lang_eng) { reloadFragment(); } else if (v.getId() == R.id.backButton) { AppLogger.v("newbranch","back button KycViewFragment button Step 1"); getActivity().onBackPressed(); AppLogger.e("handleback", "backlisner"); } else if (v.getId() == R.id.bt_transfer_money) { openSendMoneyFragment(); } else if (v.getId() == R.id.wallet_info) { openWalletInfoFragment(); } } public void openSendMoneyFragment() { // getActivity().getSupportFragmentManager().popBackStack(); Bundle bundle = new Bundle(); SendMoneyFragment sendMoneyFragment = new SendMoneyFragment(); bundle.putParcelable(AppConstant.DASHBOARD_RES_MODEL, dashboardResModel); sendMoneyFragment.setArguments(bundle); openFragment(sendMoneyFragment); } private void openTransactionFragment() { Bundle bundle = new Bundle(); bundle.putParcelable(AppConstant.DASHBOARD_RES_MODEL, dashboardResModel); TransactionsFragment fragment = new TransactionsFragment(); fragment.setArguments(bundle); openFragment(fragment); } public void callNumber() { Intent callIntent = new Intent(Intent.ACTION_DIAL); callIntent.setData(Uri.parse("tel:9667480783")); startActivity(callIntent); } private void reloadFragment() { FragmentTransaction ft = getFragmentManager().beginTransaction(); if (Build.VERSION.SDK_INT >= 26) { ft.setReorderingAllowed(false); } ft.detach(this).attach(this).commit(); } public void openKYCFragment() { dashboardResModel.setModify(true); Bundle bundle = new Bundle(); KYCFragment kycFragment = new KYCFragment(); bundle.putParcelable(AppConstant.DASHBOARD_RES_MODEL, dashboardResModel); kycFragment.setArguments(bundle); getActivity().getSupportFragmentManager().popBackStack(); openFragment(kycFragment); } private void openFragment(Fragment fragment) { getActivity().getSupportFragmentManager() .beginTransaction() .setReorderingAllowed(true) .replace(AuroApp.getFragmentContainerUiId(), fragment, KYCViewFragment.class .getSimpleName()) .addToBackStack(null) .commitAllowingStateLoss(); } @Override public void onDestroy() { super.onDestroy(); // CustomSnackBar.INSTANCE.dismissCartSnackbar(); } private void setDataStepsOfVerifications() { /* dashboardResModel.setIs_kyc_uploaded("Yes"); dashboardResModel.setIs_kyc_verified("Rejected"); dashboardResModel.setIs_payment_lastmonth("Yes");*/ // dashboardResModel.setIs_kyc_verified(AppConstant.DocumentType.YES); // dashboardResModel.setApproved_scholarship_money("50"); if (dashboardResModel.getIs_kyc_uploaded().equalsIgnoreCase(AppConstant.DocumentType.YES)) { binding.stepOne.tickSign.setVisibility(View.VISIBLE); binding.stepOne.textUploadDocumentMsg.setText(R.string.document_uploaded); binding.stepOne.textUploadDocumentMsg.setTextColor(AuroApp.getAppContext().getResources().getColor(R.color.ufo_green)); if (dashboardResModel.getIs_kyc_verified().equalsIgnoreCase(AppConstant.DocumentType.IN_PROCESS)) { binding.stepTwo.textVerifyMsg.setText(getString(R.string.verification_is_in_process)); binding.stepTwo.textVerifyMsg.setVisibility(View.VISIBLE); } else if (dashboardResModel.getIs_kyc_verified().equalsIgnoreCase(AppConstant.DocumentType.APPROVE)) { binding.stepTwo.textVerifyMsg.setText(R.string.document_verified); binding.stepTwo.textVerifyMsg.setVisibility(View.VISIBLE); binding.stepTwo.tickSign.setVisibility(View.VISIBLE); binding.btModifyAll.setVisibility(View.GONE); binding.stepTwo.textVerifyMsg.setTextColor(AuroApp.getAppContext().getResources().getColor(R.color.ufo_green)); int approvedMoney = ConversionUtil.INSTANCE.convertStringToInteger(dashboardResModel.getApproved_scholarship_money()); if (approvedMoney < 1) { /* binding.stepThree.tickSign.setVisibility(View.VISIBLE); binding.stepThree.textQuizVerifyMsg.setText(AuroApp.getAppContext().getResources().getString(R.string.scholarship_approved)); binding.stepFour.textTransferMsg.setText(R.string.successfully_transfered); binding.stepFour.textTransferMsg.setTextColor(AuroApp.getAppContext().getResources().getColor(R.color.ufo_green)); binding.stepFour.tickSign.setVisibility(View.GONE); binding.stepFour.textTransferMsg.setVisibility(View.VISIBLE); binding.stepFour.btTransferMoney.setVisibility(View.GONE);*/ } else { binding.stepThree.tickSign.setVisibility(View.VISIBLE); binding.stepThree.textQuizVerifyMsg.setText(AuroApp.getAppContext().getResources().getString(R.string.scholarship_approved)); binding.stepThree.textQuizVerifyMsg.setTextColor(AuroApp.getAppContext().getResources().getColor(R.color.ufo_green)); binding.stepFour.textTransferMsg.setTextColor(AuroApp.getAppContext().getResources().getColor(R.color.ufo_green)); binding.stepFour.textTransferMsg.setText(R.string.call_our_customercare); binding.stepFour.textTransferMsg.setVisibility(View.GONE); binding.stepFour.tickSign.setVisibility(View.VISIBLE); binding.stepFour.btTransferMoney.setVisibility(View.VISIBLE); binding.stepFour.btTransferMoney.setOnClickListener(this); } } else if (dashboardResModel.getIs_kyc_verified().equalsIgnoreCase(AppConstant.DocumentType.REJECTED)) { binding.stepTwo.textVerifyMsg.setText(R.string.declined); binding.stepTwo.textVerifyMsg.setTextColor(AuroApp.getAppContext().getResources().getColor(R.color.color_red)); binding.stepTwo.textVerifyMsg.setVisibility(View.VISIBLE); binding.stepTwo.tickSign.setVisibility(View.VISIBLE); binding.stepTwo.tickSign.setBackground(AuroApp.getAppContext().getResources().getDrawable(R.drawable.ic_cancel_icon)); binding.stepFour.textTransferMsg.setTextColor(ContextCompat.getColor(getActivity(), R.color.auro_dark_blue)); binding.stepFour.textTransferMsg.setText(R.string.you_will_see_transfer); binding.stepFour.btTransferMoney.setVisibility(View.GONE); binding.stepFour.tickSign.setVisibility(View.GONE); } else if (!TextUtil.isEmpty(dashboardResModel.getIs_kyc_verified()) && dashboardResModel.getIs_kyc_verified().equalsIgnoreCase(AppConstant.DocumentType.PENDING)) { AppLogger.e("chhonker step ", "kyc Step 7"); binding.stepTwo.textVerifyMsg.setText(getString(R.string.verification_pending)); binding.stepTwo.textVerifyMsg.setVisibility(View.VISIBLE); } } } private void observeServiceResponse() { kycViewModel.serviceLiveData().observeForever(responseApi -> { switch (responseApi.status) { case LOADING: /*Do handling in background*/ break; case SUCCESS: if (responseApi.apiTypeStatus == AZURE_API) { sendFaceImageOnServer(); } break; case NO_INTERNET: case AUTH_FAIL: case FAIL_400: default: updateFaceListInPref(); break; } }); } private void sendFaceImageOnServer() { if (!TextUtil.checkListIsEmpty(faceModelList)) { faceModelList.get(faceCounter).setUploaded(true); faceCounter++; if (faceModelList.size() > faceCounter) { // kycViewModel.sendAzureImageData(faceModelList.get(faceCounter)); } else { updateFaceListInPref(); } } } private void updateFaceListInPref() { PrefModel prefModel = AppPref.INSTANCE.getModelInstance(); if (prefModel != null) { List<AssignmentReqModel> newList = new ArrayList<>(); for (AssignmentReqModel model : faceModelList) { if (model != null && !model.isUploaded()) { newList.add(model); } } prefModel.setListAzureImageList(newList); AppPref.INSTANCE.setPref(prefModel); } } private void openWalletInfoFragment() { Bundle bundle = new Bundle(); bundle.putParcelable(AppConstant.DASHBOARD_RES_MODEL, dashboardResModel); WalletInfoDetailFragment fragment = new WalletInfoDetailFragment(); fragment.setArguments(bundle); openFragment(fragment); } /* @Override public void onRefresh() { AppLogger.e("chhonker--","onRefresh"); //((StudentMainDashboardActivity) getActivity()).setListner(this); // ((StudentMainDashboardActivity) getActivity()).callDashboardApi(); }*/ @Override public void commonEventListner(CommonDataModel commonDataModel) { switch (commonDataModel.getClickType()) { case LISTNER_SUCCESS: binding.swipeRefreshLayout.setRefreshing(false); handleNavigationProgress(1, ""); dashboardResModel = (DashboardResModel) commonDataModel.getObject(); dashboardResModel.setModify(true); ((StudentMainDashboardActivity) getActivity()).dashboardModel(dashboardResModel); if (checkKycStatus(dashboardResModel)) { ((StudentMainDashboardActivity) getActivity()).openKYCViewFragment(dashboardResModel); } else { ((StudentMainDashboardActivity) getActivity()). openKYCFragment(dashboardResModel); } setDataonFragment(); break; case LISTNER_FAIL: handleNavigationProgress(2, (String) commonDataModel.getObject()); break; } } public boolean checkKycStatus(DashboardResModel dashboardResModel) { if (dashboardResModel != null && !TextUtil.isEmpty(dashboardResModel.getPhoto()) && !TextUtil.isEmpty(dashboardResModel.getSchoolid()) && !TextUtil.isEmpty(dashboardResModel.getIdback()) && !TextUtil.isEmpty(dashboardResModel.getIdfront())) { return true; } return false; } private void handleNavigationProgress(int status, String msg) { if (status == 0) { binding.transparet.setVisibility(View.VISIBLE); binding.kycbackground.setVisibility(View.VISIBLE); binding.errorConstraint.setVisibility(View.GONE); } else if (status == 1) { binding.transparet.setVisibility(View.GONE); binding.kycbackground.setVisibility(View.VISIBLE); binding.errorConstraint.setVisibility(View.GONE); } else if (status == 2) { binding.transparet.setVisibility(View.GONE); binding.kycbackground.setVisibility(View.GONE); binding.errorConstraint.setVisibility(View.VISIBLE); binding.errorLayout.textError.setText(msg); binding.errorLayout.btRetry.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((StudentMainDashboardActivity) getActivity()).callDashboardApi(); } }); } } }
import java.util.Scanner; public class uniquequadruple { public static void main(String[] args) { int n; Scanner sc=new Scanner(System.in); n=sc.nextInt(); int arr[]=new int[n]; for(int i=0;i<n;i++) { arr[i]=sc.nextInt(); } int num=sc.nextInt(); for(int i=0;i<n-3;i++) { for(int j=i+1;j<n-2;j++) { for(int k=j+1;k<n-1;k++) { for(int l=k+1;l<n;l++) { if(arr[i]+arr[j]+arr[k]+arr[l]==num) { System.out.println(arr[i]+" "+arr[j]+" "+arr[k]+" "+arr[l]); } } } } } } }
package com.designpattern.dp6proxypattern.dynamicproxy.jdkdynamicproxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class JDKMedia implements InvocationHandler { // 保存被代理对象的引用 private Object target; // 获取代理对象 public Object getProxyInstance(Object target) throws Exception{ this.target = target; Class<?> clazz = target.getClass(); return Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this); } @Override public Object invoke(Object o, Method method, Object[] objects) throws Throwable { before(); Object obj = method.invoke(this.target, objects); after(); return obj; } private void before(){ System.out.println("增强前操作..."); } private void after(){ System.out.println("增强后操作..."); } }
/* * 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 classes.facade; import classes.HibernateUtil; import classes.model.Vesture; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; public class VestureFacade { public static void createVesture(Vesture vesture) { saveVesture(vesture); } public static Vesture findVestureById(Integer id) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = session.beginTransaction(); String hql = "from Vesture where id = :id"; Query select = session.createQuery(hql); select.setParameter("id", id); Vesture vesture = (Vesture) select.uniqueResult(); session.getTransaction().commit(); session.close(); return vesture; } public static List<Vesture> listVesture() { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = session.beginTransaction(); Query select = session.createQuery("from Vesture"); List<Vesture> vestures = select.list(); session.getTransaction().commit(); session.close(); return vestures; } public static void saveVesture(Vesture vesture) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = session.beginTransaction(); session.save(vesture); transaction.commit(); session.close(); } }
package de.varylab.discreteconformal.plugin; import static java.lang.Math.cosh; import static java.lang.Math.sinh; import org.junit.Assert; import org.junit.Test; public class HyperIdealVisualizationPluginTest extends Assert { @Test public void testGetEuclideanCircleFromHyperbolic_Centered() throws Exception { double[] center = {0.0, 0.0, 0.0, 1.0}; double radius = 1.0; double[] result = HyperIdealVisualizationPlugin.getEuclideanCircleFromHyperbolic(center, radius); assertEquals(0.0, result[0], 1E-12); assertEquals(0.0, result[1], 1E-12); assertEquals(sinh(1.0) / (cosh(1.0) + 1), result[2], 1E-12); } @Test public void testGetEuclideanCircleFromHyperbolic_OffCenter() throws Exception { double[] center = {sinh(1.0), 0.0, 0.0, cosh(1.0)}; double radius = 1.0; double[] result = HyperIdealVisualizationPlugin.getEuclideanCircleFromHyperbolic(center, radius); assertEquals(result[2], result[0], 1E-12); assertEquals(0.0, result[1], 1E-12); } }
package view; import dao.ConsultaFornecedor; import dao.ConsultaParcelasPagar; import entidades.Fornecedor; import entidades.ParcelasPagar; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import util.ComboBoxModelGenerico; public class FrmCadParcelasPagar extends javax.swing.JDialog { public ParcelasPagar entidade; // Passa para alterar public void entidadeTela() { tfDataCompra.setText(entidade.getDataCompra().toString()); tfDataVencimento.setText(entidade.getDataVencimento().toString()); tfDataPagamento.setText(entidade.getDataPagamento().toString()); cbFornecedor.setSelectedItem(entidade.getFornecedor().getNome()); } // Recebe public void telaEntidade() { System.out.println("" + tfDataPagamento.getText().trim().length()); if (tfDataPagamento.getText().trim().length() == 4) { entidade.setDataPagamento(null); } else { try { entidade.setDataPagamento(new SimpleDateFormat("dd/mm/yyyy").parse(tfDataPagamento.getText())); } catch (ParseException ex) { Logger.getLogger(FrmCadParcelasPagar.class.getName()).log(Level.SEVERE, null, ex); } } try { entidade.setDataCompra(new SimpleDateFormat("dd/mm/yyyy").parse(tfDataCompra.getText())); entidade.setDataVencimento(new SimpleDateFormat("dd/mm/yyyy").parse(tfDataVencimento.getText())); } catch (ParseException ex) { Logger.getLogger(FrmCadParcelasPagar.class.getName()).log(Level.SEVERE, null, ex); } entidade.setFornecedor((Fornecedor) cbFornecedor.getSelectedItem()); } public ParcelasPagar getEntidade() { return entidade; } public void setEntidade(ParcelasPagar entidade) { this.entidade = entidade; } private boolean valida() { boolean retorno = true; //System.out.println("tfNome.getText(): " + tfDataCompra.getText()); if (tfDataCompra.getText().trim().length() == 0) { msg.setText("(*) Campos obrigatorio!"); retorno = false; } if (tfDataVencimento.getText().trim().length() == 0) { msg.setText("(*) Campos obrigatorio!"); retorno = false; } if (!retorno) { JOptionPane.showMessageDialog(null, "Data invalida, formato dd/mm/aaaa"); } if (cbFornecedor.getSelectedItem() == null) { msg.setText("(*) Campos obrigatorio!"); retorno = false; } return retorno; //Validou } /** Creates new form FrmCadCor */ public FrmCadParcelasPagar(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); setLocationRelativeTo(null); tfDataCompra.requestFocus(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { ob = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); cbFornecedor = new javax.swing.JComboBox(); jButton3 = new javax.swing.JButton(); ob1 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); ob2 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); msg = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); tfDataCompra = new javax.swing.JFormattedTextField(); tfDataVencimento = new javax.swing.JFormattedTextField(); tfDataPagamento = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); ob.setForeground(java.awt.Color.red); ob.setText("(*)"); ob.setEnabled(false); jLabel2.setText("Forncedor:"); cbFornecedor.setModel(new ComboBoxModelGenerico(Fornecedor.class)); jButton3.setText("Novo"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); ob1.setForeground(java.awt.Color.red); ob1.setText("(*)"); ob1.setEnabled(false); jLabel3.setText("Data compra:"); ob2.setForeground(java.awt.Color.red); ob2.setText("(*)"); ob2.setEnabled(false); jLabel4.setText("Data vencimento:"); jLabel5.setText("Data pagamento:"); msg.setForeground(java.awt.Color.red); jButton1.setText("Ok"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("Cancelar"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); try { tfDataCompra.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } try { tfDataVencimento.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(ob1) .addComponent(ob)) .addComponent(ob2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(msg, javax.swing.GroupLayout.PREFERRED_SIZE, 259, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING)) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jButton3) .addGap(19, 19, 19)) .addGroup(layout.createSequentialGroup() .addGap(2, 2, 2) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(cbFornecedor, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(tfDataCompra, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tfDataVencimento, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tfDataPagamento, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 56, Short.MAX_VALUE)))))) .addGroup(layout.createSequentialGroup() .addComponent(jButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton2))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(17, 17, 17) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(ob) .addComponent(cbFornecedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(ob1) .addComponent(tfDataCompra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(40, 40, 40) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(ob2) .addComponent(tfDataVencimento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(tfDataPagamento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(msg, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton2) .addComponent(jButton1)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed if (valida()) { telaEntidade(); setVisible(false); } }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed entidade = null; setVisible(false); }//GEN-LAST:event_jButton2ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed ConsultaFornecedor con = new ConsultaFornecedor(); con.inserir(); cbFornecedor.setModel(new ComboBoxModelGenerico(Fornecedor.class)); }//GEN-LAST:event_jButton3ActionPerformed public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { FrmCadParcelasPagar dialog = new FrmCadParcelasPagar(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JComboBox cbFornecedor; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel msg; private javax.swing.JLabel ob; private javax.swing.JLabel ob1; private javax.swing.JLabel ob2; private javax.swing.JFormattedTextField tfDataCompra; private javax.swing.JTextField tfDataPagamento; private javax.swing.JFormattedTextField tfDataVencimento; // End of variables declaration//GEN-END:variables }
package com.standardchartered.crm.utility; public abstract class MenuOption { private int option; private String caption; public MenuOption(int option, String caption) { this.option = option; this.caption = caption; } public int getOption() { return option; } public void setOption(int option) { this.option = option; } public String getCaption() { return caption; } public void setCaption(String caption) { this.caption = caption; } public abstract void performAction(); @Override public String toString() { String result = "(" + this.option + ") " + this.caption; return result; } }
//package com.sshfortress.controller.system; // //import java.util.HashMap; //import java.util.List; //import java.util.Map; // //import javax.servlet.http.HttpServletRequest; //import javax.servlet.http.HttpServletResponse; // //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.stereotype.Controller; //import org.springframework.web.bind.annotation.RequestMapping; //import org.springframework.web.bind.annotation.RequestMethod; //import org.springframework.web.bind.annotation.ResponseBody; // //import com.sshfortress.common.beans.DabaseTable; //import com.sshfortress.common.util.Pager; //import com.sshfortress.dao.system.mapper.DabaseTableMapper; //import com.sshfortress.service.system.GeneratorCodeService; // //import io.swagger.annotations.ApiImplicitParam; //import io.swagger.annotations.ApiImplicitParams; //import io.swagger.annotations.ApiOperation; // //@Controller //@RequestMapping("generator") //public class GeneratorCodeWeb { // @Autowired // DabaseTableMapper dabaseTableMapper; // @Autowired // GeneratorCodeService generatorCodeService; // // @ApiOperation(value="数据库", notes="获取库中的表") // @RequestMapping(value= "/dabaseTableList" ,method=RequestMethod.GET) // @ResponseBody // public List<DabaseTable> userList(HttpServletRequest req, HttpServletResponse res, Pager page) { // Map<String,Object> map = new HashMap<String, Object>(); // map.put("page", page); // List<DabaseTable> list = dabaseTableMapper.queryByParamsListPager(map); // return list; // } // // @RequestMapping(value="/generatorCode" ,method=RequestMethod.GET) // @ResponseBody public Map<String, Object> generatorCode(Pager page) { // Map<String, Object> resultMap = new HashMap<String, Object>(); // Map<String,Object> map = new HashMap<String, Object>(); // map.put("page", page); // List<DabaseTable> list = dabaseTableMapper.queryByParamsListPager(map); // // resultMap.put("status", Integer.valueOf(200)); // resultMap.put("message", "生成成功"); // try { // generatorCodeService.generatorCode(list); // } catch (Exception e) { // e.printStackTrace(); // resultMap.put("status", Integer.valueOf(500)); // resultMap.put("message", "错误"); // } // return resultMap; // } // //}
package com.pinyougou.user.service.impl; import com.alibaba.dubbo.config.annotation.Service; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.pinyougou.mapper.TbItemMapper; import com.pinyougou.mapper.TbOrderItemMapper; import com.pinyougou.mapper.TbOrderMapper; import com.pinyougou.mapper.TbPayLogMapper; import com.pinyougou.pojo.*; import com.pinyougou.pojo.TbPayLogExample.Criteria; import com.pinyougou.user.service.PayLogService; import entity.OrderEntity; import entity.PageResult; import org.springframework.beans.factory.annotation.Autowired; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 服务实现层 * @author Administrator * */ @Service public class PayLogServiceImpl implements PayLogService { @Autowired private TbPayLogMapper payLogMapper; @Autowired private TbOrderMapper orderMapper; /** * 查询全部 */ @Override public List<TbPayLog> findAll() { return payLogMapper.selectByExample(null); } /** * 按分页查询 */ @Override public PageResult findPage(int pageNum, int pageSize) { PageHelper.startPage(pageNum, pageSize); Page<TbPayLog> page= (Page<TbPayLog>) payLogMapper.selectByExample(null); return new PageResult(page.getTotal(), page.getResult()); } /** * 增加 */ @Override public void add(TbPayLog payLog) { payLogMapper.insert(payLog); } /** * 修改 */ @Override public void update(TbPayLog payLog){ payLogMapper.updateByPrimaryKey(payLog); } /** * 根据ID获取实体 * @param id * @return */ @Override public TbPayLog findOne(Long id){ return payLogMapper.selectByPrimaryKey(id.toString()); } /** * 批量删除 */ @Override public void delete(Long[] ids) { for(Long id:ids){ payLogMapper.deleteByPrimaryKey(id.toString()); } } @Override public PageResult findPage(TbPayLog payLog, int pageNum, int pageSize) { PageHelper.startPage(pageNum, pageSize); TbPayLogExample example=new TbPayLogExample(); Criteria criteria = example.createCriteria(); if(payLog!=null){ if(payLog.getOutTradeNo()!=null && payLog.getOutTradeNo().length()>0){ criteria.andOutTradeNoLike("%"+payLog.getOutTradeNo()+"%"); } if(payLog.getUserId()!=null && payLog.getUserId().length()>0){ criteria.andUserIdLike("%"+payLog.getUserId()+"%"); } if(payLog.getTransactionId()!=null && payLog.getTransactionId().length()>0){ criteria.andTransactionIdLike("%"+payLog.getTransactionId()+"%"); } if(payLog.getTradeState()!=null && payLog.getTradeState().length()>0){ criteria.andTradeStateLike("%"+payLog.getTradeState()+"%"); } if(payLog.getOrderList()!=null && payLog.getOrderList().length()>0){ criteria.andOrderListLike("%"+payLog.getOrderList()+"%"); } if(payLog.getPayType()!=null && payLog.getPayType().length()>0){ criteria.andPayTypeLike("%"+payLog.getPayType()+"%"); } } Page<TbPayLog> page= (Page<TbPayLog>)payLogMapper.selectByExample(example); return new PageResult(page.getTotal(), page.getResult()); } @Autowired private TbOrderItemMapper orderItemMapper; @Autowired private TbItemMapper itemMapper; /** * * @param pageNum * @param pageSize * @param status * status 1,待付款 2,待发货 3,待收货 4,待评价 * 数据库 状态:1、未付款,2、已付款,3、未发货,4、已发货,5、交易成功,6、交易关闭,7、待评价 * @return */ public Map findOrderListfromPayLog(int pageNum, int pageSize, String status, String userId){ List<String> orderList = new ArrayList<>(); Map map = new HashMap<>(); List<OrderEntity> orderEntities = new ArrayList<>(); PageHelper.startPage(pageNum,pageSize); TbPayLogExample example = new TbPayLogExample(); Criteria criteria3 = example.createCriteria(); if ("1".equals(status)){ criteria3.andStatusEqualTo("1"); } if ("2".equals(status)){ List<String> list = new ArrayList<String>(); list.add("2"); list.add("3"); criteria3.andStatusIn(list); } if ("3".equals(status)){ criteria3.andStatusEqualTo("4"); } if ("4".equals(status)){ criteria3.andStatusEqualTo("7"); } criteria3.andUserIdEqualTo(userId); Page<TbPayLog> page= (Page<TbPayLog>) payLogMapper.selectByExample(example); List<TbPayLog> tbPayLogs = page.getResult(); long totalNumbers = page.getTotal(); long totalPages = totalNumbers%pageSize==0?totalNumbers/pageSize:totalNumbers/pageSize+1; map.put("totalPages",totalPages); map.put("currentPage",pageNum); for (TbPayLog tbPayLog : tbPayLogs) { String payLogOrderListIn = tbPayLog.getOrderList(); orderList.add(payLogOrderListIn); String orderIdsFromPayLog = tbPayLog.getOrderList(); if (orderIdsFromPayLog.contains(",")){ OrderEntity orderEntity = new OrderEntity(); List<TbOrder> orders = new ArrayList<>(); String[] orderIdsFromPayLogList = orderIdsFromPayLog.split(", "); for (String orderIdSingle : orderIdsFromPayLogList) { //订单(一个paylog对应多个订单) TbOrder orders1 = orderMapper.selectByPrimaryKey(Long.parseLong(orderIdSingle)); orders.add(orders1); //orderItems TbOrderItemExample orderItemExample = new TbOrderItemExample(); TbOrderItemExample.Criteria criteria1 = orderItemExample.createCriteria(); criteria1.andOrderIdEqualTo(Long.parseLong(orderIdSingle)); List<TbOrderItem> orderItems = orderItemMapper.selectByExample(orderItemExample); orders1.setOrderItems(orderItems); //spec for (TbOrderItem orderItem : orderItems) { TbItem tbItem = itemMapper.selectByPrimaryKey(orderItem.getItemId()); orderItem.setSpec(tbItem.getSpec()); } } orderEntity.setOrderList(orders); orderEntity.setPayLog(tbPayLog); orderEntities.add(orderEntity); }else{ OrderEntity orderEntity = new OrderEntity(); List<TbOrder> orders = new ArrayList<>(); TbOrder order = orderMapper.selectByPrimaryKey(Long.parseLong(orderIdsFromPayLog)); //orderItems TbOrderItemExample orderItemExample = new TbOrderItemExample(); TbOrderItemExample.Criteria criteria1 = orderItemExample.createCriteria(); criteria1.andOrderIdEqualTo(Long.parseLong(orderIdsFromPayLog)); List<TbOrderItem> orderItems = orderItemMapper.selectByExample(orderItemExample); order.setOrderItems(orderItems); orders.add(order); //spec for (TbOrderItem orderItem : orderItems) { TbItem tbItem = itemMapper.selectByPrimaryKey(orderItem.getItemId()); orderItem.setSpec(tbItem.getSpec()); } orderEntity.setOrderList(orders); orderEntity.setPayLog(tbPayLog); orderEntities.add(orderEntity); } } map.put("orderEntityList",orderEntities); return map; } @Override public OrderEntity findOrderListByOutTradeNo(String outTradeNo) { System.out.println("outTradeNo"+outTradeNo); TbPayLog tbPayLog = payLogMapper.selectByPrimaryKey(outTradeNo); String orderIdsFromPayLog = tbPayLog.getOrderList(); OrderEntity orderEntity = new OrderEntity(); if (orderIdsFromPayLog.contains(",")){ List<TbOrder> orders = new ArrayList<>(); String[] orderIdsFromPayLogList = orderIdsFromPayLog.split(", "); for (String orderIdSingle : orderIdsFromPayLogList) { //订单(一个paylog对应多个订单) TbOrderExample example2 = new TbOrderExample(); TbOrderExample.Criteria criteria = example2.createCriteria(); criteria.andOrderIdEqualTo(Long.valueOf(orderIdSingle)); List<TbOrder> orders1 = orderMapper.selectByExample(example2); orders.add(orders1.get(0)); //orderItems TbOrderItemExample orderItemExample = new TbOrderItemExample(); TbOrderItemExample.Criteria criteria1 = orderItemExample.createCriteria(); criteria1.andOrderIdEqualTo(Long.parseLong(orderIdSingle)); List<TbOrderItem> orderItems = orderItemMapper.selectByExample(orderItemExample); orders1.get(0).setOrderItems(orderItems); //spec for (TbOrderItem orderItem : orderItems) { TbItemExample itemExample = new TbItemExample(); TbItemExample.Criteria criteria2 = itemExample.createCriteria(); criteria2.andIdEqualTo(orderItem.getItemId()); List<TbItem> tbItems = itemMapper.selectByExample(itemExample); if (tbItems != null && tbItems.size() > 0){ orderItem.setSpec(tbItems.get(0).getSpec()); } } } orderEntity.setOrderList(orders); orderEntity.setPayLog(tbPayLog); }else{ TbOrderExample example3 = new TbOrderExample(); TbOrderExample.Criteria criteria = example3.createCriteria(); criteria.andOrderIdEqualTo(Long.parseLong(orderIdsFromPayLog)); List<TbOrder> orders1 = orderMapper.selectByExample(example3); //orderItems TbOrderItemExample orderItemExample = new TbOrderItemExample(); TbOrderItemExample.Criteria criteria1 = orderItemExample.createCriteria(); criteria1.andOrderIdEqualTo(Long.parseLong(orderIdsFromPayLog)); List<TbOrderItem> orderItems = orderItemMapper.selectByExample(orderItemExample); orders1.get(0).setOrderItems(orderItems); //spec for (TbOrderItem orderItem : orderItems) { TbItemExample itemExample = new TbItemExample(); TbItemExample.Criteria criteria2 = itemExample.createCriteria(); criteria2.andIdEqualTo(orderItem.getItemId()); List<TbItem> tbItems = itemMapper.selectByExample(itemExample); if (tbItems != null && tbItems.size() > 0){ System.out.println("================="); orderItem.setSpec(tbItems.get(0).getSpec()); System.out.println(tbItems.get(0).getSpec()); } } orderEntity.setOrderList(orders1); orderEntity.setPayLog(tbPayLog); System.out.println("payLog的totalFee"+tbPayLog.getTotalFee()); } return orderEntity; } @Override public String findTotalFeeByOutTradeNo(String out_trade_no) { TbPayLog payLog = payLogMapper.selectByPrimaryKey(out_trade_no); return payLog.getTotalFee()+""; } }
package slimeknights.tconstruct.smeltery.block; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import java.util.Random; import javax.annotation.Nonnull; import slimeknights.tconstruct.library.TinkerRegistry; import slimeknights.tconstruct.smeltery.tileentity.TileSmeltery; public class BlockSmelteryController extends BlockMultiblockController { public BlockSmelteryController() { super(Material.ROCK); this.setCreativeTab(TinkerRegistry.tabSmeltery); this.setHardness(3F); this.setResistance(20F); this.setSoundType(SoundType.METAL); } @Nonnull @Override public TileEntity createNewTileEntity(@Nonnull World worldIn, int meta) { return new TileSmeltery(); } @Override public void randomDisplayTick(IBlockState state, World world, BlockPos pos, Random rand) { if(isActive(world, pos)) { EnumFacing enumfacing = state.getValue(FACING); double d0 = (double) pos.getX() + 0.5D; double d1 = (double) pos.getY() + 0.5D + (rand.nextFloat() * 6F) / 16F; double d2 = (double) pos.getZ() + 0.5D; double d3 = 0.52D; double d4 = rand.nextDouble() * 0.6D - 0.3D; spawnFireParticles(world, enumfacing, d0, d1, d2, d3, d4); } } }
package com.plivo.sdk.response.message; import java.util.List; import com.google.gson.annotations.SerializedName; public class MessageList { public MessageMeta meta ; @SerializedName("api_id") public String apiID ; @SerializedName("objects") public List<Message> messageList ; public String error; public MessageList() { // empty } }
public class sort { public static void quickSort(int[] nums,int start,int end) { int i = start; int j = end; int key = nums[i]; while(i<j){ while(nums[j]>key){ j--; } swap(nums,i,j); i++; while(nums[i]<key){ i++; } swap(nums,i,j); j--; } quickSort(nums,start,i); quickSort(nums,i+1,end); } private static void swap(int[] nums,int i,int j){ int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } public static void main(String[] args){ int[] array = {3,4,2,1,9,8,7}; String s = "asd"; System.out.println(); } }
package com.example.moviedb.fragment; import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.databinding.DataBindingUtil; import androidx.fragment.app.Fragment; import androidx.lifecycle.LifecycleOwner; import androidx.lifecycle.ViewModelProvider; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.moviedb.activity.DetailActivity; import com.example.moviedb.adapter.MovieAdapter; import com.example.moviedb.OnMovieListener; import com.example.moviedb.R; import com.example.moviedb.databinding.FragmentPopularBinding; import com.example.moviedb.model.MovieResponse; import com.example.moviedb.model.SearchResponse; import com.example.moviedb.viewmodel.PoPularViewModel; public class PopularFragment extends Fragment implements OnMovieListener { private PoPularViewModel poPularViewModel; private MovieAdapter adapter; private FragmentPopularBinding fragmentPopularBinding; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { fragmentPopularBinding = DataBindingUtil.inflate(inflater,R.layout.fragment_popular,container,false); return fragmentPopularBinding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); adapter = new MovieAdapter(requireContext()); adapter.setOnMovieListener(this); poPularViewModel = new ViewModelProvider(this).get(PoPularViewModel.class); fragmentPopularBinding.recyclerviewPopular.setAdapter(adapter); poPularViewModel.getPopular().observe((LifecycleOwner) getContext(), o -> { if( o == null ) return; adapter.setMovieResponse((MovieResponse) o); }); poPularViewModel.fetchPopular(); } @Override public void onMovieClick(MovieResponse.Movie movie) { Intent intent = new Intent(getContext(), DetailActivity.class); intent.putExtra("movie_id", movie.getId()); startActivity(intent); } @Override public void onSearchKeyword(SearchResponse.Result result) { } }
/* * * using setScale(number of decimals, rounding mode) making decimal number rounded. * */ package BigNumber; import java.math.BigDecimal; import java.math.RoundingMode; /** * * @author YNZ */ public class BigNumberRounding { public static void main(String[] args) { BigDecimal bd = new BigDecimal(String.valueOf(12.346377545)).setScale(5, RoundingMode.HALF_UP); System.out.println("" + bd); } }
package com.classicphoto.rpmfordriver; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.LinearLayout; import com.classicphoto.rpmfordriver.R; import com.edmodo.cropper.CropImageView; import java.io.File; public class CropActivity extends AppCompatActivity { CropImageView cropImageView; static Bitmap croppedImage; String pictuerPath; int i = 0; LinearLayout adContainer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_crop); getSupportActionBar().setDisplayHomeAsUpEnabled(true); setTitle("Crop Photo"); cropImageView = (CropImageView) findViewById(R.id.CropImageView); Intent getIntent = getIntent(); pictuerPath = getIntent.getStringExtra("pictuerPath"); File imagePath = new File(pictuerPath); if (imagePath.exists()) { Bitmap imageBitmap = BitmapFactory.decodeFile(imagePath.getAbsolutePath()); cropImageView.setImageBitmap(imageBitmap); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_crop, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem menuItem) { switch (menuItem.getItemId()) { case android.R.id.home: onBackPressed(); finish(); return true; case R.id.Crop: croppedImage = cropImageView.getCroppedImage(); // Intent returnIntent = new Intent(); // returnIntent.putExtra("data", croppedImage); // setResult(Activity.RESULT_OK, returnIntent); // finish(); onBackPressed(); // Intent intent = new Intent(CropActivity.this, DeliveryActivity.class); // startActivity(intent); // finish(); // overridePendingTransition(0, 0); return true; default: return super.onOptionsItemSelected(menuItem); } } }
package com.peregudova.multinote.requests; public class GetAllNotesCommand extends Command{ public GetAllNotesCommand(String token, String user) { super("getallnotes", token, user); } }
package bis.project.validators; import bis.project.model.BankOrder; public class BankOrderValidator { public static void Validate(BankOrder bankOrder) throws ValidationException{ ValidationException.ThrowIfNullOrEmpty(bankOrder.getBankOrderDate(),"Bank order date"); ValidationException.ThrowIfNullOrEmpty(bankOrder.getDirection(),"Direction"); ValidationException.ThrowIfNullOrEmpty(bankOrder.getAmount(),"Amount"); ValidationException.ThrowIfNullOrEmpty(bankOrder.getCurrencyDate(),"Current date"); ValidationException.ThrowIfNullOrEmpty(bankOrder.getDebtor(),"Debtor"); ValidationException.ThrowIfNullOrEmpty(bankOrder.getFirstAccount(),"First account"); ValidationException.ThrowIfNullOrEmpty(bankOrder.getFirstModel(),"First model"); ValidationException.ThrowIfNullOrEmpty(bankOrder.getFirstNumber(),"First number"); ValidationException.ThrowIfNullOrEmpty(bankOrder.getSecondAccount(),"Second account"); ValidationException.ThrowIfNullOrEmpty(bankOrder.getSecondModel(),"Second model"); ValidationException.ThrowIfNullOrEmpty(bankOrder.getSecondNumber(),"Second number"); ValidationException.ThrowIfNullOrEmpty(bankOrder.getOrderDate(),"Order date"); ValidationException.ThrowIfNullOrEmpty(bankOrder.getPurposeOfPayment(),"Purpose of payment"); ValidationException.ThrowIfNullOrEmpty(bankOrder.getRecipient(),"Recipient"); ValidationException.ThrowIfNullOrEmpty(bankOrder.getDailyAccountBalance(),"Daily account balance"); ValidationException.ThrowIfLengthGratherThan(255, bankOrder.getDebtor(),"Debtor"); ValidationException.ThrowIfLengthGratherThan(255, bankOrder.getPurposeOfPayment(),"Purpose of payment"); ValidationException.ThrowIfLengthGratherThan(255, bankOrder.getRecipient(),"Recipient"); ValidationException.ThrowIfLengthDifferentThat(18, bankOrder.getFirstAccount(),"First Account"); ValidationException.ThrowIfLengthGratherThan(2, bankOrder.getFirstModel(),"First Model"); ValidationException.ThrowIfLengthGratherThan(22, bankOrder.getFirstNumber(),"First Number"); ValidationException.ThrowIfLengthDifferentThat(18, bankOrder.getSecondAccount(),"Second Account"); ValidationException.ThrowIfLengthGratherThan(2, bankOrder.getSecondModel(),"Second Model"); ValidationException.ThrowIfLengthGratherThan(18, bankOrder.getSecondNumber(),"Second Number"); } }
package com.example.testproject.startup; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.Button; import android.widget.FrameLayout; import android.widget.LinearLayout; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.RecyclerView; import androidx.viewpager2.adapter.FragmentStateAdapter; import androidx.viewpager2.widget.ViewPager2; import com.example.testproject.R; import com.example.testproject.registration.RegisterActivity; import com.example.testproject.startup.adapter.ScreenSlidePagerAdapter; import com.example.testproject.utils.ZoomOutPageTransformer; import me.relex.circleindicator.CircleIndicator3; public class StartupActivity extends AppCompatActivity { private boolean showSplash = true; private FrameLayout splashLayout; private ViewPager2 viewPager; private LinearLayout skipLayout; private Button btnNext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_startup); initView(); if (showSplash) { splashLayout.setVisibility(View.VISIBLE); showSplash = false; new Handler().postDelayed(() -> splashLayout.setVisibility(View.GONE), 1500); } FragmentStateAdapter pagerAdapter = new ScreenSlidePagerAdapter(this); viewPager.setAdapter(pagerAdapter); ((RecyclerView) viewPager.getChildAt(0)).setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER); CircleIndicator3 indicator = findViewById(R.id.indicator); indicator.setViewPager(viewPager); viewPager.setPageTransformer(new ZoomOutPageTransformer()); skipLayout.setOnClickListener(v -> skipStartUp()); btnNext.setOnClickListener(v -> { if (viewPager.getCurrentItem() == 2) { skipStartUp(); } else { viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true); } }); } private void skipStartUp() { if (btnNext.isEnabled()) { startActivity(new Intent(this, RegisterActivity.class)); } btnNext.setEnabled(false); } private void initView() { splashLayout = findViewById(R.id.slash_layout); skipLayout = findViewById(R.id.skip_layout); btnNext = findViewById(R.id.btn_next); viewPager = findViewById(R.id.pager); } @Override protected void onResume() { super.onResume(); btnNext.setEnabled(true); } @Override public void onBackPressed() { if (viewPager.getCurrentItem() == 0) { super.onBackPressed(); } else { viewPager.setCurrentItem(viewPager.getCurrentItem() - 1); } } }
import com.bridgelabz.censusAnalyser.censusDAO.CensusAnalyserDAO; import com.bridgelabz.censusAnalyser.censusDTO.IndianStateCensusData; import com.bridgelabz.censusAnalyser.censusDTO.StateCodePOJO; import com.bridgelabz.censusAnalyser.exception.CensusAnalyserException; import com.bridgelabz.censusAnalyser.service.CensusAnalyserMain; import com.google.gson.Gson; import org.junit.Assert; import org.junit.Test; public class CensusAnalyserMainTest { //Constant private static final String STATE_CENSUS_DATA_CSV_FILE_PATH = "./src/test/resources/StateCensusData.csv"; private static final String STATE_CENSUS_DATA_CSV_FILE_INCORRECT_PATH = "./src/test/resources/StateCensus.csv"; private static final String STATE_CENSUS_DATA_CSV_INCORRECT_FILE_TYPE = "./src/test/resources/StateCensusData.cs"; private static final String STATE_CENSUS_DATA_CSV_INCORRECT_DELIMITER_FILE_TYPE = "./src/test/resources/StateCensusDataEror.csv"; private static final String STATE_CENSUS_DATA_CSV_INCORRECT_HEADER_FILE = "./src/test/resources/StateCensusDataErorType.csv"; private static final String STATE_CODE_DATA_CSV_FILE_PATH = "./src/test/resources/StateCo.csv"; private static final String STATE_CODE_DATA_CSV_FILE_INCORRECT_PATH = "./src/test/resources/State.csv"; private static final String STATE_CODE_DATA_CSV_FILE_INCORRECT_TYPE = "./src/test/resources/StateCo.cs"; private static final String STATE_CODE_DATA_CSV_FILE_INCORRECT_DELIMITER = "./src/test/resources/StateCodeIncorectDelimiter.csv"; private static final String STATE_CODE_DATA_CSV_FILE_INCORRECT_HEADER = "./src/test/resources/StateCensusDataErorType.csv"; private static final String US_CODE_DATA_CSV_FILE = "./src/test/resources/USCensusData.csv"; // Create main method Class object CensusAnalyserMain censusAnalyserIndia = new CensusAnalyserMain(CensusAnalyserMain.COUNTRY.INDIA); CensusAnalyserMain censusAnalyserUS = new CensusAnalyserMain(CensusAnalyserMain.COUNTRY.US); @Test public void givenRecordInCSVFile_WhenNumberOfRecordMatch_ThenTrue() throws Exception { CensusAnalyserMain censusAnalyserMain = new CensusAnalyserMain(CensusAnalyserMain.COUNTRY.INDIA); int record=censusAnalyserMain.loadCensusData(STATE_CENSUS_DATA_CSV_FILE_PATH); Assert.assertEquals( 29,record); } @Test public void givenStateCensusCSVFile_WhenIncorrectFileName_ThenCustomException() throws Exception { try { censusAnalyserIndia.loadCensusData(STATE_CENSUS_DATA_CSV_FILE_INCORRECT_PATH); }catch (CensusAnalyserException e) { Assert.assertEquals(CensusAnalyserException.MyException_Type.FILE_NOT_FOUND,e.type); } } @Test public void givenCSVFile_WhenIncorrectTypeMatch_ThenTrue() throws Exception { try{ censusAnalyserIndia.loadCensusData(STATE_CENSUS_DATA_CSV_INCORRECT_FILE_TYPE); }catch (CensusAnalyserException e) { Assert.assertEquals(CensusAnalyserException.MyException_Type.FILE_NOT_FOUND,e.type); } } @Test public void givenCSVFile_WhenIncorrectDelimiter_ThenTrue() throws Exception { try{ censusAnalyserIndia.loadCensusData(STATE_CENSUS_DATA_CSV_INCORRECT_DELIMITER_FILE_TYPE); }catch (CensusAnalyserException e) { Assert.assertEquals(CensusAnalyserException.MyException_Type.DELIMITER_INCORECT,e.type); } } @Test public void givenCSVFile_WhenIncorrectHeader_ThenTrue() throws Exception { try{ censusAnalyserIndia.loadCensusData(STATE_CENSUS_DATA_CSV_INCORRECT_HEADER_FILE); }catch (CensusAnalyserException e) { Assert.assertEquals(CensusAnalyserException.MyException_Type.DELIMITER_INCORECT,e.type); } } @Test public void givenCheckWithStateCodeCSV_WhenNumberOfRecordMatches_ThenTrue() throws Exception { int stateCensusDataRecords = censusAnalyserIndia.loadCensusData(STATE_CENSUS_DATA_CSV_FILE_PATH,STATE_CODE_DATA_CSV_FILE_PATH); Assert.assertEquals(29,stateCensusDataRecords); } @Test public void givenStateCodeCSVFile_WhenIncorrectFileName_ThenCustomException() { try { censusAnalyserIndia.loadCensusData(STATE_CODE_DATA_CSV_FILE_INCORRECT_PATH); }catch (CensusAnalyserException e) { Assert.assertEquals(CensusAnalyserException.MyException_Type.FILE_NOT_FOUND,e.type); } } @Test public void givenStateCodeCSVFile_WhenIncorrectTypeMatch_ThenTrue() throws Exception { try{ censusAnalyserIndia.loadCensusData(STATE_CODE_DATA_CSV_FILE_INCORRECT_TYPE); }catch (CensusAnalyserException e) { Assert.assertEquals(CensusAnalyserException.MyException_Type.FILE_NOT_FOUND,e.type); } } @Test public void givenStateCodeeCSVFile_WhenIncorrectDelimiter_ThenTrue() throws Exception { try{ censusAnalyserIndia.loadCensusData(STATE_CODE_DATA_CSV_FILE_INCORRECT_DELIMITER); }catch (CensusAnalyserException e) { Assert.assertEquals(CensusAnalyserException.MyException_Type.DELIMITER_INCORECT,e.type); } } @Test public void givenStateCodeCSVFile_WhenIncorrectHeader_ThenTrue() throws Exception { try{ censusAnalyserIndia.loadCensusData(STATE_CODE_DATA_CSV_FILE_INCORRECT_HEADER); }catch (CensusAnalyserException e) { Assert.assertEquals(CensusAnalyserException.MyException_Type.DELIMITER_INCORECT,e.type); } } @Test public void givenStateCensusData_WhenStateWiseSort_ThenReturn() { try{ censusAnalyserIndia.loadCensusData(STATE_CENSUS_DATA_CSV_FILE_PATH); String sortedStateList = censusAnalyserIndia.getSortCensusData(CensusAnalyserMain.SORTING_MODE.STATE); IndianStateCensusData sortedStateArray[] = new Gson().fromJson(sortedStateList,IndianStateCensusData[].class); Assert.assertEquals("Andhra Pradesh",sortedStateArray[0].state); } catch(Exception e){ e.printStackTrace(); } } @Test public void givenStateCodeData_WhenStateCodeWiseSort_ThenReturn() { try{ censusAnalyserIndia.loadCensusData(STATE_CODE_DATA_CSV_FILE_PATH); String sortedStateCodeData = censusAnalyserIndia.getSortCensusData (CensusAnalyserMain.SORTING_MODE.STATECODE); StateCodePOJO sortedStateCodeArray[] = new Gson().fromJson(sortedStateCodeData,StateCodePOJO[].class); Assert.assertEquals("AD",sortedStateCodeArray[0].stateCode); } catch(Exception e){ e.printStackTrace(); } } @Test public void givenStateCensusData_WhenPopulationWiseSort_ThenReturn() { try{ censusAnalyserIndia.loadCensusData(STATE_CENSUS_DATA_CSV_FILE_PATH); String sortedStateList = censusAnalyserIndia.getSortCensusData(CensusAnalyserMain.SORTING_MODE.POPULATION); CensusAnalyserDAO sortedPopulationArray[] = new Gson().fromJson(sortedStateList,CensusAnalyserDAO[].class); Assert.assertEquals(199812341,sortedPopulationArray[0].population); } catch(Exception e){ e.printStackTrace(); } } @Test public void givenTheStateCensusData_WhenSortedOnDensityPerSqKm_ShouldReturnSortedResult() { try { censusAnalyserIndia.loadCensusData(STATE_CENSUS_DATA_CSV_FILE_PATH); String sortedCensusData = censusAnalyserIndia.getSortCensusData(CensusAnalyserMain.SORTING_MODE.DENSITY); CensusAnalyserDAO sortedDensityPerSqKmArray[] = new Gson(). fromJson(sortedCensusData,CensusAnalyserDAO[].class); Assert.assertEquals(1102,sortedDensityPerSqKmArray[0].density); } catch (Exception e) { e.printStackTrace(); } } @Test public void givenStateCensusData_WhenSortedOnAreaInPerSqKm_ThenReturnSortedData() { try { censusAnalyserIndia.loadCensusData(STATE_CENSUS_DATA_CSV_FILE_PATH); String sortedCensusData = censusAnalyserIndia.getSortCensusData(CensusAnalyserMain.SORTING_MODE.AREA); CensusAnalyserDAO csvStateAreaCensuses[] = new Gson().fromJson(sortedCensusData, CensusAnalyserDAO[].class); Assert.assertEquals(342239, csvStateAreaCensuses[0].area); } catch ( Exception e) { e.printStackTrace(); } } @Test public void givenTheUSStateCensusData_WhenSortedOnPopulation_ShouldReturnSortedResult() { try { censusAnalyserUS.loadCensusData(US_CODE_DATA_CSV_FILE); String sortedStateList = censusAnalyserUS.getSortCensusData(CensusAnalyserMain.SORTING_MODE.POPULATION); CensusAnalyserDAO csvStateAreaCensuses[] = new Gson().fromJson(sortedStateList, CensusAnalyserDAO[].class); Assert.assertEquals("California", csvStateAreaCensuses[0].state); } catch (Exception e) { e.getStackTrace(); } } @Test public void givenTheUSStateCensusData_WhenSortedOnDensity_ShouldReturnSortedResult() { try { censusAnalyserUS.loadCensusData(US_CODE_DATA_CSV_FILE); String sortedStateList = censusAnalyserUS.getSortCensusData(CensusAnalyserMain.SORTING_MODE.DENSITY); CensusAnalyserDAO csvStateAreaCensuses[] = new Gson().fromJson(sortedStateList, CensusAnalyserDAO[].class); Assert.assertEquals("District of Columbia", csvStateAreaCensuses[0].state); } catch (Exception e) { e.getStackTrace(); } } @Test public void givenTheUSStateCensusData_WhenSortedOnStateArea_ShouldReturnSortedResult() { try { censusAnalyserUS.loadCensusData(US_CODE_DATA_CSV_FILE); String sortedStateList = censusAnalyserUS.getSortCensusData(CensusAnalyserMain.SORTING_MODE.AREA); CensusAnalyserDAO csvStateAreaCensuses[] = new Gson().fromJson(sortedStateList, CensusAnalyserDAO[].class); Assert.assertEquals("Alaska", csvStateAreaCensuses[0].state); } catch (Exception e) { e.getStackTrace(); } } @Test public void givenUSAndIndiaStateCensusData_WhenSortedPopulationAndDensity_ShouldReturnSortedList_2() { try { censusAnalyserUS.loadCensusData(US_CODE_DATA_CSV_FILE); String sortedStateList = censusAnalyserUS.getSortCensusData(CensusAnalyserMain.SORTING_MODE.POPULATION); CensusAnalyserDAO csvStateAreaCensuses[] = new Gson().fromJson(sortedStateList, CensusAnalyserDAO[].class); censusAnalyserIndia.loadCensusData(STATE_CENSUS_DATA_CSV_FILE_PATH); String sortedCensusData = censusAnalyserIndia.getSortCensusData(CensusAnalyserMain.SORTING_MODE.POPULATION); CensusAnalyserDAO densityPerSqKmArray[] = new Gson().fromJson(sortedCensusData,CensusAnalyserDAO[].class); Assert.assertEquals(true, (String.valueOf(densityPerSqKmArray[0].density)). compareToIgnoreCase(String.valueOf(csvStateAreaCensuses[0].density)) < 0); } catch (Exception e) { e.printStackTrace(); } } }
package com.lenovohit.hcp.base.dao.impl; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import com.alibaba.fastjson.TypeReference; import com.lenovohit.core.utils.JSONUtils; import com.lenovohit.hcp.base.dao.HcpRestClientDao; import com.lenovohit.hcp.base.model.HcpUser; import com.lenovohit.hcp.base.transfer.RestEntityResponse; import com.lenovohit.hcp.base.transfer.RestListResponse; import com.lenovohit.hcp.base.transfer.RestResponse; public class HcpRestClientDaoImpl implements HcpRestClientDao{ private RestTemplate restTemplate = new RestTemplate(); /*********************************************GET*************************************************/ public <T> RestEntityResponse<T> getForEntity(String url, Class<T> responseType, Object... urlVariables) { String text = restTemplate.getForObject(url, String.class, urlVariables); @SuppressWarnings("unchecked") RestEntityResponse<T> response = JSONUtils.deserialize(text, RestEntityResponse.class); if(!response.isSuccess())return response; String content = response.getResult(); T t = JSONUtils.parseObject(content,responseType); response.setEntity(t); return response; } public <T> RestListResponse<T> getForList(String url, Class<T> responseType, Object... urlVariables) { String text = restTemplate.getForObject(url, String.class, urlVariables); @SuppressWarnings("unchecked") RestListResponse<T> response = JSONUtils.deserialize(text, RestListResponse.class); if(!response.isSuccess())return response; String content = response.getResult(); List<String> list = JSONUtils.parseObject(content,new TypeReference<List<String>>(){}); List<T> result = new ArrayList<T>(); for(String str : list ){ System.out.println(str); T t = JSONUtils.parseObject(str,responseType); result.add(t); } response.setList(result); return response; } public <T> RestResponse getForResponse(String url,Object... urlVariables) { String response = restTemplate.getForObject(url, String.class, urlVariables); RestResponse reponse = JSONUtils.deserialize(response, RestResponse.class); return reponse; } public <T> RestEntityResponse<T> getForEntity(String url, Class<T> responseType,Map<String, ?> urlVariables) { String text = restTemplate.getForObject(url, String.class, urlVariables); @SuppressWarnings("unchecked") RestEntityResponse<T> response = JSONUtils.deserialize(text, RestEntityResponse.class); if(!response.isSuccess())return response; String content = response.getResult(); T t = JSONUtils.parseObject(content,responseType); response.setEntity(t); return response; } public <T> RestListResponse<T> getForList(String url, Class<T> responseType, Map<String, ?> urlVariables) { String text = restTemplate.getForObject(url, String.class, urlVariables); @SuppressWarnings("unchecked") RestListResponse<T> response = JSONUtils.deserialize(text, RestListResponse.class); if(!response.isSuccess())return response; String content = response.getResult(); List<String> list = JSONUtils.parseObject(content,new TypeReference<List<String>>(){}); List<T> result = new ArrayList<T>(); for(String str : list ){ System.out.println(str); T t = JSONUtils.parseObject(str,responseType); result.add(t); } response.setList(result); return response; } public <T> RestResponse getForResponse(String url,Map<String, ?> urlVariables) { String response = restTemplate.getForObject(url, String.class, urlVariables); RestResponse reponse = JSONUtils.deserialize(response, RestResponse.class); return reponse; } /*********************************************POST*************************************************/ public <T> RestEntityResponse<T> postForEntity(String url, Object request, Class<T> responseType, Object... uriVariables) { String text = restTemplate.postForObject(url, request, String.class,uriVariables); @SuppressWarnings("unchecked") RestEntityResponse<T> response = JSONUtils.deserialize(text, RestEntityResponse.class); if(!response.isSuccess())return response; String content = response.getResult(); T t = JSONUtils.parseObject(content,responseType); response.setEntity(t); return response; } public <T> RestListResponse<T> postForList(String url, Object request, Class<T> responseType, Object... uriVariables) { String text = restTemplate.postForObject(url, request, String.class,uriVariables); @SuppressWarnings("unchecked") RestListResponse<T> response = JSONUtils.deserialize(text, RestListResponse.class); if(!response.isSuccess())return response; String content = response.getResult(); List<String> list = JSONUtils.parseObject(content,new TypeReference<List<String>>(){}); List<T> result = new ArrayList<T>(); for(String str : list ){ System.out.println(str); T t = JSONUtils.parseObject(str,responseType); result.add(t); } response.setList(result); return response; } public <T> RestResponse postForResponse(String url, Object request, Class<T> responseType, Object... uriVariables) { String response = restTemplate.postForObject(url, request, String.class,uriVariables); RestResponse reponse = JSONUtils.deserialize(response, RestResponse.class); return reponse; } /*********************************************PUT*************************************************/ public <T> RestEntityResponse<T> putForEntity(String url, Object request, Class<T> responseType, Object... uriVariables) { String text = putForString(url, request,uriVariables); @SuppressWarnings("unchecked") RestEntityResponse<T> response = JSONUtils.deserialize(text, RestEntityResponse.class); if(!response.isSuccess())return response; String content = response.getResult(); T t = JSONUtils.parseObject(content,responseType); response.setEntity(t); return response; } public <T> RestListResponse<T> putForList(String url, Object request, Class<T> responseType, Object... uriVariables) { String text = putForString(url, request,uriVariables); @SuppressWarnings("unchecked") RestListResponse<T> response = JSONUtils.deserialize(text, RestListResponse.class); if(!response.isSuccess())return response; String content = response.getResult(); List<String> list = JSONUtils.parseObject(content,new TypeReference<List<String>>(){}); List<T> result = new ArrayList<T>(); for(String str : list ){ System.out.println(str); T t = JSONUtils.parseObject(str,responseType); result.add(t); } response.setList(result); return response; } public <T> RestResponse putForResponse(String url, Object request, Class<T> responseType, Object... uriVariables) { String text = putForString(url, request,uriVariables); RestResponse reponse = JSONUtils.deserialize(text, RestResponse.class); return reponse; } public String putForString(String url, Object request, Object... uriVariables) { HttpEntity<String> requestEntity = new HttpEntity<String>(JSONUtils.serialize(request)); ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.PUT, requestEntity, String.class); return responseEntity.getBody(); } /********************************************* DELETE *************************************************/ public <T> RestEntityResponse<T> deleteForEntity(String url, Object request, Class<T> responseType, Object... uriVariables) { String text = putForString(url, request,uriVariables); @SuppressWarnings("unchecked") RestEntityResponse<T> response = JSONUtils.deserialize(text, RestEntityResponse.class); if(!response.isSuccess())return response; String content = response.getResult(); T t = JSONUtils.parseObject(content,responseType); response.setEntity(t); return response; } public <T> RestListResponse<T> deleteForList(String url, Object request, Class<T> responseType, Object... uriVariables) { String text = putForString(url, request,uriVariables); @SuppressWarnings("unchecked") RestListResponse<T> response = JSONUtils.deserialize(text, RestListResponse.class); if(!response.isSuccess())return response; String content = response.getResult(); List<String> list = JSONUtils.parseObject(content,new TypeReference<List<String>>(){}); List<T> result = new ArrayList<T>(); for(String str : list ){ T t = JSONUtils.parseObject(str,responseType); result.add(t); } response.setList(result); return response; } public <T> RestResponse deleteForResponse(String url, Object request, Class<T> responseType, Object... uriVariables) { String text = putForString(url, request,uriVariables); RestResponse reponse = JSONUtils.deserialize(text, RestResponse.class); return reponse; } public String deleteForString(String url, Object request, Object... uriVariables) { HttpEntity<String> requestEntity = new HttpEntity<String>(JSONUtils.serialize(request)); ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, String.class); return responseEntity.getBody(); } public static void main(String args[]) { HcpRestClientDaoImpl dao = new HcpRestClientDaoImpl(); RestListResponse<HcpUser> response = dao.getForList("http://127.0.0.1/api//hcp/base/user/list", HcpUser.class); for(HcpUser user : response.getList()){ System.out.println(user.getName()); } } }
package listeners; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import widgets.VisitInfo; /** * Handles removal of the visit. Once a visit is removed, it cannot be reverted. * * @author aggie * * @version $Revision: 1.0 $ */ public class RemoveVisitHandler { private Shell shell; private VisitInfo visit; public RemoveVisitHandler(Shell shell, VisitInfo visit) { this.shell = shell; this.visit = visit; MessageBox box = new MessageBox(shell); box.setText("Remove the visit"); box.setMessage("Are you sure you want to remove the selected visit?"); int choice = box.open(); switch (choice) { case SWT.YES: remove(); case SWT.NO: break; } } private void remove() { // TODO remove the visit from the database } }
package slimeknights.tconstruct.world.block; import net.minecraft.block.Block; import net.minecraft.block.BlockSapling; import net.minecraft.block.SoundType; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.EnumPlantType; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import java.util.Random; import javax.annotation.Nonnull; import slimeknights.tconstruct.library.TinkerRegistry; import slimeknights.tconstruct.shared.TinkerCommons; import slimeknights.tconstruct.shared.block.BlockSlime; import slimeknights.tconstruct.world.TinkerWorld; import slimeknights.tconstruct.world.block.BlockSlimeGrass.FoliageType; import slimeknights.tconstruct.world.worldgen.SlimeTreeGenerator; public class BlockSlimeSapling extends BlockSapling { public static PropertyEnum<FoliageType> FOLIAGE = BlockSlimeGrass.FOLIAGE; public BlockSlimeSapling() { setCreativeTab(TinkerRegistry.tabWorld); setDefaultState(this.blockState.getBaseState()); this.setSoundType(SoundType.PLANT); } @Override @SideOnly(Side.CLIENT) public void getSubBlocks(CreativeTabs tab, NonNullList<ItemStack> list) { for(FoliageType type : FoliageType.values()) { list.add(new ItemStack(this, 1, getMetaFromState(getDefaultState().withProperty(FOLIAGE, type)))); } } @Nonnull @Override protected BlockStateContainer createBlockState() { // TYPE has to be included because of the BlockSapling constructor.. but it's never used. return new BlockStateContainer(this, FOLIAGE, STAGE, TYPE); } /** * Convert the given metadata into a BlockState for this Block */ @Nonnull @Override public IBlockState getStateFromMeta(int meta) { if(meta < 0 || meta >= BlockSlimeGrass.FoliageType.values().length) { meta = 0; } BlockSlimeGrass.FoliageType grass = BlockSlimeGrass.FoliageType.values()[meta]; return this.getDefaultState().withProperty(BlockSlimeGrass.FOLIAGE, grass); } /** * Convert the BlockState into the correct metadata value */ @Override public int getMetaFromState(IBlockState state) { return state.getValue(BlockSlimeGrass.FOLIAGE).ordinal(); } @Override public int damageDropped(IBlockState state) { return getMetaFromState(state); } @Override public boolean isReplaceable(IBlockAccess worldIn, @Nonnull BlockPos pos) { return false; } @Override public boolean canPlaceBlockAt(World worldIn, BlockPos pos) { Block ground = worldIn.getBlockState(pos.down()).getBlock(); return ground == TinkerWorld.slimeGrass || ground == TinkerWorld.slimeDirt; } @Nonnull @Override public EnumPlantType getPlantType(IBlockAccess world, BlockPos pos) { return TinkerWorld.slimePlantType; } @Nonnull @Override public ItemStack getPickBlock(@Nonnull IBlockState state, RayTraceResult target, @Nonnull World world, @Nonnull BlockPos pos, EntityPlayer player) { IBlockState iblockstate = world.getBlockState(pos); int meta = iblockstate.getBlock().getMetaFromState(iblockstate); return new ItemStack(Item.getItemFromBlock(this), 1, meta); } @Override public void generateTree(@Nonnull World worldIn, @Nonnull BlockPos pos, @Nonnull IBlockState state, @Nonnull Random rand) { if(!net.minecraftforge.event.terraingen.TerrainGen.saplingGrowTree(worldIn, rand, pos)) { return; } BlockSlime.SlimeType slimeType = BlockSlime.SlimeType.GREEN; if(state.getValue(FOLIAGE) == FoliageType.ORANGE) { slimeType = BlockSlime.SlimeType.MAGMA; } IBlockState slimeGreen = TinkerCommons.blockSlimeCongealed.getDefaultState().withProperty(BlockSlime.TYPE, slimeType); IBlockState leaves = TinkerWorld.slimeLeaves.getDefaultState().withProperty(BlockSlimeGrass.FOLIAGE, state.getValue(FOLIAGE)); SlimeTreeGenerator gen = new SlimeTreeGenerator(5, 4, slimeGreen, leaves, null); // replace sapling with air worldIn.setBlockToAir(pos); // try generating gen.generateTree(rand, worldIn, pos); // check if it generated if(worldIn.isAirBlock(pos)) { // nope, set sapling again worldIn.setBlockState(pos, state, 4); } } }
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.cloudera.director.client.v11.model; import java.util.Objects; import com.cloudera.director.client.v11.model.DiagnosticDataSummary; import com.cloudera.director.client.v11.model.ErrorInfo; import com.cloudera.director.client.v11.model.Health; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * The status of a multi-step Cloudera Altus Director process */ @ApiModel(description = "The status of a multi-step Cloudera Altus Director process") public class Status { /** * Current stage of the process */ @JsonAdapter(StageEnum.Adapter.class) public enum StageEnum { BOOTSTRAPPING("BOOTSTRAPPING"), BOOTSTRAP_FAILED("BOOTSTRAP_FAILED"), READY("READY"), UPDATING("UPDATING"), UPDATE_FAILED("UPDATE_FAILED"), TERMINATING("TERMINATING"), TERMINATE_FAILED("TERMINATE_FAILED"), TERMINATED("TERMINATED"), UNKNOWN("UNKNOWN"); private String value; StageEnum(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static StageEnum fromValue(String text) { for (StageEnum b : StageEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } public static class Adapter extends TypeAdapter<StageEnum> { @Override public void write(final JsonWriter jsonWriter, final StageEnum enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public StageEnum read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return StageEnum.fromValue(String.valueOf(value)); } } } @SerializedName("stage") private StageEnum stage = null; @SerializedName("description") private String description = null; @SerializedName("descriptionDetails") private List<String> descriptionDetails = null; @SerializedName("errorInfo") private ErrorInfo errorInfo = null; @SerializedName("remainingSteps") private Integer remainingSteps = null; @SerializedName("completedSteps") private Integer completedSteps = null; @SerializedName("health") private Health health = null; @SerializedName("diagnosticDataSummaries") private List<DiagnosticDataSummary> diagnosticDataSummaries = null; public Status() { // Do nothing } private Status(StatusBuilder builder) { this.stage = builder.stage; this.description = builder.description; this.descriptionDetails = builder.descriptionDetails; this.errorInfo = builder.errorInfo; this.remainingSteps = builder.remainingSteps; this.completedSteps = builder.completedSteps; this.health = builder.health; this.diagnosticDataSummaries = builder.diagnosticDataSummaries; } public static StatusBuilder builder() { return new StatusBuilder(); } public static class StatusBuilder { private StageEnum stage = null; private String description = null; private List<String> descriptionDetails = new ArrayList<String>(); private ErrorInfo errorInfo = null; private Integer remainingSteps = null; private Integer completedSteps = null; private Health health = null; private List<DiagnosticDataSummary> diagnosticDataSummaries = new ArrayList<DiagnosticDataSummary>(); public StatusBuilder stage(StageEnum stage) { this.stage = stage; return this; } public StatusBuilder description(String description) { this.description = description; return this; } public StatusBuilder descriptionDetails(List<String> descriptionDetails) { this.descriptionDetails = descriptionDetails; return this; } public StatusBuilder errorInfo(ErrorInfo errorInfo) { this.errorInfo = errorInfo; return this; } public StatusBuilder remainingSteps(Integer remainingSteps) { this.remainingSteps = remainingSteps; return this; } public StatusBuilder completedSteps(Integer completedSteps) { this.completedSteps = completedSteps; return this; } public StatusBuilder health(Health health) { this.health = health; return this; } public StatusBuilder diagnosticDataSummaries(List<DiagnosticDataSummary> diagnosticDataSummaries) { this.diagnosticDataSummaries = diagnosticDataSummaries; return this; } public Status build() { return new Status(this); } } public StatusBuilder toBuilder() { return builder() .stage(stage) .description(description) .descriptionDetails(descriptionDetails) .errorInfo(errorInfo) .remainingSteps(remainingSteps) .completedSteps(completedSteps) .health(health) .diagnosticDataSummaries(diagnosticDataSummaries) ; } public Status stage(StageEnum stage) { this.stage = stage; return this; } /** * Current stage of the process * @return stage **/ @ApiModelProperty(required = true, value = "Current stage of the process") public StageEnum getStage() { return stage; } public void setStage(StageEnum stage) { this.stage = stage; } public Status description(String description) { this.description = description; return this; } /** * Status description * @return description **/ @ApiModelProperty(required = true, value = "Status description") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Status descriptionDetails(List<String> descriptionDetails) { this.descriptionDetails = descriptionDetails; return this; } public Status addDescriptionDetailsItem(String descriptionDetailsItem) { if (this.descriptionDetails == null) { this.descriptionDetails = new ArrayList<String>(); } this.descriptionDetails.add(descriptionDetailsItem); return this; } /** * Detailed status description * @return descriptionDetails **/ @ApiModelProperty(value = "Detailed status description") public List<String> getDescriptionDetails() { return descriptionDetails; } public void setDescriptionDetails(List<String> descriptionDetails) { this.descriptionDetails = descriptionDetails; } public Status errorInfo(ErrorInfo errorInfo) { this.errorInfo = errorInfo; return this; } /** * Error information associated with the status * @return errorInfo **/ @ApiModelProperty(value = "Error information associated with the status") public ErrorInfo getErrorInfo() { return errorInfo; } public void setErrorInfo(ErrorInfo errorInfo) { this.errorInfo = errorInfo; } public Status remainingSteps(Integer remainingSteps) { this.remainingSteps = remainingSteps; return this; } /** * Number of remaining steps planned for the process * @return remainingSteps **/ @ApiModelProperty(required = true, value = "Number of remaining steps planned for the process") public Integer getRemainingSteps() { return remainingSteps; } public void setRemainingSteps(Integer remainingSteps) { this.remainingSteps = remainingSteps; } public Status completedSteps(Integer completedSteps) { this.completedSteps = completedSteps; return this; } /** * Number of steps completed for the process * @return completedSteps **/ @ApiModelProperty(required = true, value = "Number of steps completed for the process") public Integer getCompletedSteps() { return completedSteps; } public void setCompletedSteps(Integer completedSteps) { this.completedSteps = completedSteps; } public Status health(Health health) { this.health = health; return this; } /** * Health reported for the entity being processed * @return health **/ @ApiModelProperty(required = true, value = "Health reported for the entity being processed") public Health getHealth() { return health; } public void setHealth(Health health) { this.health = health; } public Status diagnosticDataSummaries(List<DiagnosticDataSummary> diagnosticDataSummaries) { this.diagnosticDataSummaries = diagnosticDataSummaries; return this; } public Status addDiagnosticDataSummariesItem(DiagnosticDataSummary diagnosticDataSummariesItem) { if (this.diagnosticDataSummaries == null) { this.diagnosticDataSummaries = new ArrayList<DiagnosticDataSummary>(); } this.diagnosticDataSummaries.add(diagnosticDataSummariesItem); return this; } /** * Diagnostic data summaries * @return diagnosticDataSummaries **/ @ApiModelProperty(value = "Diagnostic data summaries") public List<DiagnosticDataSummary> getDiagnosticDataSummaries() { return diagnosticDataSummaries; } public void setDiagnosticDataSummaries(List<DiagnosticDataSummary> diagnosticDataSummaries) { this.diagnosticDataSummaries = diagnosticDataSummaries; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Status status = (Status) o; return Objects.equals(this.stage, status.stage) && Objects.equals(this.description, status.description) && Objects.equals(this.descriptionDetails, status.descriptionDetails) && Objects.equals(this.errorInfo, status.errorInfo) && Objects.equals(this.remainingSteps, status.remainingSteps) && Objects.equals(this.completedSteps, status.completedSteps) && Objects.equals(this.health, status.health) && Objects.equals(this.diagnosticDataSummaries, status.diagnosticDataSummaries); } @Override public int hashCode() { return Objects.hash(stage, description, descriptionDetails, errorInfo, remainingSteps, completedSteps, health, diagnosticDataSummaries); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Status {\n"); sb.append(" stage: ").append(toIndentedString(stage)).append("\n"); sb.append(" description: ").append(toIndentedString(description)).append("\n"); sb.append(" descriptionDetails: ").append(toIndentedString(descriptionDetails)).append("\n"); sb.append(" errorInfo: ").append(toIndentedString(errorInfo)).append("\n"); sb.append(" remainingSteps: ").append(toIndentedString(remainingSteps)).append("\n"); sb.append(" completedSteps: ").append(toIndentedString(completedSteps)).append("\n"); sb.append(" health: ").append(toIndentedString(health)).append("\n"); sb.append(" diagnosticDataSummaries: ").append(toIndentedString(diagnosticDataSummaries)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
package edu.uw.service; import java.util.Date; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.apache.commons.lang3.StringUtils; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.domain.Specifications; import edu.uw.model.PersonEntity; public class PersonSpecifications { public static Specification<PersonEntity> hasAffiliations(String affiliation) { return new Specification<PersonEntity>() { @Override public Predicate toPredicate(Root<PersonEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) { return cb.equal(root.join("affiliatons").get("name"), affiliation); } }; } public static Specification<PersonEntity> hasZip(int zip) { return new Specification<PersonEntity>() { @Override public Predicate toPredicate(Root<PersonEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) { return cb.equal(root.join("address").get("zip"), zip); } }; } public static Specification<PersonEntity> hasActive(Date date) { return new Specification<PersonEntity>() { @Override public Predicate toPredicate(Root<PersonEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) { return cb.equal(root.get("hireDate"), date); } }; } public static Specification<PersonEntity> hasPersonId(Long personId) { return new Specification<PersonEntity>() { @Override public Predicate toPredicate(Root<PersonEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) { return cb.equal(root.get("personId"), personId); } }; } public static Specification<PersonEntity> createSpec(String affiliation, Date activeOn, Integer zip) { Specifications<PersonEntity> spec = null; if (StringUtils.isNoneBlank(affiliation)) { spec = Specifications.where(hasAffiliations(affiliation)); } if (activeOn != null) { if (spec == null) { spec = Specifications.where(hasActive(activeOn)); } else { spec = spec.and(Specifications.where(hasActive(activeOn))); } } if (zip != null) { if (spec == null) { spec = Specifications.where(hasZip(zip)); } else { spec = spec.and(Specifications.where(hasZip(zip))); } } return spec; } public static Specification<PersonEntity> createSpecLastName(String LastName) { Specifications<PersonEntity> spec = null; if (StringUtils.isNoneBlank(LastName)) { spec = Specifications.where(hasLastName(LastName)); } return spec; } public static Specification<PersonEntity> hasLastName(String LastName) { return new Specification<PersonEntity>() { @Override public Predicate toPredicate(Root<PersonEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) { return cb.equal(root.join("LastName").get("lastName"), LastName); } }; } }
package com.company.model; import java.util.HashMap; import java.util.Map; /** * Created by abalamanova on May, 2019 */ public class Customer { private int bonusPoints = 0; private int totalPrice = 0; public Map<Integer, Film> filmList = new HashMap<>(); public int getTotalPrice() { return this.totalPrice; } public int getBonusPoints() { return bonusPoints; } public void setBonusPoints(int bonusPoints) { this.bonusPoints = bonusPoints; } public void setTotalPrice(int totalPrice) { this.totalPrice = totalPrice; } public Map<Integer, Film> getFilmList() { return filmList; } }
package com.legaoyi.protocol.down.messagebody; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.fasterxml.jackson.annotation.JsonProperty; import com.legaoyi.protocol.message.MessageBody; /** * 云台调整光圈控制 * * @author <a href="mailto:shengbo.gao@gmail.com;78772895@qq.com">gaoshengbo</a> * @version 1.0.0 * @since 2018-04-09 */ @Scope("prototype") @Component(MessageBody.MESSAGE_BODY_BEAN_PREFIX + "9303_2016" + MessageBody.MESSAGE_BODY_BEAN_SUFFIX) public class JTT1078_9303_MessageBody extends MessageBody { private static final long serialVersionUID = -2222441901600081391L; public static final String MESSAGE_ID = "9303"; /** 逻辑通道号 **/ @JsonProperty("channelId") private int channelId; /** 光圈调整方式 **/ @JsonProperty("type") private int type; public final int getChannelId() { return channelId; } public final void setChannelId(int channelId) { this.channelId = channelId; } public final int getType() { return type; } public final void setType(int type) { this.type = type; } }
package com.alexey.vk; import android.content.ContentValues; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import com.alexey.vk.model.DBHelper; import com.alexey.vk.model.DrawerMenu; import com.alexey.vk.model.News; import com.alexey.vk.model.OnBackPressedListener; import com.alexey.vk.model.User; import com.alexey.vk.view.NewsPreview; import com.alexey.vk.view.OpenPhoto; import com.alexey.vk.view.PagePreview; import com.alexey.vk.view.UserPage; import com.alexey.vk.view.logged.NewsFragment; import com.alexey.vk.view.registration.Login; import com.alexey.vk.view.registration.RegFirst; import java.text.DateFormat; import java.util.Date; import java.util.List; public class MainActivity extends AppCompatActivity { private Fragment fragment; private View HEADER; public static Toolbar toolbar; private Cursor cursorNews; private Cursor cursorUser; private Cursor cursorFriends; public static Cursor CTHISUSER = null; private ContentValues cv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent intent = getIntent(); DBHelper dbHelper = new DBHelper(this); dbHelper.create(); dbHelper.openDB(); toolbar = (Toolbar) findViewById(R.id.toolbar); cv = new ContentValues(); int click = intent.getIntExtra("click", 0); switch (click) { case 0: final boolean b = setUserNameInHeader(); if (b) { searchThisUser(CTHISUSER); createDrawer(); fragment = new NewsFragment(); } break; case 1: fragment = new RegFirst(); break; case 2: fragment = new Login(); break; } getSupportFragmentManager().beginTransaction() .replace(R.id.frame, fragment) .commit(); } @Override protected void onDestroy() { if (CTHISUSER != null) { CTHISUSER.close(); DBHelper.Companion.getDb().close(); } super.onDestroy(); } @Override public void onBackPressed() { OnBackPressedListener listener = null; for (Fragment fragments : getSupportFragmentManager().getFragments()) { if (fragments instanceof OnBackPressedListener) { listener = (OnBackPressedListener) fragments; break; } } if (listener != null) { listener.onBackPressed(); } else { if (DrawerMenu.drawer.isDrawerOpen()) { DrawerMenu.drawer.closeDrawer(); } else super.onBackPressed(); super.onBackPressed(); } } public void saveUser(String s, String ls) { cv.clear(); cv.put(DBHelper.Companion.getUSER_NAME(), s.toLowerCase()); cv.put(DBHelper.Companion.getUSER_LASTNAME(), ls.toLowerCase()); cv.put(DBHelper.Companion.getISFRIEND(), 0); DBHelper.Companion.getDb().insert(DBHelper.Companion.getUSER_TABLE(), null, cv); SharedPreferences.Editor editor = Start.SP.edit(); editor.putString(Start.NAME, s); editor.putString(Start.LASTNAME, ls); editor.apply(); } public void saveNews(String textNews) { cv.clear(); cv.put(DBHelper.Companion.getNEWS_TITLE(), upFirst(CTHISUSER.getString(CTHISUSER.getColumnIndex(DBHelper.Companion.getUSER_NAME()))) + " " + upFirst(CTHISUSER.getString(CTHISUSER.getColumnIndex(DBHelper.Companion.getUSER_LASTNAME()))));//Start.sp.getString(NAME, "")) + " " + upFirst(Start.sp.getString(LASTNAME, ""))); cv.put(DBHelper.Companion.getNEWS_TIME(), DateFormat.getDateTimeInstance().format(new Date())); cv.put(DBHelper.Companion.getNEWS_TEXT(), textNews); cv.put(DBHelper.Companion.getNEWS_LIKE(), 0); cv.put(DBHelper.Companion.getNEWS_REPOST(), 0); cv.put(DBHelper.Companion.getNEWS_COMMENT(), 0); cv.put(DBHelper.Companion.getNEWS_USERID(), CTHISUSER.getInt(CTHISUSER.getColumnIndex(DBHelper.Companion.getID_USER()))); DBHelper.Companion.getDb().insert(DBHelper.Companion.getNEWS_TABLE(), null, cv); } public void getAllNews(List<News> newsList) { cursorNews = null; cursorNews = DBHelper.Companion.selectFrom(DBHelper.Companion.getNEWS_TABLE(), DBHelper.Companion.getColumnsNews(), null, null, DBHelper.Companion.getNEWS_TIME() + " DESC"); if (cursorNews != null && cursorNews.moveToFirst()) { do { News news = new News(cursorNews.getInt(cursorNews.getColumnIndex(DBHelper.Companion.getID_NEWS())), R.drawable.news, cursorNews.getString(cursorNews.getColumnIndex(DBHelper.Companion.getNEWS_TITLE())), cursorNews.getString(cursorNews.getColumnIndex(DBHelper.Companion.getNEWS_TIME())), cursorNews.getString(cursorNews.getColumnIndex(DBHelper.Companion.getNEWS_TEXT())) + " " + cursorNews.getInt(cursorNews.getColumnIndex(DBHelper.Companion.getID_NEWS())), cursorNews.getInt(cursorNews.getColumnIndex(DBHelper.Companion.getNEWS_LIKE())), cursorNews.getInt(cursorNews.getColumnIndex(DBHelper.Companion.getNEWS_REPOST())), cursorNews.getInt(cursorNews.getColumnIndex(DBHelper.Companion.getNEWS_COMMENT())) ); newsList.add(news); } while (cursorNews.moveToNext()); cursorNews.close(); } } public void getUserNews(List<News> newsList) { cursorNews = null; cursorNews = DBHelper.Companion.selectFrom(DBHelper.Companion.getNEWS_TABLE(), DBHelper.Companion.getColumnsNews(), DBHelper.Companion.getNEWS_USERID() + " =?", new String[]{String.valueOf(CTHISUSER.getInt(CTHISUSER.getColumnIndex(DBHelper.Companion.getID_USER())))}, DBHelper.Companion.getNEWS_TIME() + " ASC"); if (cursorNews != null && cursorNews.moveToLast()) { do { News news = new News(cursorNews.getInt(cursorNews.getColumnIndex(DBHelper.Companion.getID_NEWS())), R.drawable.news, upFirst(Start.SP.getString(Start.NAME, "")) + " " + upFirst(Start.SP.getString(Start.LASTNAME, "")), cursorNews.getString(cursorNews.getColumnIndex(DBHelper.Companion.getNEWS_TIME())), cursorNews.getString(cursorNews.getColumnIndex(DBHelper.Companion.getNEWS_TEXT())), cursorNews.getInt((cursorNews.getColumnIndex(DBHelper.Companion.getNEWS_LIKE()))), cursorNews.getInt(cursorNews.getColumnIndex(DBHelper.Companion.getNEWS_REPOST())), cursorNews.getInt(cursorNews.getColumnIndex(DBHelper.Companion.getNEWS_COMMENT())) ); newsList.add(news); } while (cursorNews.moveToPrevious()); cursorNews.close(); } } public void getFriends(List<User> friends) { cursorFriends = null; cursorFriends = DBHelper.Companion.selectFrom(DBHelper.Companion.getUSER_TABLE(), DBHelper.Companion.getColumnsUser(), DBHelper.Companion.getISFRIEND() + " =?", new String[]{String.valueOf(CTHISUSER.getInt(CTHISUSER.getColumnIndex(DBHelper.Companion.getID_USER())))}, null); if (cursorFriends != null && cursorFriends.moveToFirst()) { do { User userVK = new User( cursorFriends.getString(cursorFriends.getColumnIndex(DBHelper.Companion.getUSER_NAME())), cursorFriends.getString(cursorFriends.getColumnIndex(DBHelper.Companion.getUSER_LASTNAME())), null, null, null, null, 0, 0, 0, 0, 0, 0, 0, 0); friends.add(userVK); } while (cursorFriends.moveToNext()); cursorFriends.close(); } } public void getAllUsers(List<User> friends) { cursorFriends = null; cursorFriends = DBHelper.Companion.selectFrom(DBHelper.Companion.getUSER_TABLE(), DBHelper.Companion.getColumnsUser(), DBHelper.Companion.getUSER_NAME() + " !=?", new String[]{Start.SP.getString(Start.NAME, "").toLowerCase()}, null); Log.d("", "getAllUsers: " + (cursorFriends != null ? cursorFriends.getCount() : 0)); if (cursorFriends != null && cursorFriends.moveToFirst()) { do { User userVK = new User( cursorFriends.getString(cursorFriends.getColumnIndex(DBHelper.Companion.getUSER_NAME())), cursorFriends.getString(cursorFriends.getColumnIndex(DBHelper.Companion.getUSER_LASTNAME())), cursorFriends.getString(cursorFriends.getColumnIndex(DBHelper.Companion.getUSER_BIRTH())), cursorFriends.getString(cursorFriends.getColumnIndex(DBHelper.Companion.getUSER_STATUS())), cursorFriends.getString(cursorFriends.getColumnIndex(DBHelper.Companion.getUSER_COUNTRY())), cursorFriends.getString(cursorFriends.getColumnIndex(DBHelper.Companion.getUSER_CITY())), cursorFriends.getInt(cursorFriends.getColumnIndex(DBHelper.Companion.getUSER_FRIENDS())), cursorFriends.getInt(cursorFriends.getColumnIndex(DBHelper.Companion.getUSER_GROUPS())), cursorFriends.getInt(cursorFriends.getColumnIndex(DBHelper.Companion.getUSER_FOLLOWERS())), cursorFriends.getInt(cursorFriends.getColumnIndex(DBHelper.Companion.getUSER_PHOTOS())), cursorFriends.getInt(cursorFriends.getColumnIndex(DBHelper.Companion.getUSER_VIDEOS())), cursorFriends.getInt(cursorFriends.getColumnIndex(DBHelper.Companion.getUSER_AUDIOS())), cursorFriends.getInt(cursorFriends.getColumnIndex(DBHelper.Companion.getUSER_PHONENUMBER())), cursorFriends.getInt(cursorFriends.getColumnIndex(DBHelper.Companion.getISFRIEND())) ); friends.add(userVK); } while (cursorFriends.moveToNext()); cursorFriends.close(); } } public void clickFriend(Bundle bundle) { PagePreview fragment = new PagePreview(); fragment.setArguments(bundle); getSupportFragmentManager().beginTransaction().replace(R.id.frame, fragment).commit(); } public boolean auth(String name) { cursorUser = null; cursorUser = DBHelper.Companion.selectFrom(DBHelper.Companion.getUSER_TABLE(), DBHelper.Companion.getColumnsUser(), DBHelper.Companion.getUSER_NAME() + " =?", new String[]{name}, null); if (cursorUser.moveToFirst()) { // Start.sp = getSharedPreferences(NAME, MODE_PRIVATE); SharedPreferences.Editor ed = Start.SP.edit(); ed.putString(Start.NAME, name); String ln = cursorUser.getString(cursorUser.getColumnIndex(DBHelper.Companion.getUSER_LASTNAME())); ed.putString(Start.LASTNAME, ln); ed.apply(); boolean b = setUserNameInHeader(); if (b) { cursorUser.close(); searchThisUser(CTHISUSER); return true; } } else Toast.makeText(this, "Reenter login or password", Toast.LENGTH_SHORT).show(); cursorUser.close(); return false; } public void openPhoto(View view) { getSupportFragmentManager().beginTransaction().replace(R.id.frame, new OpenPhoto()).commit(); } public boolean setUserNameInHeader() { String name = Start.SP.getString(Start.NAME, ""); if (!name.isEmpty()) { HEADER = getLayoutInflater().inflate(R.layout.header, new ViewGroup(this) { @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { } }, false); TextView userName = (TextView) HEADER.findViewById(R.id.user_name); userName.setText(upFirst(name)); toolbar.setTitle(upFirst(name)); return true; } else return false; } public void clickUserPage(View view) { DrawerMenu.drawer.closeDrawer(); toolbar.setTitle(upFirst(Start.SP.getString(Start.NAME, ""))); getSupportFragmentManager().beginTransaction() .replace(R.id.frame, new UserPage()) .commit(); } public void clickNews(Bundle bundle) { NewsPreview fragment = new NewsPreview(); fragment.setArguments(bundle); getSupportFragmentManager().beginTransaction().replace(R.id.frame, fragment).commit(); } public void addToFriends(String s) { ContentValues cv1 = new ContentValues(); cursorUser = null; String us = firsWord(s.toLowerCase()); cursorUser = DBHelper.Companion.selectFrom(DBHelper.Companion.getUSER_TABLE(), DBHelper.Companion.getColumnsUser(), DBHelper.Companion.getUSER_NAME() + " =?", new String[]{us}, null); boolean b = cursorUser.moveToFirst(); cv.clear(); cv1.clear(); if (b) { cv.put(DBHelper.Companion.getISFRIEND(), CTHISUSER.getInt(CTHISUSER.getColumnIndex(DBHelper.Companion.getID_USER()))); cv1.put(DBHelper.Companion.getISFRIEND(), cursorUser.getInt(cursorUser.getColumnIndex(DBHelper.Companion.getID_USER()))); Toast.makeText(MainActivity.this, upFirst(cursorUser.getString(cursorUser.getColumnIndex(DBHelper.Companion.getUSER_NAME()))) + " add in friends", Toast.LENGTH_SHORT).show(); } else { cv.put(DBHelper.Companion.getISFRIEND(), -1); Toast.makeText(MainActivity.this, upFirst(cursorUser.getString(cursorUser.getColumnIndex(DBHelper.Companion.getUSER_NAME()))) + " delete in friends", Toast.LENGTH_SHORT).show(); } DBHelper.Companion.getDb().update(DBHelper.Companion.getUSER_TABLE(), cv1, DBHelper.Companion.getID_USER() + " =?", new String[]{String.valueOf(CTHISUSER.getInt(CTHISUSER.getColumnIndex(DBHelper.Companion.getID_USER())))} ); DBHelper.Companion.getDb().update(DBHelper.Companion.getUSER_TABLE(), cv, DBHelper.Companion.getID_USER() + " =?", new String[]{String.valueOf(cursorUser.getInt(cursorUser.getColumnIndex(DBHelper.Companion.getID_USER())))} ); cursorUser.close(); } public void setUserPage(TextView name, TextView status, TextView friends, TextView followers, TextView groups, TextView photos, TextView audios, TextView videos) { Cursor cursor = DBHelper.Companion.selectFrom(DBHelper.Companion.getUSER_TABLE(), DBHelper.Companion.getColumnsUser(), DBHelper.Companion.getISFRIEND() + " =?", new String[]{String.valueOf(CTHISUSER.getInt(CTHISUSER.getColumnIndex(DBHelper.Companion.getID_USER())))}, null); if (cursor != null && cursor.moveToFirst()) { friends.setText(String.valueOf(cursor.getCount())); } else { friends.setText("0"); } String namePlusLast = upFirst(CTHISUSER.getString(CTHISUSER.getColumnIndex(DBHelper.Companion.getUSER_NAME()))) + " " + upFirst(CTHISUSER.getString(CTHISUSER.getColumnIndex(DBHelper.Companion.getUSER_LASTNAME()))); name.setText(namePlusLast); status.setText(upFirst(CTHISUSER.getString(CTHISUSER.getColumnIndex(DBHelper.Companion.getUSER_NAME())))); followers.setText(String.valueOf(CTHISUSER.getInt(CTHISUSER.getColumnIndex(DBHelper.Companion.getUSER_FOLLOWERS())))); groups.setText(String.valueOf(CTHISUSER.getInt(CTHISUSER.getColumnIndex(DBHelper.Companion.getUSER_GROUPS())))); photos.setText(String.valueOf(CTHISUSER.getInt(CTHISUSER.getColumnIndex(DBHelper.Companion.getUSER_PHOTOS())))); audios.setText(String.valueOf(CTHISUSER.getInt(CTHISUSER.getColumnIndex(DBHelper.Companion.getUSER_AUDIOS())))); videos.setText(String.valueOf(CTHISUSER.getInt(CTHISUSER.getColumnIndex(DBHelper.Companion.getUSER_VIDEOS())))); } public void setNewsPreview(String tim, ImageButton icon, TextView title, TextView time, TextView text, TextView comment, TextView repost, TextView like) { Cursor cursor = DBHelper.Companion.selectFrom(DBHelper.Companion.getNEWS_TABLE(), DBHelper.Companion.getColumnsNews(), DBHelper.Companion.getNEWS_TIME() + " =?", new String[]{tim}, null); if (cursor.moveToFirst()) { icon.setImageResource(R.drawable.news); title.setText(upFirst(cursor.getString(cursor.getColumnIndex(DBHelper.Companion.getNEWS_TITLE())))); time.setText(cursor.getString(cursor.getColumnIndex(DBHelper.Companion.getNEWS_TIME()))); text.setText(cursor.getString(cursor.getColumnIndex(DBHelper.Companion.getNEWS_TEXT()))); like.setText(String.valueOf(cursor.getInt((cursor.getColumnIndex(DBHelper.Companion.getNEWS_LIKE()))))); repost.setText(String.valueOf(cursor.getInt(cursor.getColumnIndex(DBHelper.Companion.getNEWS_REPOST())))); comment.setText(String.valueOf(cursor.getInt(cursor.getColumnIndex(DBHelper.Companion.getNEWS_COMMENT())))); } cursor.close(); } public void upgradePhoto(View view) { Toast.makeText(MainActivity.this, "up", Toast.LENGTH_SHORT).show(); } public void exitUser() { Start.SP.edit().clear().apply(); } public void searchThisUser(Cursor cursor) { CTHISUSER = null; CTHISUSER = DBHelper.Companion.selectFrom(DBHelper.Companion.getUSER_TABLE(),DBHelper.Companion.getColumnsUser(),DBHelper.Companion.getUSER_NAME() + " =?", new String[]{Start.SP.getString(Start.NAME, "").toLowerCase()}, null); CTHISUSER.moveToFirst(); } public void createDrawer() { new DrawerMenu(toolbar, this, HEADER, getSupportFragmentManager()); } public static String upFirst(String s) { String s1; if (!s.isEmpty()) { s1 = String.valueOf(s.charAt(0)).toUpperCase(); for (int i = 1; i < s.length(); i++) { s1 += String.valueOf(s.charAt(i)); } return s1; } else return null; } public String firsWord(String s) { String s1 = ""; int i = 0; while (i < s.length()) { if (s.charAt(i) == ' ') { return s1; } else { s1 += s.charAt(i); i++; } } return s1; } }
package com.citibank.ods.entity.pl.valueobject; public class TplFundMortMovEntityVO extends BaseTplFundMortMovEntityVO { }
package cl.cehd.ocr.facade; import cl.cehd.ocr.algorithm.usecase.AccountNumberIdentifier; import cl.cehd.ocr.io.AccountInputReader; import cl.cehd.ocr.io.AccountNumberInput; import cl.cehd.ocr.io.AccountNumberOut; import java.util.List; import java.util.stream.Collectors; public class AccountNumberIdentifierFacade { private final AccountInputReader accountInputReader; private final AccountNumberIdentifier accountNumberIdentifier; public AccountNumberIdentifierFacade(AccountInputReader accountInputReader, AccountNumberIdentifier accountNumberIdentifier) { this.accountInputReader = accountInputReader; this.accountNumberIdentifier = accountNumberIdentifier; } public List<AccountNumberOut> processORCAccounts() { List<AccountNumberInput> accountNumberInputs = accountInputReader.readInputData(); List<String> rawAccountsNumbers = getRawAccountNumbers(accountNumberInputs); return rawAccountsNumbers .stream() .map(AccountNumberOut::new) .collect(Collectors.toList()); } private List<String> getRawAccountNumbers(List<AccountNumberInput> accountNumberInputs) { return accountNumberInputs .stream() .map(accountInput -> accountNumberIdentifier.identifyAccountNumber(accountInput.generateDigits())) .collect(Collectors.toList()); } }
/* * This code is sample code, provided as-is, and we make no * warranties as to its correctness or suitability for * any purpose. * * We hope that it's useful to you. Enjoy. * Copyright 2006-12 LearningPatterns Inc. */ package com.javatunes.data; import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.javatunes.domain.MusicItem; /** * This class is a simple bean that emulates the search of some catalog. We do * this so we don't need a database at this early stage of the course. This will * be replaced with a persistent entity that goes to a database in a later lab. */ public class InMemoryItemDAO implements ItemDAO { // catalog of MusicItem objects private final List<MusicItem> catalog; // Constructor - JavaTunesSearch must be created with a catalog passed in public InMemoryItemDAO(final List<MusicItem> catalogIn) { this.catalog = catalogIn; } @Override public MusicItem create(final MusicItem newItem) { this.catalog.add(newItem); return this.catalog.get(this.catalog.size() - 1); } @Override public List<MusicItem> getAll() { return Collections.unmodifiableList(this.catalog); } // searches catalog by ID @Override public MusicItem getByID(final Long id) { // declare return value MusicItem result = null; // iterate through the catalog, looking for an ID match for (final MusicItem item : this.catalog) { if (item.getId().equals(id)) { result = item; // assign to return value break; // found it - stop looping } } return result; } @Override public void remove(final Long id) { this.catalog.remove(getByID(id)); } // searches catalog by keyword @Override public List<MusicItem> searchByArtistTitle(String keyword) { // declare return value final List<MusicItem> result = new ArrayList<MusicItem>(); // remove case sensitivity keyword = keyword.toLowerCase(); // iterate through the catalog, looking for a keyword match for (final MusicItem item : this.catalog) { if ((item.getTitle().toLowerCase().indexOf(keyword) != -1) || (item.getArtist().toLowerCase().indexOf(keyword) != -1)) { result.add(item); } } return result; } }
package es.upm.grise.profundizacion2019.ex3; public final class MyClass { // La instancia usada para calcular el tiempo private Time time; // Un constructor que inyecta la dependencia public MyClass(final Time time) { this.time = time; } // Calcula un tiempo futuro usando el tiempo actual como base public void nextTime(final long seconds) { final String next = time.getFutureTime(seconds); System.out.println(next); } }
package com.ronoco.yodlee.service.impl; import com.ronoco.yodlee.model.*; import com.ronoco.yodlee.service.YodleeService; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.util.*; @Service public class YodleeServiceImpl implements YodleeService { private static final String ACCEPT_CHARSET = "UTF-8"; private static final String ACCOUNTS_URL = "accounts?status=ACTIVE"; private static final String API_VERSION = "1.1"; private static final String API_VERSION_HEADER = "Api-Version"; private static final String APP_ID = "10003600"; private static final String COBRAND_HEADER = "Cobrand-Name"; private static final String COBRAND_LOGIN_URL = "cobrand/login"; private static final String CONTENT_TYPE = "application/json"; private static final String INVESTMENT_TYPE = "investment"; private static final String USER_LOGIN_URL = "user/login"; private static final String ACCESS_TOKEN_URL = "user/accessTokens?appIds=" + APP_ID; private final String cobrandLogin; private final String cobrandPassword; private final String locale; private final String yodleeAccountPassword; private final String cobrandName; private final String yodleeUrl; private final RestTemplate restTemplate; public YodleeServiceImpl(@Value("${yodlee.cobrand.login}") String cobrandLogin, @Value("${yodlee.cobrand.password}") String cobrandPassword, @Value("${yodlee.cobrand.locale}") String locale, @Value("${yodlee.api.accountPassword}") String yodleeAccountPassword, @Value("${yodlee.cobrand.name}") String cobrandName, @Value("${yodlee.api.url}") String yodleeUrl, RestTemplate restTemplate) { this.cobrandLogin = cobrandLogin; this.cobrandPassword = cobrandPassword; this.locale = locale; this.yodleeAccountPassword = yodleeAccountPassword; this.cobrandName = cobrandName; this.yodleeUrl = yodleeUrl; this.restTemplate = restTemplate; } @Override public String getCobSession() { HttpHeaders headers = getHttpHeaders(); CobrandRequest cobrandRequest = new CobrandRequest(); Cobrand cobrand = new Cobrand(); cobrandRequest.setCobrand(cobrand); cobrand.setCobrandLogin(this.cobrandLogin); cobrand.setCobrandPassword(this.cobrandPassword); cobrand.setLocale(this.locale); HttpEntity<CobrandRequest> httpEntity = new HttpEntity<>(cobrandRequest, headers); ResponseEntity<CobrandResponse> responseEntity = restTemplate.exchange( yodleeUrl + COBRAND_LOGIN_URL, HttpMethod.POST, httpEntity, CobrandResponse.class); CobrandResponse cobrandResponse = responseEntity.getBody(); return cobrandResponse.getSession().getCobSession(); } @Override public String getUserSession(String cobSession, String username) { HttpHeaders headers = getHttpHeaders(); headers.add(HttpHeaders.AUTHORIZATION, getAuthorizationHeader(cobSession)); UserRequest userRequest = new UserRequest(); User user = new User(); userRequest.setUser(user); user.setLoginName(username); user.setPassword(this.yodleeAccountPassword); user.setLocale(this.locale); HttpEntity<UserRequest> httpEntity = new HttpEntity<>(userRequest, headers); String url = yodleeUrl + USER_LOGIN_URL; ResponseEntity<UserResponse> responseEntity = restTemplate.exchange( yodleeUrl + USER_LOGIN_URL, HttpMethod.POST, httpEntity, UserResponse.class); UserResponse userResponse = responseEntity.getBody(); return userResponse.getUser().getSession().getUserSession(); } @Override public String registerUser(String cobSession, String username, String password, String email) { return null; } @Override public String getAccessTokens(String cobSession, String userSession) { HttpHeaders headers = getHttpHeaders(); headers.add(HttpHeaders.AUTHORIZATION, getAuthorizationHeader(cobSession, userSession)); HttpEntity<?> httpEntity = new HttpEntity<String>(headers); String url = yodleeUrl + ACCESS_TOKEN_URL; ResponseEntity<UserAccessTokenResponse> responseEntity = restTemplate.exchange( yodleeUrl + ACCESS_TOKEN_URL, HttpMethod.GET, httpEntity, UserAccessTokenResponse.class); UserAccessTokenResponse userAccessTokenResponse = responseEntity.getBody(); List<AccessToken> accessTokenList = userAccessTokenResponse.getUser().getAccessTokens(); for(AccessToken accessToken : accessTokenList) { if(accessToken.getAppId().equals(APP_ID)) { return accessToken.getValue(); } } return null; } @Override public List<Account> getInvestmentAccounts(String cobSession, String userSession) { HttpHeaders headers = getHttpHeaders(); headers.add(HttpHeaders.AUTHORIZATION, getAuthorizationHeader(cobSession, userSession)); HttpEntity<?> httpEntity = new HttpEntity<String>(headers); ResponseEntity<AccountResponse> responseEntity = restTemplate.exchange( yodleeUrl + ACCOUNTS_URL, HttpMethod.GET, httpEntity, AccountResponse.class); List<Account> accountList = responseEntity.getBody().getAccount(); List<Account> investmentAccountList = new ArrayList<>(); for(Account account : accountList) { if(INVESTMENT_TYPE.equals(account.getContainer())) { investmentAccountList.add(account); } } return investmentAccountList; } String getAuthorizationHeader(String cobSession) { return "cobSession=" + cobSession; } String getAuthorizationHeader(String cobSession, String userSession) { return "cobSession=" + cobSession + ",userSession=" + userSession; } HttpHeaders getHttpHeaders() { HttpHeaders headers = new HttpHeaders(); headers.add(COBRAND_HEADER, cobrandName); headers.add(API_VERSION_HEADER, API_VERSION); headers.add(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE); headers.add(HttpHeaders.ACCEPT_CHARSET, ACCEPT_CHARSET); return headers; } }
package com.clicky.profepa.fragments; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.clicky.profepa.R; import com.clicky.profepa.data.Documentos; import com.clicky.profepa.data.PROFEPAPreferences; import com.parse.GetCallback; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQuery; /** * * Created by Clicky on 3/22/15. * */ public class ReportFragment extends Fragment { private static String EXTRA_FOLIO = "folio"; private TextView txtFolio, txtTitular; private EditText editReport; private String folio; public static ReportFragment newInstance(String folio){ ReportFragment frag = new ReportFragment(); Bundle args = new Bundle(); args.putString(EXTRA_FOLIO, folio); frag.setArguments(args); return frag; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_report, container, false); Toolbar toolbar = (Toolbar)v.findViewById(R.id.toolbar); ((ActionBarActivity)getActivity()).setSupportActionBar(toolbar); setUpBar(); txtFolio = (TextView)v.findViewById(R.id.txt_folio); txtTitular = (TextView)v.findViewById(R.id.txt_titular); editReport = (EditText)v.findViewById(R.id.edit_reporte); getFolio(); return v; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); decodeArguments(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_reporte, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: getActivity().onBackPressed(); return true; case R.id.action_send: if(validate()){ sendReport(); }else{ Toast.makeText(getActivity(),R.string.error_fields,Toast.LENGTH_SHORT).show(); } return true; default: return super.onOptionsItemSelected(item); } } private void decodeArguments(){ Bundle args = getArguments(); if(args != null) { folio = args.getString(EXTRA_FOLIO); } } private boolean validate(){ return !editReport.getText().toString().isEmpty(); } private void setUpBar(){ ActionBarActivity activity = (ActionBarActivity)getActivity(); activity.getSupportActionBar().setHomeButtonEnabled(true); activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true); getActivity().setTitle(R.string.title_reportar); } private void getFolio(){ ParseQuery<Documentos> query = Documentos.getQuery(); query.include("Titular"); query.whereEqualTo("objectId", folio); query.fromLocalDatastore(); query.getFirstInBackground(new GetCallback<Documentos>() { public void done(Documentos doc, ParseException e) { if (e == null) { // Results were successfully found from the local datastore. txtFolio.setText(doc.getFolioProg().toString()); txtTitular.setText(doc.getTitular().getString("Nombre")); } else { // There was an error. Log.i("ResultFragment", "findFolio: Error finding document: " + e.getMessage()); } } }); } private void sendReport(){ PROFEPAPreferences prefs = new PROFEPAPreferences(getActivity()); ParseObject inspeccion = new ParseObject("Inspecciones"); inspeccion.put("Reporte", "Error"); inspeccion.put("Detalles", editReport.getText().toString()); inspeccion.put("Inspector", ParseObject.createWithoutData("Inspectores", prefs.getInspector())); inspeccion.put("Documentos", ParseObject.createWithoutData("Documentos", folio)); inspeccion.saveEventually(); Toast.makeText(getActivity(),R.string.toast_sent,Toast.LENGTH_LONG).show(); getActivity().onBackPressed(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package inputs; import edu.wpi.first.wpilibj.*; /** * * @author adam */ public class Driver { private final Joystick joy; private static final double YCENTER = 0.03125; private static final double ROTCENTER = 0.0156; private static final double XMIN = -0.641; private static final double XMAX = 0.648; private static final double YMIN = -0.57 - YCENTER; private static final double YMAX = 0.641 - YCENTER; private static final double ZMIN = -0.54; private static final double ZMAX = 0.63; private static final double ROTMIN = -0.64 - ROTCENTER; private static final double ROTMAX = 0.68 - ROTCENTER; private static final double XEXPO = 0.4; private static final double YEXPO = 0.4; private static final double ROTEXPO = 0.6; public Driver(Joystick joy) { this.joy = joy; } public double getY() { double y = normalize(joy.getAxis(Joystick.AxisType.kY) - YCENTER, YMIN, YMAX) * -1.0; y = expo(y, YEXPO); //System.out.print("y: " + y); return y; } public double getX() { double x = normalize(joy.getAxis(Joystick.AxisType.kX), XMIN, XMAX); x = expo(x, XEXPO); //System.out.print(" x: " + x); return x; } public double getZ() { // Invert the Z axis so that up on the stick is positive return normalize(joy.getAxis(Joystick.AxisType.kZ), ZMIN, ZMAX) * -1.0; } public double getRot() { double rot = normalize(joy.getRawAxis(5) - ROTCENTER, ROTMIN, ROTMAX) / 2.0; rot = expo(rot, ROTEXPO); //System.out.println(" rot: " + rot); return rot; } public boolean getRightSw() { return joy.getButton(Joystick.ButtonType.kTop); } public boolean getLeftSw() { return joy.getButton(Joystick.ButtonType.kTrigger); } // Normalize input values to -1.0 to 1.0 private double normalize(double joyVal, double min, double max) { double retVal = 0.0; if (joyVal < 0.0) retVal = Math.abs(joyVal) / min; else if (joyVal > 0.0) retVal = Math.abs(joyVal) / max; if (retVal < -1.0) retVal = -1.0; else if (retVal > 1.0) retVal = 1.0; return retVal; //return joyVal; } // Apply exponential function private double expo(double x, double a) { return (a * (x*x*x) + (1-a) * x); } }
package com.chad.baserecyclerviewadapterhelper; import android.graphics.Color; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import com.chad.baserecyclerviewadapterhelper.base.BaseActivity; import com.chad.library.adapter.base.BaseQuickAdapter; import java.util.List; /** * https://github.com/CymChad/BaseRecyclerViewAdapterHelper */ public abstract class BasePagingRefreshingActivity<T> extends BaseActivity { protected static final int REQUEST_LOAD_FIRST_PAGE = 1000; protected static final int REQUEST_LOAD_MORE_PAGE = 1001; protected static final int PAGE_SIZE = 6; protected RecyclerView mRecyclerView; protected SwipeRefreshLayout mSwipeRefreshLayout; protected BaseQuickAdapter mAdapter; private View noDataView; private View errorView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mRecyclerView = (RecyclerView) findViewById(R.id.rv_list); mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeLayout); mSwipeRefreshLayout.setColorSchemeColors(Color.rgb(47, 223, 189)); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); noDataView = getLayoutInflater().inflate(R.layout.empty_view, (ViewGroup) mRecyclerView.getParent(), false); noDataView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAdapter.setEmptyView(R.layout.loading_view, (ViewGroup) mRecyclerView.getParent()); refresh(); } }); errorView = getLayoutInflater().inflate(R.layout.error_view, (ViewGroup) mRecyclerView.getParent(), false); errorView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAdapter.setEmptyView(R.layout.loading_view, (ViewGroup) mRecyclerView.getParent()); refresh(); } }); initAdapter(); initRefreshLayout(); mSwipeRefreshLayout.setRefreshing(true); refresh(); } protected abstract BaseQuickAdapter getPullToRefreshAdapter(); private void initAdapter() { mAdapter = getPullToRefreshAdapter(); mAdapter.setHeaderFooterEmpty(true, true); mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() { @Override public void onLoadMoreRequested() { loadMore(); } }, mRecyclerView); // mAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT); // mAdapter.setPreLoadNumber(3); mRecyclerView.setAdapter(mAdapter); } private void initRefreshLayout() { mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { refresh(); } }); } protected abstract void fetchFirstPage(); protected abstract void fetchMorePage(); protected void handleFirstPageResponse(List<T> data) { setData(true, data); mAdapter.setEnableLoadMore(true); mSwipeRefreshLayout.setRefreshing(false); if (data.isEmpty()) { //显示暂无数据 mAdapter.setEmptyView(noDataView); } } protected void handleFirstPageError() { mAdapter.setEnableLoadMore(true); mSwipeRefreshLayout.setRefreshing(false); mAdapter.setEmptyView(errorView); } protected void handleMorePageResponse(List<T> data) { setData(false, data); } protected void handleMorePageError() { mAdapter.loadMoreFail(); } protected void refresh() { mAdapter.setEnableLoadMore(false);//这里的作用是防止下拉刷新的时候还可以上拉加载 fetchFirstPage(); } private void loadMore() { fetchMorePage(); } private void setData(boolean isRefresh, List data) { final int size = data == null ? 0 : data.size(); if (isRefresh) { mAdapter.resetData(data); } else { if (size > 0) { mAdapter.addData(data); } } if (size < PAGE_SIZE) { //第一页如果不够一页就不显示没有更多数据布局 mAdapter.loadMoreEnd(isRefresh); } else { mAdapter.loadMoreComplete(); } } }
// import java.io.*; // import java.util.*; // class Pair { // int height; // int quantity; // Pair(int height, int quantity) { // this.height = height; // this.quantity = quantity; // } // } // class baek__3015 { // public static void main(String[] args) throws IOException { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // int n = Integer.parseInt(br.readLine()); // int[] heights = new int[n]; // for (int i = 0; i < n; i++) { // heights[i] = Integer.parseInt(br.readLine()); // } // Stack<Pair> stack = new Stack<>(); // long answer = 0; // for (int i = 0; i < n; i++) { // if (stack.empty()) { // stack.add(new Pair(heights[i], 1)); // } else { // while (!stack.empty() && stack.peek().height < heights[i]) { // Pair now = stack.pop(); // answer += now.quantity; // } // if (stack.empty()) { // stack.add(new Pair(heights[i], 1)); // } else if (stack.peek().height == heights[i]) { // Pair now = stack.pop(); // answer += now.quantity; // if (!stack.empty()) { // answer += 1; // } // stack.add(new Pair(heights[i], now.quantity + 1)); // } else if (stack.peek().height > heights[i]) { // stack.add(new Pair(heights[i], 1)); // answer += 1; // } // } // } // System.out.print(answer); // } // }
package com.javarush.test.level10.lesson03.task01; public class Solution { int c = 10000; byte d = (byte) c; }
package ro.ase.csie.g1093.testpractice.decorator; public class DecoratorRanitCritic extends DecoratorACME{ public DecoratorRanitCritic(InterfataCaractereACMEForDecorator batman) { super(batman); } @Override public void esteAtacat(int puncte) { super.esteAtacat(puncte); if(this.erou.getPuncteViata() < 100) { System.out.println("Atentie! Este ranit critic"); } } }
package com.krish.iw; public class SortTwoArray { public static void main(String[] args) { int ar1[] = { 1, 5, 9, 10, 15, 20 }; int ar2[] = { 2, 3, 8, 13 }; sort(ar1, ar2); } private static void sort(int[] ar1, int[] ar2) { int len1 = ar1.length; int len2 = ar2.length; for (int i = len2-1; i >= 0; i--) { int j = 0; int last = ar1[len1 - 1]; for (j = len1 - 1; j >= 0 && ar1[j] > ar2[i]; j--) { ar1[j + 1] = ar1[j]; } if (j != len1 - 1) { ar1[j + 1] = ar2[i]; ar2[i] = last; } } for (int i : ar1) { System.out.print(ar1[i]); } System.out.println(""); for (int i : ar2) { System.out.print(ar2[i]); } } }
package studio.visualdust.product.screendark.gui.widgets.maincover.Clock; public class ClockConfig { private boolean dayPainted; private boolean hourPainted; private boolean minutePainted; private boolean secondPainted; public ClockConfig(boolean paintDay, boolean paintHour, boolean paintMinute, boolean paintSecond) { dayPainted = paintDay; hourPainted = paintHour; minutePainted = paintMinute; secondPainted = paintSecond; } public boolean isDayPainted() { return dayPainted; } public boolean isHourPainted() { return hourPainted; } public boolean isMinutePainted() { return minutePainted; } public boolean isSecondPainted() { return secondPainted; } }
package dao; public interface AP { /** * 接口和抽象类的区别 * 区别1: * 子类只能继承一个抽象类,不能继承多个 * 子类可以实现多个接口 * * 区别2: * 抽象类可以定义 * public,protected,package,private * 静态和非静态属性 * final和非final属性 * 但是接口中声明的属性,只能是 * public 静态 final的 * 即便没有显式的声明 * * 注: 抽象类和接口都可以有实体方法。 接口中的实体方法,叫做默认方法 */ String type = "法师"; default void attack() { System.out.println("attack"); }; void magicAttack(); static void main(String[] args) { } }
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.wizardpager.wizard.ui; import com.example.android.wizardpager.R; import com.example.android.wizardpager.wizard.model.MultipleFixedChoicePage; import com.example.android.wizardpager.wizard.model.Page; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.ListFragment; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class MultipleChoiceFragment extends ListFragment { private static final String ARG_KEY = "key"; private PageFragmentCallbacks mCallbacks; private String mKey; private List<String> mChoices; private Page mPage; public static MultipleChoiceFragment create(String key) { Bundle args = new Bundle(); args.putString(ARG_KEY, key); MultipleChoiceFragment fragment = new MultipleChoiceFragment(); fragment.setArguments(args); return fragment; } public MultipleChoiceFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args = getArguments(); mKey = args.getString(ARG_KEY); mPage = mCallbacks.onGetPage(mKey); MultipleFixedChoicePage fixedChoicePage = (MultipleFixedChoicePage) mPage; mChoices = new ArrayList<String>(); for (int i = 0; i < fixedChoicePage.getOptionCount(); i++) { mChoices.add(fixedChoicePage.getOptionAt(i)); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_page, container, false); ((TextView) rootView.findViewById(android.R.id.title)).setText(mPage.getTitle()); final ListView listView = (ListView) rootView.findViewById(android.R.id.list); setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_multiple_choice, android.R.id.text1, mChoices)); listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); // Pre-select currently selected items. new Handler().post(new Runnable() { @Override public void run() { ArrayList<String> selectedItems = mPage.getData().getStringArrayList( Page.SIMPLE_DATA_KEY); if (selectedItems == null || selectedItems.size() == 0) { return; } Set<String> selectedSet = new HashSet<String>(selectedItems); for (int i = 0; i < mChoices.size(); i++) { if (selectedSet.contains(mChoices.get(i))) { listView.setItemChecked(i, true); } } } }); return rootView; } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof PageFragmentCallbacks)) { throw new ClassCastException("Activity must implement PageFragmentCallbacks"); } mCallbacks = (PageFragmentCallbacks) activity; } @Override public void onDetach() { super.onDetach(); mCallbacks = null; } @Override public void onListItemClick(ListView l, View v, int position, long id) { SparseBooleanArray checkedPositions = getListView().getCheckedItemPositions(); ArrayList<String> selections = new ArrayList<String>(); for (int i = 0; i < checkedPositions.size(); i++) { if (checkedPositions.valueAt(i)) { selections.add(getListAdapter().getItem(checkedPositions.keyAt(i)).toString()); } } mPage.getData().putStringArrayList(Page.SIMPLE_DATA_KEY, selections); mPage.notifyDataChanged(); } }
/* * 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 CollectionFun; import java.util.ArrayList; import java.util.Collection; /** * * @author YNZ */ public class Question2 { public static void main(String[] args) { Collection<String> coll = new ArrayList<>(); coll.add("Fred"); coll.add("Jim"); coll.add("Sheila"); System.out.println("coll is " + coll); if (coll.contains("Fred")) { coll.remove("Fred"); } System.out.println("coll is " + coll); } }
public class FileTest { //test for web directory list fault public static void main(String[] args) { } }
package com.example.qunxin.erp.modle; //ShangpinDatus import java.io.Serializable; public class ZhanghuDatus implements Serializable { private String acName; private int imgRes; private String bankName; private String amount; private String id; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getAcName() { return acName; } public void setAcName(String acName) { this.acName = acName; } public int getImgRes() { return imgRes; } public void setImgRes(int imgRes) { this.imgRes = imgRes; } public String getBankName() { return bankName; } public void setBankName(String bankName) { this.bankName = bankName; } public String getAmount() { return amount; } public void setAmount(String amount) { this.amount = amount; } }
package yo.estructura_de_datos; import java.util.Collections; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Scanner; import javax.swing.*; import static yo.estructura_de_datos.val.edad; import static yo.estructura_de_datos.val.esletras; import static yo.estructura_de_datos.val.nombre; import static yo.estructura_de_datos.val.numerito; import static yo.estructura_de_datos.val.numerito2; public class Equipo { public static void main (String [ ] args){ int cons=3; nino[] equipo=new nino[cons]; for(int i=0;i<cons;i++){ equipo[i]=new nino(); } Scanner s=new Scanner(System.in); int cont=0; boolean n=true; char op; String aux; String aux2; Double d; int aux_int; do { System.out.println("[1] Registrar a un miembro del equipo miembros enlistados: " + cont); System.out.println("[2] mostrar equipo"); System.out.println("[3] Salir"); op=s.next(). charAt(0); switch(op) { case '1': if(cont<cons){ aux=JOptionPane.showInputDialog(null,"dame el nombre(s) del niñ@"); aux=aux.toUpperCase(); if(nombre(aux)==false){ JOptionPane.showMessageDialog(null, "te equivocaste al escribir el nombre my dude"); break; } equipo[cont].setNombre(aux); aux=JOptionPane.showInputDialog(null,"dame el apellido paterno del niñ@"); aux=aux.toUpperCase(); if(esletras(aux)==false){ JOptionPane.showMessageDialog(null, "te equivocaste al escribir el apellido my dude"); break; } equipo[cont].setApellido_paterno(aux); aux=JOptionPane.showInputDialog(null,"dame el apellido materno del niñ@"); aux=aux.toUpperCase(); if(esletras(aux)==false){ JOptionPane.showMessageDialog(null, "te equivocaste al escribir el apellido my dude"); break; } equipo[cont].setApellido_materno(aux); aux=JOptionPane.showInputDialog(null,"dame la posicion del niñ@"); if(esletras(aux)==false){ JOptionPane.showMessageDialog(null, "te equivocaste al escribir la posicion my dude"); break; } equipo[cont].setPosicion(aux); aux=(JOptionPane.showInputDialog(null,"dame la edad del niñ@ [5-12]")); if(numerito(aux)==false){ JOptionPane.showMessageDialog(null, "te equivocaste al escribir la edad my dude"); break; } if(edad(aux)==false){ JOptionPane.showMessageDialog(null, "te equivocaste al escribir la edad my dude"); break; } else{ d=Double.parseDouble(aux); } equipo[cont].setEdad(d); aux=(JOptionPane.showInputDialog(null,"dame el peso del niñ@ [en kilos ejemplo: 45.50]")); if(numerito(aux)==false){ JOptionPane.showMessageDialog(null, "te equivocaste al escribir el peso my dude"); break; } else{ d=Double.parseDouble(aux); } equipo[cont].setPeso(d); aux=(JOptionPane.showInputDialog(null,"dame la estatura del niñ@ (en metros)")); if(numerito(aux)==false){ JOptionPane.showMessageDialog(null, "te equivocaste al escribir la estatura my dude"); break; } else{ d=Double.parseDouble(aux); } equipo[cont].setEstatura(d); aux=(JOptionPane.showInputDialog(null,"dame el numero de telefono del niñ@")); if(numerito2(aux)==false){ JOptionPane.showMessageDialog(null, "te equivocaste al escribir el numeero de telefono my dude"); break; } else{ } equipo[cont].setTelefono(aux); cont++; } else{ JOptionPane.showMessageDialog(null, "ya ingresaste a todos los integrantes del equipo"); } break; case '2': if(cont==cons){ //aca pasa la magia ArrayList<nino> lista = new ArrayList<nino>(); for(int k=0;k<cons;k++){ lista.add(equipo[k]); } Collections.sort(lista); //aqui termina la magia for(int k=0;k<cons;k++){ System.out.printf("\nNombre: %s %s %s \n",lista.get(k).getNombre(),lista.get(k).getApellido_paterno(),lista.get(k).getApellido_materno()); System.out.printf("Posición: %s \n",lista.get(k).getPosicion()); System.out.printf("Edad: %f \n",lista.get(k).getEdad()); System.out.printf("Peso: %f \n",lista.get(k).getPeso()); System.out.printf("Estatura: %f \n",lista.get(k).getEstatura()); System.out.printf("Estatura: %s \n",lista.get(k).getTelefono()); } } else{ JOptionPane.showMessageDialog(null, "aun no ingresas todos los integrantes del equipo my dude"); } break; case '3': System.exit(0); break; default: System.out.println("ERROR: por favor ingresa un dato valido"); } }while(n); } } class nino implements Comparable<nino>{ nino(){ } public String nombre; public String apellido_paterno; public String apellido_materno; public String posicion; public double edad; public double peso; public double estatura; public String telefono; public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getApellido_paterno() { return apellido_paterno; } public void setApellido_paterno(String apellido_paterno) { this.apellido_paterno = apellido_paterno; } public String getApellido_materno() { return apellido_materno; } public void setApellido_materno(String apellido_materno) { this.apellido_materno = apellido_materno; } public String getPosicion() { return posicion; } public void setPosicion(String posicion) { this.posicion = posicion; } public double getEdad() { return edad; } public void setEdad(double edad) { this.edad = edad; } public double getPeso() { return peso; } public void setPeso(double peso) { this.peso = peso; } public double getEstatura() { return estatura; } public void setEstatura(double estatura) { this.estatura = estatura; } public String getTelefono() { return telefono; } public void setTelefono(String telefono) { this.telefono = telefono; } @Override public int compareTo(nino o) { int comparaint= nombre.compareTo(o.nombre); if(comparaint<0){ return -1; } if(comparaint>0){ return 1; } return 0; } } class val { val(){ } public static boolean esletras(String str) { return ((str != null) && (!str.equals("")) && (str.matches("^[A-Za-zñÑáéíóúÁÉÍÓÚ]*$"))); } public static boolean numerito(String Num) { if (Num == null) { return false; } try { double d = Double.parseDouble(Num); } catch (NumberFormatException nfe) { return false; } return true; } public static boolean numerito2(String str) { return ((str != null) && (!str.equals("")) && (str.matches("^[0-9]*$"))); } public static boolean nombre(String str) { return ((str != null) && (!str.equals("")) && (str.matches("^[A-Za-zñÑáéíóúÁÉÍÓÚ ]*$"))); } public static boolean edad(String str){ if(Integer.parseInt(str)<5){ return false; } if(Integer.parseInt(str)>12){ return false; } return true; } }
package ur.api_ur.api_data_obj.news; /** * Created by redjack on 15/9/22. */ public class URNewsRotateObj { /** * 輪播模式, 1:外部LINK, 用inapp browser開啟, 2: NEWSID, 直接開啟內容. */ public int rotate_type = 0; /** rorate_type=1 */ public String rotate_link; /** rorate_type=2*/ public String news_id; /** 大圖URL, ex:http://gt4g.com/1234.png */ public String news_pic; /** HTML */ public String news_body; /** 最新消息-title */ public String title; /** 發布日期 (只有新聞懶人包要顯示在client端) */ public long pub_ts = 0; /** 1(cat), 2(keyword), 3(marked) */ public int news_type = 0; /** 分類, ex: 熱門Top10,常識懶人包... 等 */ public String news_cat; /** 次分類, ex: 輪胎,油品... 等 */ public String news_cat_su; /** 觀看次數 */ public long viewed = 0; /** 0未收藏, 1已收藏 */ public int mark = 0; /** 點擊的時候, 發一個 http get 到這個網址即可, 不用管後續 */ public String click_url; /** 當使用者看到時發一個 http get 到這個網址即可, 不用管後續 */ public String imp_url; /** 發一個 http get 到這個網址即可, (回傳1表成功收藏, 回傳0表收藏失敗, rawdata, 非json) */ public String mark_url; /** 發一個 http get 到這個網址即可, (回傳1表成功取消收藏, 回傳0表收藏失敗, rawdata, 非json) */ public String unmark_url; }
package edu.rit.cs.mining.registry; import edu.rit.cs.mining.Config; import java.net.ServerSocket; // change it to /** * This class is used to Listen for any heartbeat JsonRequests from other Miners. */ public class MinerHeartbeatsListener extends Thread { public Registry reg; public MinerHeartbeatsListener(Registry r) { reg = r; } /** * This method listens on a predefined port and when receives a request will launch a new thread to analyze the request and * starts hearing again. */ public void run() { try(ServerSocket serversocket = new ServerSocket(Config.MINER_Heartbeat_LISTNER_PORT)){ while(this.reg.isActive){ new JsonRpcNotificationBackend(serversocket.accept(), this.reg).start(); } }catch (Exception e){ System.out.println("error in Heart Listner!!!!!!!!!!!!!!"); System.exit(-1); } // try { // //ServerSocket servsocket = new ServerSocket(Config.MINER_Heartbeat_LISTNER_PORT); // //ServerSocket serversocket = null; // while (true) { // //// try{ //// s = new ServerSocket(Config.MINER_Heartbeat_LISTNER_PORT); //// new JsonRpcNotificationBackend(s.accept(), this.reg).start(); //// }catch (Exception e){ //// //// e.printStackTrace(); //// System.out.println(e.getMessage()); //// System.err.println("Could not listen on port " + Config.MINER_Heartbeat_LISTNER_PORT +" in MinerHeatBeat"); //// System.exit(-5); //// } // // // //// ServerSocket serversocket = new ServerSocket(Config.MINER_Heartbeat_LISTNER_PORT); //// //// serversocket.setSoTimeout(5000); //// System.out.println("HeartBeat received in Listner"); //// new JsonRpcNotificationBackend(serversocket.accept(), this.reg).start(); // //serversocket.close(); // } // // // } catch (Exception e) { // // e.printStackTrace(); // System.out.println(e.getMessage()); // System.err.println("Could not listen on port " + Config.MINER_Heartbeat_LISTNER_PORT + " in MinerHeatBeat"); // System.exit(-5); // } } }
import java.util.Scanner; /* * Rename this class to Main! */ final class T1_Assignment1 { public static final String TEMPLATE_STRING = "Average website rating: %.15f\n" + "Average focus group rating: %.1f\n" + "Average movie critic rating: %.2f\n" + "Overall movie rating: %.14f"; public static void main(String[] args) { Scanner input = new Scanner(System.in); int[] rateReviewWeb = new int[3]; double[] rateFocusGroup = new double[2]; double avgCrtRating, avgWebRating, avgFGroupRating; System.out.println("Please enter ratings from the movie review website."); rateReviewWeb[0] = input.nextInt(); rateReviewWeb[1] = input.nextInt(); rateReviewWeb[2] = input.nextInt(); avgWebRating = (double) (((double) rateReviewWeb[0] + (double) rateReviewWeb[1] + (double) rateReviewWeb[2]) / 3); System.out.println("Please enter ratings from the focus group."); rateFocusGroup[0] = input.nextDouble(); rateFocusGroup[1] = input.nextDouble(); avgFGroupRating = (rateFocusGroup[0] + rateFocusGroup[1]) / 2; System.out.println("Please enter the average movie critic rating."); avgCrtRating = input.nextDouble(); // System.out.println(String.format(TEMPLATE_STRING, avgWebRating, // avgFGroupRating, avgCrtRating, // (avgWebRating*0.20)+(avgFGroupRating*0.30)+(0.5*avgCrtRating))); // WHY IS THIS BROKEN System.out.println( "Average website rating: " + avgWebRating + "\nAverage focus group rating: " + avgFGroupRating + "\nAverage movie critic rating: " + avgCrtRating + "\nOverall movie rating: " + ((avgWebRating * 0.20) + (avgFGroupRating * 0.30) + (0.5 * avgCrtRating)) ); input.close(); } }
package com.bnrc.util.collectwifi; import java.util.List; import java.util.Map; import com.bnrc.busapp.R; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.TextView; import android.widget.Toast; public class MyDialogReadWifi extends Dialog implements android.view.View.OnClickListener { private Context context; private ListView readList; // private ItemDialogListener listener; private List<Map<String, String>> LocalSave; private MyReadDialogAdapter readAdapter; // interface ItemDialogListener { // public void onClick(View view); // } public MyDialogReadWifi(Context context) { // TODO Auto-generated constructor stub super(context); // TODO Auto-generated constructor stub this.context = context; } public MyDialogReadWifi(Context context, int theme, List<Map<String, String>> LocalSave) { // TODO Auto-generated constructor stub super(context, theme); // TODO Auto-generated constructor stub this.context = context; // this.listener = listener; this.LocalSave = LocalSave; } private void initView() { readList = (ListView) findViewById(R.id.dialog_readwifi_list); readAdapter = new MyReadDialogAdapter(context, LocalSave); readList.setAdapter(readAdapter); } @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); this.setContentView(R.layout.dialog_readwifi); initView(); } public void onClick(View view) { // if (view.getId() == R.id.submit) { // Toast.makeText(context, "success!", Toast.LENGTH_LONG).show(); // dismiss(); // } } }
package MachineLearning; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; public class MLDataModifier { public static void main(String args[]) throws IOException{ ArrayList<String> types = new ArrayList<String>(); types.add("rain"); types.add("eq"); types.add("dosha"); for(String type : types){ ArrayList<String> subjects = new ArrayList<String>(); subjects.add("tsukin_time_diff"); subjects.add("office_time_diff"); subjects.add("kitaku_time_diff"); subjects.add("home_exit_diff"); subjects.add("home_return_diff"); subjects.add("office_enter_diff"); subjects.add("office_exit_diff"); for(String subject : subjects){ String in = "/home/c-tyabe/Data/MLResults_"+type+"/"+subject+"_ML_no2.csv"; String in2 = "/home/c-tyabe/Data/MLResults_"+type+"/"+subject+"_ML_lineforeach2.csv"; String newoutfile = "/home/c-tyabe/Data/MLResults_"+type+"/"+subject+"_ML_no3.csv"; String newoutfile2 = "/home/c-tyabe/Data/MLResults_"+type+"/"+subject+"_ML_lineforeach3.csv"; DeleteBisho(new File(in), new File(newoutfile)); DeleteBisho(new File(in2), new File(newoutfile2)); // String multiplelines = "/home/c-tyabe/Data/MLResults_"+type+"/"+subject+"_ML_lineforeach2.csv"; // MLDataModifier.Modify(new File(in), new File(multiplelines)); } } } public static void Modify(File in, File out) throws IOException{ BufferedReader br = new BufferedReader(new FileReader(in)); BufferedWriter bw = new BufferedWriter(new FileWriter(out)); String line = null; while((line=br.readLine())!=null){ String[] tokens = line.split(" "); Double y = Double.parseDouble(tokens[0]); Integer numoflines = numofline(y); for(int i = 0; i<numoflines; i++){ bw.write(line); bw.newLine(); } } br.close(); bw.close(); } public static int numofline(Double num){ double num2 = Math.abs(num); int res = 0; if(num2<10){ res = (int)Math.round(num2); if(res==0){ res = 1; } } else if(num2>=10){ res = 10; } else{ res = 0; } return res; } public static void DeleteBisho(File in, File out) throws IOException{ BufferedReader br = new BufferedReader(new FileReader(in)); BufferedWriter bw = new BufferedWriter(new FileWriter(out)); String line = null; while((line=br.readLine())!=null){ ArrayList<String> temp = new ArrayList<String>(); String[] tokens = line.split(" "); for(String token: tokens){ if(token.split(":").length==2){ if(!token.split(":")[1].contains("E")){ temp.add(token); } } else{ temp.add(token); } } for(String t : temp){ bw.write(t+" "); } bw.newLine(); } br.close(); bw.close(); } }
package com.example.knkapp; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.util.Patterns; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.HashMap; public class DangkiActivity extends AppCompatActivity { // khai báo button và edittext EditText EditEmail, EditPassword; Button btnDangki; TextView txtYesaccount; // khai báo sử dụng hộp thoại ProgressDialog progressDialog ; //Khai báo một thể hiện của Firebase Auth private FirebaseAuth mAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dangki); // tạo thanh tiêu đề dùng actionbar ActionBar actionBar = getSupportActionBar(); actionBar.setTitle("Tạo tài khoản"); // bật nút quay lại actionBar.setDisplayHomeAsUpEnabled(true); // hiển thị trang chủ actionBar.setDisplayShowCustomEnabled(true); // hiển thị chế độ tùy chỉnh // gọi id từ view EditEmail = findViewById(R.id.Edit_Demail_id); EditPassword= findViewById(R.id.Edit_Dpassword_id); btnDangki = findViewById(R.id.btn_Ddangki_id); txtYesaccount= findViewById(R.id.txt_Dyesaccount_id); //Trong phương thức onCreate (), khởi tạo thể hiện FirebaseAuth. mAuth = FirebaseAuth.getInstance(); progressDialog = new ProgressDialog(this); progressDialog.setMessage("Đăng kí người dùng..."); btnDangki.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // nhập tài khoản , mật khẩu String email= EditEmail.getText().toString().trim(); String password = EditPassword.getText().toString().trim(); if(!Patterns.EMAIL_ADDRESS.matcher(email).matches()){ // set lỗi EditEmail.setError("Email không hợp lệ "); EditEmail.setFocusable(true); }else if(password.length()<6){ EditPassword.setError("Mật khẩu phải dài hơn 6 kí tự "); EditPassword.setFocusable(true); }else { registerUser(email,password); } } }); // xử lý sự kiện nếu đã có tài khoản, chuyển đến trang đăng nhập txtYesaccount.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(DangkiActivity.this,DangnhapActivity.class)); finish(); } }); } private void registerUser(String email, String password) { // tài khoản và mật khẩu hợp lệ, bắt đầu đăng nhập use progressDialog.show(); mAuth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success. progressDialog.dismiss(); FirebaseUser user = mAuth.getCurrentUser(); // Lấy email người dùng và id của auth String email= user.getEmail(); String uid= user.getUid(); //Khi người dùng đâng kí, thông tin người dùng được lưu trữ theo thời gian thực // sử dụng hashMap HashMap<Object, String> hashMap= new HashMap<>(); // đưa thông tin vào HashMap hashMap.put("email",email); // email người dùng hashMap.put("uid",uid); // id người dùng hashMap.put("name","");// sẽ thêm sao hashMap.put("phone",""); // sdt người dùng // cơ sở dữ liệu của firebase FirebaseDatabase firebaseDatabase= FirebaseDatabase.getInstance(); // đường dẫn lưu trữ dữ liệu người dùng có tên "Users" DatabaseReference reference= firebaseDatabase.getReference("Users"); // đưa dữ liệu vào hàm Hashmap trong csdl reference.child(uid).setValue(hashMap); Toast.makeText(DangkiActivity.this, "Đăng kí tài khoản "+user.getEmail()+" thành công !", Toast.LENGTH_SHORT).show(); startActivity(new Intent(DangkiActivity.this, BangDieuKhienActivity.class)); finish(); } else { // If sign in fails, display a message to the user. progressDialog.dismiss(); Toast.makeText(DangkiActivity.this, "Lỗi tạo tài khoản !", Toast.LENGTH_SHORT).show(); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // lỗi , bỏ qua tiến trình và hiển thị hộp thoại lỗi (project này của Trần Đăng khoa) progressDialog.dismiss(); Toast.makeText(DangkiActivity.this," Địa chỉ gmail "+EditEmail.getText().toString()+" đã có người sử dụng !"/*+e.getMessage()*/,Toast.LENGTH_SHORT).show(); } }); } @Override public boolean onSupportNavigateUp() { onBackPressed(); // đi đến activity trước return super.onSupportNavigateUp(); } }
package com.notthemostcommon.creditcardpayoff.Debts; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface DebtRepository extends JpaRepository<Debt, Long> { List<Debt> findAllById(Long id); List<Debt> findByAppUserId(Long userId); }
package org.example.codingtest.a_real_test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Test2 { private static final Test2 o = new Test2(); public static void main(String[] args) { String[] card = {"ABACDEFG", "NOPQRSTU", "HIJKLKMM"}; String[] word = {"GPQM", "GPMZ", "EFU", "MMNA"}; String[] solution = o.solution(card, word); Arrays.stream(solution).forEach(System.out::println); } public String[] solution(String[] card, String[] word) { String[] answer = {}; List<String> list = new ArrayList<>(); int m = card.length; int n = card[0].length(); boolean[][] isVisited = new boolean[m][n]; char[][] splitByCard = new char [m][n]; for (int i = 0; i < card.length; i++) { for (int j = 0; j < card[i].length(); j++) { char c = card[i].charAt(j); splitByCard[i][j] = c; } } for (int i = 0; i < word.length; i++) { if (!isValid(card, word[i])){ continue; } isVisited = new boolean[3][8]; if(isChecked(splitByCard, word[i], isVisited)){ list.add(word[i]); } } if (list.size()==0) return new String[]{"-1"}; answer = new String[list.size()]; for (int i = 0; i < list.size(); i++) { answer[i] = list.get(i); } return answer; } private boolean isChecked(char[][] splitByCard, String s, boolean[][] isVisited) { int cnt =0; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); for (int j = 0; j < splitByCard.length; j++) { for (int k = 0; k < splitByCard[j].length; k++) { if (!isVisited[j][k] && c == splitByCard[j][k]){ isVisited[j][k] = true; cnt++; break; } } } } if (cnt==s.length()){ //모두 찾아다는 뜻 (중복 포함) for (int i = 0; i < isVisited.length; i++) { boolean isFlag = false; for (int j = 0; j < isVisited[0].length; j++) { if (isVisited[i][j]) isFlag = true; } if (!isFlag) return false; } } else { return false; } return true; } // 전체 카드에 지정 문자가 하나라도 없는지 점검 boolean isValid(String[] card, String word){ for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); boolean isFlag = false; for (int j = 0; j < card.length; j++) { if (card[j].contains(String.valueOf(c))) isFlag = true; } if (!isFlag) return false; } return true; } }
package com.ccspace.facade.domain.common.util; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import org.apache.commons.codec.binary.Base64; import org.apache.http.*; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.config.ConnectionConfig; import org.apache.http.config.SocketConfig; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.TrustStrategy; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.SSLContext; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.nio.charset.CodingErrorAction; import java.security.GeneralSecurityException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * 功能说明:http协议控制器 * <p> 系统版本: v1.0<br> * 开发人员: luopeng12856 * 开发时间: 2016—05-26 上午10:12 <br> */ public class HttpClientUtil { private static final JsonNodeFactory factory = new JsonNodeFactory(false); private static Logger log = LoggerFactory.getLogger(HttpClientUtil.class); /** * 编码格式. */ public static final String CHARSET = "UTF-8"; /** * HTTP HEADER字段 Authorization应填充字符串Bearer */ public static final String BEARER = "Bearer "; /** * 环境 */ public static final String URL = "https://sandbox.hscloud.cn"; /** * 环境 */ public static final String OPENURL = "https://open.hscloud.cn"; /** * HTTP HEADER字段 Authorization应填充字符串BASIC */ public static final String BASIC = "Basic "; private static CloseableHttpClient httpClient = null; /** * 指客户端和服务器建立连接的timeout 毫秒 */ public final static int connectTimeout = 10000; /** * socket连接超时时间 客户端从服务器读取数据的timeout,超出后会抛出SocketTimeOutException */ public final static int socketTimeout = 10000; /** * 从连接池获取连接的timeout */ public final static int requestTimeout = 5000; /** * 允许管理器限制最大连接数 ,还允许每个路由器针对某个主机限制最大连接数。 */ public static PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); /** * 最大连接数 */ public final static int MAX_TOTAL_CONNECTIONS = 500; /** * 每个路由最大连接数 访问每个目标机器 算一个路由 默认 2个 */ public final static int MAX_ROUTE_CONNECTIONS = 80; private static RequestConfig requestConfig; private static final int MAX_TIMEOUT = 10000; static { cm.setDefaultMaxPerRoute(MAX_ROUTE_CONNECTIONS);// 设置最大路由数 cm.setMaxTotal(MAX_TOTAL_CONNECTIONS);// 最大连接数 /** * 大量的构造器设计模式,很多的配置都不建议直接new出来,而且相关的API也有所改动,例如连接参数, * 以前是直接new出HttpConnectionParams对象后通过set方法逐一设置属性, 现在有了构造器,可以通过如下方式进行构造: * SocketConfig.custom().setSoTimeout(100000).build(); */ SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true) .build(); cm.setDefaultSocketConfig(socketConfig); RequestConfig defaultRequestConfig = RequestConfig.custom() .setCookieSpec(CookieSpecs.BEST_MATCH) .setExpectContinueEnabled(true) .setStaleConnectionCheckEnabled(true).setRedirectsEnabled(true) .build(); // CodingErrorAction.IGNORE指示通过删除错误输入、向输出缓冲区追加 coder // 的替换值和恢复编码操作来处理编码错误的操作。 ConnectionConfig connectionConfig = ConnectionConfig.custom() .setCharset(Consts.UTF_8) .setMalformedInputAction(CodingErrorAction.IGNORE) .setUnmappableInputAction(CodingErrorAction.IGNORE).build(); //cm 连接manager默认的构造函数含有http https的注册机制 httpClient = HttpClients.custom().setConnectionManager(cm) .setDefaultRequestConfig(defaultRequestConfig) .setDefaultConnectionConfig(connectionConfig).build(); //用于httpPOST HttpGet的请求设置 RequestConfig.Builder configBuilder = RequestConfig.custom(); // 设置连接超时 configBuilder.setConnectTimeout(MAX_TIMEOUT); // 设置读取超时 configBuilder.setSocketTimeout(MAX_TIMEOUT); // 设置从连接池获取连接实例的超时 configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT); // 在提交请求之前 测试连接是否可用 configBuilder.setStaleConnectionCheckEnabled(true); requestConfig = configBuilder.build(); } public static String sendPost(String url, Map<String, String> params, String charSet, String charsetReturn, HttpHost proxy, String authorization, String interfacename) { try { HttpPost post = new HttpPost(url); RequestConfig.Builder builder = RequestConfig.custom(); if (proxy != null) { builder.setProxy(proxy); RequestConfig requestConfig = builder //与服务器连接超时时间:httpclient会创建一个异步线程用以创建socket连接, // 此处设置该socket的连接超时时间 .setSocketTimeout(socketTimeout) // 请求获取数据的超时时间(即响应时间),单位毫秒。 // 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。 .setConnectTimeout(connectTimeout) // 设置从connect Manager(连接池)获取Connection 超时时间,单位毫秒。 // 这个属性是新加的属性,因为目前版本是可以共享连接池的。 .setConnectionRequestTimeout(requestTimeout) .setExpectContinueEnabled(false) .setRedirectsEnabled(true).build(); post.setConfig(requestConfig); } post.setHeader("Content-Type", "application/x-www-form-urlencoded"); post.setHeader("Authorization", authorization); List<NameValuePair> nvps = new ArrayList<>(); StringBuffer sb = new StringBuffer(); if (params != null) { int n = 0; for (Entry<String, String> set : params.entrySet()) { if (n == 0) { n++; sb.append(set.getKey() + "=" + set.getValue()); } else { sb.append("&" + set.getKey() + "=" + set.getValue()); } nvps.add(new BasicNameValuePair(set.getKey(), set .getValue())); } } post.setEntity(new UrlEncodedFormEntity(nvps, charSet)); LogUtils.log("\n功能名称:" + interfacename + "\n" + "post url = [" + (url.endsWith("?") ? url : url + "?") + sb.toString() + "]", log); HttpResponse response = httpClient.execute(post); int status = response.getStatusLine().getStatusCode(); HttpEntity entity = null; try { entity = response.getEntity(); if (entity != null) { String result = EntityUtils.toString(entity, charsetReturn); LogUtils.log("result = " + result, log); return result; } else { return null; } } catch (Exception e) { LogUtils.log("HttpClient 请求 http状态码 status = [" + status + "] 获取HttpEntity ", e, log); throw new RuntimeException(e); } finally { if (entity != null) { entity.getContent().close(); } } } catch (ClientProtocolException e) { LogUtils.log("HttpClient 请求 ClientProtocolException ", e, log); throw new RuntimeException(e); } catch (IOException e) { LogUtils.log("HttpClient 请求 IOException ", e, log); throw new RuntimeException(e); } } public static String sendPost(String url, Map<String, String> params,Map<String, String> headerMap, HttpHost proxy) { try { HttpPost post = new HttpPost(url); initPostRequestConfig(post,proxy); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); post.setHeader("merchantId", headerMap.get("merchantId")); post.setHeader("userId", headerMap.get("userId")); List<NameValuePair> npList = organizeParamsAsNamePair(params); post.setEntity(new UrlEncodedFormEntity(npList, CHARSET)); HttpResponse response = httpClient.execute(post); int status = response.getStatusLine().getStatusCode(); HttpEntity entity = null; try { entity = response.getEntity(); if (entity != null) { String result = EntityUtils.toString(entity, CHARSET); LogUtils.log("result = " + result, log); return result; }else { return null; } } catch (Exception e) { LogUtils.error("HttpClient 请求 http状态码 status = [" + status + "] 获取HttpEntity ", e, log); throw new RuntimeException(e); } finally { if (entity != null) { entity.getContent().close(); } } } catch (ClientProtocolException e) { LogUtils.log("HttpClient 请求 ClientProtocolException ", e, log); throw new RuntimeException(e); } catch (IOException e) { LogUtils.log("HttpClient 请求 IOException ", e, log); throw new RuntimeException(e); } } /** * @description * @author CF create on 2018/7/4 18:28 */ public static String sendPost(String url, String contentType, StringEntity stringEntity, String charsetReturn, HttpHost proxy) { try { HttpPost post = new HttpPost(url); RequestConfig.Builder builder = RequestConfig.custom(); if (proxy != null) { builder.setProxy(proxy); RequestConfig requestConfig = builder .setSocketTimeout(socketTimeout) .setConnectTimeout(connectTimeout) .setConnectionRequestTimeout(requestTimeout) .setExpectContinueEnabled(false) .setRedirectsEnabled(true).build(); post.setConfig(requestConfig); } post.setHeader("Content-Type", contentType); post.setEntity(stringEntity); HttpResponse response = httpClient.execute(post); int status = response.getStatusLine().getStatusCode(); HttpEntity entity = null; try { entity = response.getEntity(); if (entity != null) { String result = EntityUtils.toString(entity, charsetReturn); LogUtils.log("result = " + result, log); return result; } else { return null; } } catch (Exception e) { LogUtils.log("HttpClient 请求 http状态码 status = [" + status + "] 获取HttpEntity ", e, log); throw new RuntimeException(e); } finally { if (entity != null) { entity.getContent().close(); } } } catch (ClientProtocolException e) { LogUtils.log("HttpClient 请求 ClientProtocolException ", e, log); throw new RuntimeException(e); } catch (IOException e) { LogUtils.log("HttpClient 请求 IOException ", e, log); throw new RuntimeException(e); } } /** * get请求 * * @param url * @param params * @param charSet * @return */ public static String sendGet(String url, Map<String, String> params, String charSet, HttpHost proxy, String authorization, String interfacename) { try { StringBuffer urlbuf = new StringBuffer(url); if (params != null) { int n = 0; for (Entry<String, String> set : params.entrySet()) { if (!urlbuf.toString().contains("?")) { urlbuf.append("?"); } if (n != 0) { urlbuf.append("&"); } urlbuf.append(set.getKey()).append("=") .append(set.getValue()); n++; } } // LogUtils.log("\n功能名称:" + interfacename + "\n" + "post url = [" + urlbuf.toString() + "]", log); HttpGet get = new HttpGet(urlbuf.toString()); get.setHeader("Content-Type", "application/x-www-form-urlencoded"); get.setHeader("Authorization", authorization); // HttpUriRequest get = new HttpGet(urlbuf.toString()); RequestConfig.Builder builder = RequestConfig.custom(); if (proxy != null) { builder.setProxy(proxy); } RequestConfig defaultConfig = builder .setSocketTimeout(socketTimeout) .setConnectTimeout(connectTimeout) .setConnectionRequestTimeout(requestTimeout) .setExpectContinueEnabled(false).setRedirectsEnabled(true) .build(); get.setConfig(defaultConfig); HttpResponse response = httpClient.execute(get); int status = response.getStatusLine().getStatusCode(); HttpEntity entity = null; try { entity = response.getEntity(); if (entity != null) { String result = EntityUtils.toString(entity, charSet); if (result.startsWith("Error")) { log.error("url is :" + urlbuf.toString()); log.error("result:" + result); log.error("status:" + status); } // LogUtils.log("result = " + result, log); return result; } else { return null; } } catch (Exception e) { LogUtils.error("HttpClient 请求 http状态码 status = [" + status + "] ", e, log); throw new RuntimeException(e); } finally { if (entity != null) { entity.getContent().close(); } } } catch (ClientProtocolException e) { LogUtils.error("HttpClient 请求 ClientProtocolException url=" + url + ",params=" + params, e, log); throw new RuntimeException(e); } catch (IOException e) { LogUtils.error("HttpClient 请求 IOException url=" + url + ",params=" + params, e, log); throw new RuntimeException(e); } } /** * cifangf 是对"App Key:App Secret"进行 Base64 编码后的字符串(区分大小写,包含冒号,但不包含双引号,采用 * UTF-8 编码)。 例如: Authorization: Basic eHh4LUtleS14eHg6eHh4LXNlY3JldC14eHg= * 其中App Key和App Secret可在开放平台上创建应用后获取。 */ public static String Base64(String appkey, String appsecret, String basic) throws UnsupportedEncodingException { String str = appkey + ":" + appsecret; byte[] encodeBase64 = Base64.encodeBase64(str .getBytes(HttpClientUtil.CHARSET)); LogUtils.log("\n功能名称:AppKey:AppSecret Base64编码" + "\n" + new String(encodeBase64), log); return basic + new String(encodeBase64); } public static class LogUtils { public static void log(String msg, Logger log) { /*System.out.println(msg);*/ log.info(msg); } public static void log(String msg, Exception e, Logger log) { /*System.out.println(msg + " 异常 message = [" + e.getMessage() + "]");*/ //log.info(msg + " 异常 message = [" + e.getMessage() + "]", e); } public static void error(String msg, Exception e, Logger log) { /*System.out.println(msg + " 异常 message = [" + e.getMessage() + "]");*/ log.error(msg + " 异常 message = [" + e.getMessage() + "]", e); } } public static CloseableHttpClient getCloseableClient() { return httpClient; } /** * 发送 SSL POST请(HTTPS),K-V形式 * * @param url * @param params * @author Charlie.chen */ public static String doPostSSL(String url, Map<String, Object> params) { /* CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConn()) .setConnectionManager(cm) .setDefaultRequestConfig(requestConfig).build();*/ HttpPost httpPost = new HttpPost(url); CloseableHttpResponse response = null; String httpStr = null; try { httpPost.setConfig(requestConfig); List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size()); for (Map.Entry<String, Object> entry : params.entrySet()) { NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry .getValue().toString()); pairList.add(pair); } httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("utf-8"))); response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { return null; } HttpEntity entity = response.getEntity(); if (entity == null) { return null; } httpStr = EntityUtils.toString(entity, "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { if (response != null) { try { EntityUtils.consume(response.getEntity()); } catch (IOException e) { e.printStackTrace(); } } } return httpStr; } /** * 创建SSL安全连接 * * @return * @author Charlie.chen */ private static SSLConnectionSocketFactory createSSLConn() { SSLConnectionSocketFactory sslsf = null; try { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }).build(); sslsf = new SSLConnectionSocketFactory( sslContext, new String[]{"TLS"},//v1.2 null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); } catch (GeneralSecurityException e) { e.printStackTrace(); } return sslsf; } /** * 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址; * * @param request * @return * @throws IOException */ public static String getIpAddress(HttpServletRequest request) { // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址 String ip = request.getHeader("X-Forwarded-For"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } } else if (ip.length() > 15) { String[] ips = ip.split(","); for (int index = 0; index < ips.length; index++) { String strIp = ips[index]; if (!("unknown".equalsIgnoreCase(strIp))) { ip = strIp; break; } } } return ip; } private static void initPostRequestConfig(HttpPost post,HttpHost proxy) { RequestConfig.Builder builder = RequestConfig.custom(); if (proxy != null) { builder.setProxy(proxy); RequestConfig requestConfig = builder .setSocketTimeout(socketTimeout) .setConnectTimeout(connectTimeout) .setConnectionRequestTimeout(requestTimeout) .setExpectContinueEnabled(false) .setRedirectsEnabled(true).build(); post.setConfig(requestConfig); } } private static List<NameValuePair> organizeParamsAsNamePair(Map<String, String> params) { List<NameValuePair> nvps = new ArrayList<>(); StringBuilder sb = new StringBuilder(); if (params != null) { int n = 0; for (Entry<String, String> set : params.entrySet()) { if (n == 0) { n++; sb.append(set.getKey()).append("=").append(set.getValue()); } else { sb.append("&").append(set.getKey()).append("=").append(set.getValue()); } nvps.add(new BasicNameValuePair(set.getKey(), set.getValue())); } } return nvps; } }
package com.jrz.bettingsite.team; import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; @RunWith(SpringJUnit4ClassRunner.class) @WebMvcTest(value = TeamController.class, secure = false) public class TeamControllerTest { @Autowired private MockMvc mockMvc; @MockBean private TeamService teamService; @Test public void findById() throws Exception { // before findById GET Team team = new Team((long) 1,"Real Madrid"); Mockito.when(teamService.findById(Mockito.anyLong())).thenReturn(Optional.ofNullable(team)); // during mockMvc.perform(MockMvcRequestBuilders.get("/teams/1") .contentType(MediaType.APPLICATION_JSON) ) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.is(1))) .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.is("Real Madrid"))) .andExpect(MockMvcResultMatchers.jsonPath("$.*",Matchers.hasSize(2))); //after Mockito.verify(teamService).findById(Mockito.anyLong()); } @Test public void findAll() throws Exception { // before findAll GET List<Team> teams = new ArrayList<Team>(Arrays.asList( new Team((long) 1,"Real Madrid"), new Team((long) 2,"Barcelona"), new Team((long) 3,"Athletico Madrid"))); Mockito.when(teamService.findAll()).thenReturn(teams); // during mockMvc.perform(MockMvcRequestBuilders.get("/teams") .contentType(MediaType.APPLICATION_JSON) ) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andExpect(MockMvcResultMatchers.jsonPath("$[0].id", Matchers.is(1))) .andExpect(MockMvcResultMatchers.jsonPath("$[0].name", Matchers.is("Real Madrid"))) .andExpect(MockMvcResultMatchers.jsonPath("$[0].*",Matchers.hasSize(2))) .andExpect(MockMvcResultMatchers.jsonPath("$[1].id", Matchers.is(2))) .andExpect(MockMvcResultMatchers.jsonPath("$[1].name", Matchers.is("Barcelona"))) .andExpect(MockMvcResultMatchers.jsonPath("$[1].*",Matchers.hasSize(2))) .andExpect(MockMvcResultMatchers.jsonPath("$[2].id", Matchers.is(3))) .andExpect(MockMvcResultMatchers.jsonPath("$[2].name", Matchers.is("Athletico Madrid"))) .andExpect(MockMvcResultMatchers.jsonPath("$[2].*",Matchers.hasSize(2))); // after Mockito.verify(teamService).findAll(); } @Test public void saveTeam() throws Exception { // before saveTeam POST Team team = new Team((long) 1,"Real Madrid"); String json = "{\n" + " \"id\": 1,\n" + " \"name\": \"Real Madrid\"\n" + "}"; Mockito.doNothing().when(teamService).saveTeam(Mockito.any(Team.class)); // during mockMvc.perform(MockMvcRequestBuilders.post("/teams") .contentType(MediaType.APPLICATION_JSON) .content(json) ) .andExpect(MockMvcResultMatchers.status().isOk()) //.andExpect(MockMvcResultMatchers.status().isCreated()) .andDo(MockMvcResultHandlers.print()); // after Mockito.verify(teamService).saveTeam(Mockito.any(Team.class)); } }
<% if (namespace || package) { %> package <% if (namespace) { %><%= namespace %><% } %><% if (package) { %><%= package %><% } %>;<% } %> import java.io.Serializable; import javax.faces.context.FacesContext;<% if (extlib) { %> import com.ibm.xsp.extlib.util.ExtLibUtil;<% } %> /** * <%= name %> class, configured as a managed bean in <%= scope %>. */ public class <%= name %> implements Serializable { private static final long serialVersionUID = 1L; private static final String myBeanName = "<%= camelName %>Bean"; public <%= name %>(){ // constructor intentionally left blank } public static <%= name %> getCurrentInstance(){ <% if (extlib) { %> return (<%= name %>) ExtLibUtil.resolveVariable(FacesContext.getCurrentInstance(), <%= name %>.myBeanName); <% } -%><% if (!extlib) { %> return (<%= name %>) FacesContext.getCurrentInstance().getApplication().getVariableResolver().resolveVariable(FacesContext.getCurrentInstance(), <%= name %>.myBeanName); <% } -%> } }
package kr.ac.kopo.day17; //join public class ThreadMain03 { public static void main(String[] args) { ExtendsThread et = new ExtendsThread(); ImplementThread it = new ImplementThread(); Thread t = new Thread(it); System.out.println("감독을 시작합니다."); et.start(); t.start(); try { et.join();// 이거 때문에 얘를 포함하는 메인 스레드가 이놈이 종료하기 전까지 블럭이 돼. } catch (InterruptedException e) { e.printStackTrace(); } try { t.join();// 이거 때문에 얘를 포함하는 메인 스레드가 이놈이 종료하기 전까지 블럭이 돼. } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("감독을 종료합니다."); //순서상 감~종이 제일 마지막인거 같지만 //join이 없잖아? 제일 먼저 끝나는 놈이 바로 이놈이야. 그래서 얘를 가장 뒤로 보내려면 join을 써서 //위의 스레드 두개가 끝나기 전까지는 현재 메인 스레드가 실행되지 않게 한거야. } }
package com.designpattern.dp1simplefactory.v1; /** * 应用层代码需要依赖JavaCourse。 * 如果业务扩展,继续增加PythonCourse甚至 * 更多课程,那么客户端的依赖会变得越来越臃肿(要创建的Course对象会越来越多) */ public class Test { public static void main(String[] args) { ICourse course = new JavaCourse(); course.record(); } }
package com.gavrilov.controllers; import com.gavrilov.commons.Constant; import org.gavrilov.commons.PagerModel; import org.gavrilov.dto.CategoryDTO; import org.gavrilov.mappers.CategoryMapper; import org.gavrilov.mappers.MapperFactory; import org.gavrilov.service.CategoryService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.validation.Valid; import java.util.Optional; @Controller public class CategoryController { private final CategoryService categoryService; private CategoryMapper categoryMapper = MapperFactory.createMapper(CategoryMapper.class); @Autowired public CategoryController(CategoryService categoryService) { this.categoryService = categoryService; } @GetMapping(value = "/categories") public ModelAndView getCategories(@RequestParam("pageSize") Optional<Integer> pageSize, @RequestParam("page") Optional<Integer> page) { ModelAndView modelAndView = new ModelAndView(); int evalPageSize = pageSize.orElse(Constant.INITIAL_PAGE_SIZE); int evalPage = (page.orElse(0) < 1) ? Constant.INITIAL_PAGE : page.get() - 1; Page<CategoryDTO> categories = categoryService.getPagetOfCategory(PageRequest.of(evalPage, evalPageSize)); PagerModel pager = new PagerModel(categories.getTotalPages(), categories.getNumber(), Constant.BUTTONS_TO_SHOW); modelAndView.addObject("categories", categories); modelAndView.addObject("selectedPageSize", evalPageSize); modelAndView.addObject("pageSizes", Constant.PAGE_SIZES); modelAndView.addObject("pager", pager); modelAndView.setViewName("user/category/categories"); return modelAndView; } @GetMapping(value = "/createCategory") @PreAuthorize("hasRole('ROLE_ADMIN')") public ModelAndView getViewCreateCategory() { ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("categoryDTO", new CategoryDTO()); modelAndView.addObject("isEdit", false); modelAndView.setViewName("user/category/managementWorld"); return modelAndView; } @PostMapping(value = "/createCategory") @PreAuthorize("hasRole('ROLE_ADMIN')") public ModelAndView createCategory(@Valid CategoryDTO categoryDTO, BindingResult bindingResult) { ModelAndView modelAndView = new ModelAndView(); boolean exist = categoryService.isExist(categoryDTO.getNameCategory()); if (exist) { bindingResult.rejectValue("nameCategory", "error.category", "Такая категория уже существует"); } if (bindingResult.hasErrors()) { modelAndView.addObject("isEdit", false); modelAndView.setViewName("user/category/managementWorld"); } else { categoryService.saveCategory(categoryDTO);modelAndView.addObject("isEdit", false); modelAndView.addObject("categoryDTO", new CategoryDTO()); modelAndView.addObject("successMessage", "Категория успешно добавлена"); modelAndView.setViewName("user/category/managementWorld"); } return modelAndView; } @GetMapping(value = "/updateCategory/{id}") @PreAuthorize("hasRole('ROLE_ADMIN')") public ModelAndView updateWorld(@PathVariable Long id) { ModelAndView modelAndView = new ModelAndView(); CategoryDTO categoryDTO = categoryMapper.asCategoryDTO(categoryService.findById(id)); modelAndView.addObject("categoryDTO", categoryDTO); modelAndView.addObject("isEdit", true); modelAndView.setViewName("user/category/managementWorld"); return modelAndView; } @PutMapping(value = "/updateCategory") @PreAuthorize("hasRole('ROLE_ADMIN')") public ModelAndView updateWorld(@Valid CategoryDTO categoryDTO, BindingResult bindingResult) { ModelAndView modelAndView = new ModelAndView(); if (bindingResult.hasErrors()) { modelAndView.addObject("categoryDTO", categoryDTO); modelAndView.addObject("isEdit", true); modelAndView.setViewName("user/category/managementWorld"); } else { categoryService.updateCategory(categoryDTO); modelAndView.setViewName("redirect:/categories"); } return modelAndView; } @DeleteMapping(value = "/deleteCategory/{id}") @PreAuthorize("hasRole('ROLE_ADMIN')") public ModelAndView deleteCategory(@PathVariable Long id) { ModelAndView modelAndView = new ModelAndView(); categoryService.deleteCategory(id); modelAndView.setViewName("redirect:/categories"); return modelAndView; } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.http.codec.json; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.Arrays; import java.util.Collections; import java.util.Map; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import org.junit.jupiter.api.Test; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import org.springframework.core.ResolvableType; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.testfixture.codec.AbstractEncoderTests; import org.springframework.http.MediaType; import org.springframework.http.codec.ServerSentEvent; import org.springframework.http.codec.json.JacksonViewBean.MyJacksonView1; import org.springframework.http.codec.json.JacksonViewBean.MyJacksonView3; import org.springframework.http.converter.json.MappingJacksonValue; import org.springframework.util.MimeType; import org.springframework.util.MimeTypeUtils; import org.springframework.web.testfixture.xml.Pojo; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.springframework.http.MediaType.APPLICATION_JSON; import static org.springframework.http.MediaType.APPLICATION_NDJSON; import static org.springframework.http.MediaType.APPLICATION_OCTET_STREAM; import static org.springframework.http.MediaType.APPLICATION_STREAM_JSON; import static org.springframework.http.MediaType.APPLICATION_XML; import static org.springframework.http.codec.json.Jackson2CodecSupport.JSON_VIEW_HINT; /** * @author Sebastien Deleuze */ public class Jackson2JsonEncoderTests extends AbstractEncoderTests<Jackson2JsonEncoder> { public Jackson2JsonEncoderTests() { super(new Jackson2JsonEncoder()); } @Override @Test @SuppressWarnings("deprecation") public void canEncode() { ResolvableType pojoType = ResolvableType.forClass(Pojo.class); assertThat(this.encoder.canEncode(pojoType, APPLICATION_JSON)).isTrue(); assertThat(this.encoder.canEncode(pojoType, APPLICATION_NDJSON)).isTrue(); assertThat(this.encoder.canEncode(pojoType, APPLICATION_STREAM_JSON)).isTrue(); assertThat(this.encoder.canEncode(pojoType, null)).isTrue(); assertThat(this.encoder.canEncode(ResolvableType.forClass(Pojo.class), new MediaType("application", "json", StandardCharsets.UTF_8))).isTrue(); assertThat(this.encoder.canEncode(ResolvableType.forClass(Pojo.class), new MediaType("application", "json", StandardCharsets.US_ASCII))).isTrue(); assertThat(this.encoder.canEncode(ResolvableType.forClass(Pojo.class), new MediaType("application", "json", StandardCharsets.ISO_8859_1))).isFalse(); // SPR-15464 assertThat(this.encoder.canEncode(ResolvableType.NONE, null)).isTrue(); // SPR-15910 assertThat(this.encoder.canEncode(ResolvableType.forClass(Object.class), APPLICATION_OCTET_STREAM)).isFalse(); } @Override @Test @SuppressWarnings("deprecation") public void encode() throws Exception { Flux<Object> input = Flux.just(new Pojo("foo", "bar"), new Pojo("foofoo", "barbar"), new Pojo("foofoofoo", "barbarbar")); testEncodeAll(input, ResolvableType.forClass(Pojo.class), APPLICATION_STREAM_JSON, null, step -> step .consumeNextWith(expectString("{\"foo\":\"foo\",\"bar\":\"bar\"}\n")) .consumeNextWith(expectString("{\"foo\":\"foofoo\",\"bar\":\"barbar\"}\n")) .consumeNextWith(expectString("{\"foo\":\"foofoofoo\",\"bar\":\"barbarbar\"}\n")) .verifyComplete() ); } @Test // SPR-15866 public void canEncodeWithCustomMimeType() { MimeType textJavascript = new MimeType("text", "javascript", StandardCharsets.UTF_8); Jackson2JsonEncoder encoder = new Jackson2JsonEncoder(new ObjectMapper(), textJavascript); assertThat(encoder.getEncodableMimeTypes()).isEqualTo(Collections.singletonList(textJavascript)); } @Test public void encodableMimeTypesIsImmutable() { MimeType textJavascript = new MimeType("text", "javascript", StandardCharsets.UTF_8); Jackson2JsonEncoder encoder = new Jackson2JsonEncoder(new ObjectMapper(), textJavascript); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> encoder.getMimeTypes().add(new MimeType("text", "ecmascript"))); } @Test public void canNotEncode() { assertThat(this.encoder.canEncode(ResolvableType.forClass(String.class), null)).isFalse(); assertThat(this.encoder.canEncode(ResolvableType.forClass(Pojo.class), APPLICATION_XML)).isFalse(); ResolvableType sseType = ResolvableType.forClass(ServerSentEvent.class); assertThat(this.encoder.canEncode(sseType, APPLICATION_JSON)).isFalse(); } @Test public void encodeNonStream() { Flux<Pojo> input = Flux.just( new Pojo("foo", "bar"), new Pojo("foofoo", "barbar"), new Pojo("foofoofoo", "barbarbar") ); testEncode(input, Pojo.class, step -> step .consumeNextWith(expectString("[{\"foo\":\"foo\",\"bar\":\"bar\"}")) .consumeNextWith(expectString(",{\"foo\":\"foofoo\",\"bar\":\"barbar\"}")) .consumeNextWith(expectString(",{\"foo\":\"foofoofoo\",\"bar\":\"barbarbar\"}")) .consumeNextWith(expectString("]")) .verifyComplete()); } @Test public void encodeNonStreamEmpty() { testEncode(Flux.empty(), Pojo.class, step -> step .consumeNextWith(expectString("[")) .consumeNextWith(expectString("]")) .verifyComplete()); } @Test // gh-29038 void encodeNonStreamWithErrorAsFirstSignal() { String message = "I'm a teapot"; Flux<Object> input = Flux.error(new IllegalStateException(message)); Flux<DataBuffer> output = this.encoder.encode( input, this.bufferFactory, ResolvableType.forClass(Pojo.class), null, null); StepVerifier.create(output).expectErrorMessage(message).verify(); } @Test public void encodeWithType() { Flux<ParentClass> input = Flux.just(new Foo(), new Bar()); testEncode(input, ParentClass.class, step -> step .consumeNextWith(expectString("[{\"type\":\"foo\"}")) .consumeNextWith(expectString(",{\"type\":\"bar\"}")) .consumeNextWith(expectString("]")) .verifyComplete()); } @Test // SPR-15727 public void encodeStreamWithCustomStreamingType() { MediaType fooMediaType = new MediaType("application", "foo"); MediaType barMediaType = new MediaType("application", "bar"); this.encoder.setStreamingMediaTypes(Arrays.asList(fooMediaType, barMediaType)); Flux<Pojo> input = Flux.just( new Pojo("foo", "bar"), new Pojo("foofoo", "barbar"), new Pojo("foofoofoo", "barbarbar") ); testEncode(input, ResolvableType.forClass(Pojo.class), barMediaType, null, step -> step .consumeNextWith(expectString("{\"foo\":\"foo\",\"bar\":\"bar\"}\n")) .consumeNextWith(expectString("{\"foo\":\"foofoo\",\"bar\":\"barbar\"}\n")) .consumeNextWith(expectString("{\"foo\":\"foofoofoo\",\"bar\":\"barbarbar\"}\n")) .verifyComplete() ); } @Test public void fieldLevelJsonView() { JacksonViewBean bean = new JacksonViewBean(); bean.setWithView1("with"); bean.setWithView2("with"); bean.setWithoutView("without"); Mono<JacksonViewBean> input = Mono.just(bean); ResolvableType type = ResolvableType.forClass(JacksonViewBean.class); Map<String, Object> hints = singletonMap(JSON_VIEW_HINT, MyJacksonView1.class); testEncode(input, type, null, hints, step -> step .consumeNextWith(expectString("{\"withView1\":\"with\"}")) .verifyComplete() ); } @Test public void classLevelJsonView() { JacksonViewBean bean = new JacksonViewBean(); bean.setWithView1("with"); bean.setWithView2("with"); bean.setWithoutView("without"); Mono<JacksonViewBean> input = Mono.just(bean); ResolvableType type = ResolvableType.forClass(JacksonViewBean.class); Map<String, Object> hints = singletonMap(JSON_VIEW_HINT, MyJacksonView3.class); testEncode(input, type, null, hints, step -> step .consumeNextWith(expectString("{\"withoutView\":\"without\"}")) .verifyComplete() ); } @Test public void jacksonValue() { JacksonViewBean bean = new JacksonViewBean(); bean.setWithView1("with"); bean.setWithView2("with"); bean.setWithoutView("without"); MappingJacksonValue jacksonValue = new MappingJacksonValue(bean); jacksonValue.setSerializationView(MyJacksonView1.class); ResolvableType type = ResolvableType.forClass(MappingJacksonValue.class); testEncode(Mono.just(jacksonValue), type, null, Collections.emptyMap(), step -> step .consumeNextWith(expectString("{\"withView1\":\"with\"}")) .verifyComplete() ); } @Test // gh-28045 public void jacksonValueUnwrappedBeforeObjectMapperSelection() { JacksonViewBean bean = new JacksonViewBean(); bean.setWithView1("with"); bean.setWithView2("with"); bean.setWithoutView("without"); MappingJacksonValue jacksonValue = new MappingJacksonValue(bean); jacksonValue.setSerializationView(MyJacksonView1.class); ResolvableType type = ResolvableType.forClass(MappingJacksonValue.class); MediaType halMediaType = MediaType.parseMediaType("application/hal+json"); ObjectMapper mapper = new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, true); this.encoder.registerObjectMappersForType(JacksonViewBean.class, map -> map.put(halMediaType, mapper)); String ls = System.lineSeparator(); // output below is different between Unix and Windows testEncode(Mono.just(jacksonValue), type, halMediaType, Collections.emptyMap(), step -> step .consumeNextWith(expectString("{" + ls + " \"withView1\" : \"with\"" + ls + "}") ) .verifyComplete() ); } @Test // gh-22771 public void encodeWithFlushAfterWriteOff() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.FLUSH_AFTER_WRITE_VALUE, false); Jackson2JsonEncoder encoder = new Jackson2JsonEncoder(mapper); Flux<DataBuffer> result = encoder.encode(Flux.just(new Pojo("foo", "bar")), this.bufferFactory, ResolvableType.forClass(Pojo.class), MimeTypeUtils.APPLICATION_JSON, Collections.emptyMap()); StepVerifier.create(result) .consumeNextWith(expectString("[{\"foo\":\"foo\",\"bar\":\"bar\"}")) .consumeNextWith(expectString("]")) .expectComplete() .verify(Duration.ofSeconds(5)); } @Test public void encodeAscii() { Mono<Object> input = Mono.just(new Pojo("foo", "bar")); MimeType mimeType = new MimeType("application", "json", StandardCharsets.US_ASCII); testEncode(input, ResolvableType.forClass(Pojo.class), mimeType, null, step -> step .consumeNextWith(expectString("{\"foo\":\"foo\",\"bar\":\"bar\"}")) .verifyComplete() ); } @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") private static class ParentClass { } @JsonTypeName("foo") private static class Foo extends ParentClass { } @JsonTypeName("bar") private static class Bar extends ParentClass { } }