text
stringlengths
10
2.72M
package by.epam.jb25.day1; public class Task4 { public static void main(String[]args){ double a = 10; double b = 15; double c, s; c = Math.hypot(a,b); s = 0.5*a*b; System.out.println("Гипотенуза = " + c +" и площадь равна " + s ); } }
/** * Represents a Sandwich item. * * @author Ben Godfrey * @version 12 APRIL 2018 */ public class Sandwich implements MenuItem { /** The name of the Sandwich */ private String mName; /** The price of the Sandwich */ private double mPrice; /** * Creates a new Sandwich given the price and name * * @param name The name of the Sandwich * @param price The price of the Sandwich */ public Sandwich(String name, double price) { mName = name; mPrice = price; } public double getPrice() { return mPrice; } public String getName() { return mName; } }
package officehours04_12; import java.util.*; public class DynamicReadingInt { public static void main(String[] args) { Scanner input = new Scanner (System.in); System.out.println("how many number do you have"); int [] nums = new int [input.nextInt()]; //0 0 0 0 for(int i = 0; i < nums.length;i++){ } } }
package com.hb.rssai.presenter; import com.hb.rssai.constants.Constant; import com.hb.rssai.contract.ModifySubscriptionContract; import java.util.HashMap; import java.util.Map; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * Created by Administrator * on 2019/5/5 */ public class ModifySubscriptionPresenter extends BasePresenter<ModifySubscriptionContract.View> implements ModifySubscriptionContract.Presenter { ModifySubscriptionContract.View mView; public ModifySubscriptionPresenter(ModifySubscriptionContract.View mView) { this.mView = mView; this.mView.setPresenter(this); } public void getDataGroupList() { dataGroupApi.getDataGroupList(getDataGroupListParams()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(resDataGroup -> { mView.setDataGroupResult(resDataGroup); }, mView::loadError); } @Override public void modifySubscription(Map<String, Object> params) { findApi.modifySubscription(params) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(resBase -> mView.showModifyResult(resBase), mView::loadError); } private HashMap<String, String> getDataGroupListParams() { //参数可以不要 HashMap<String, String> map = new HashMap<>(); String jsonParams = "{\"page\":\"" + 1 + "\",\"size\":\"" + Constant.PAGE_SIZE + "\"}"; map.put(Constant.KEY_JSON_PARAMS, jsonParams); return map; } @Override public void start() { getDataGroupList(); } }
/* * 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 se.havero.sater.wiremock.model; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; import lombok.Data; /** * * @author johan */ @Data @ApiModel public class Note { private static final String CONTENT_EXAMPLE = "# Linux commands\n" + "\n" + "LIst TCP connections with portnumbers\n" + "\n" + "```bash\n" + "$ sudo lsof -i -n -P | grep TCP | more\n" + "```"; @ApiModelProperty(example = "2399") private Long noteId; @ApiModelProperty(example = "Linux how to list tcp connections") private String name; @ApiModelProperty(example = "md") private String format; @ApiModelProperty(example = CONTENT_EXAMPLE) private String content; @ApiModelProperty(example = "[\"Linux\", \"port\", \"connection\"]") private List<String> tags; public Note() { } public Note(String name, String format, String content, List<String> tags) { this.name = name; this.format = format; this.content = content; this.tags = tags; } public List<String> getTags() { if (tags == null) { tags = new ArrayList<>(); } return tags; } }
package test1; public class test1 { public static void main(String[] args) { System.out.println(1); System.out.println(2); //22222222222 //1111111111111 //333333333333333333333 //rrrrrrrrrrrrrrrr //44444444444444444 //rsfssdfsdfsfs //6666666666666666666666 //44444444444444444444 } }
package Pages; import org.openqa.selenium.WebDriver; public abstract class Page<T> { public WebDriver driver; protected abstract String url(); protected abstract T openPage(); public Page(WebDriver driver){ this.driver = driver; } }
package project; import inputStrategy.ComputerInputStrategy; import inputStrategy.HumanInputStrategy; import java.util.Random; import java.util.Scanner; class TicTacToe { private final Board board = new Board(); private final Player[] players= new Player[2]; private Player currentPlayer = null; private Player winner = null; public void start() { initializeHumanPlayer(); initializeComputerPlayer(); selectFirstPlayer(); while(!hasWinner() && !board.isFull()) { announcePlayerTurn(); Turn turn = currentPlayer.getTurn(); if(board.isValidTurn(turn)){ board.set(currentPlayer.getSign(), turn); board.display(); if(board.hasWinner()){ winner = currentPlayer; } else { currentPlayer = getNextPlayer(); } } else { logInvalidTurn(turn); } } if(hasWinner()) { announceWinner(); } else { announceDraw(); } } private void selectFirstPlayer() { Random random = new Random(); currentPlayer = random.nextBoolean() ? players[0] : players[1]; System.out.format("%s is the first player.\n", currentPlayer.getName()); } private void initializeHumanPlayer() { Player p1 = new Player(); p1.setStrategy(new HumanInputStrategy()); p1.setSign(getPreferredSign()); p1.setName("Player 1"); players[0] = p1; } private char getPreferredSign() { System.out.print("Please select your sign [X or O]: "); Scanner userInput = new Scanner(System.in); char sign; while(true) { String input = userInput.nextLine(); if(input.length() == 1) { sign = input.charAt(0); if(sign == 'X' || sign == 'O' ) break; } System.out.print("Please select your sign [X or O]: "); } return sign; } private void initializeComputerPlayer() { Player p2 = new Player(); p2.setSign(getComputerSign()); p2.setStrategy(new ComputerInputStrategy(board, p2.getSign())); p2.setName("Computer"); players[1] = p2; } private char getComputerSign() { return players[0].getSign() == 'X' ? 'O' : 'X'; } private void announcePlayerTurn() { System.out.format("It is %s's turn.\n\n", currentPlayer.getName()); } private void logInvalidTurn(Turn turn) { System.out.format("Invalid input: %d %d\n", turn.row, turn.column); } private void announceWinner() { System.out.format("Winner is %s.\n", winner.getName()); } private void announceDraw() { System.out.println("It's a draw."); } private boolean hasWinner() { return winner != null; } private Player getNextPlayer() { return currentPlayer == players[0] ? players[1] : players[0]; } }
package remote.datatypes; import enums.PacketCommand; import exceptions.IncorrectDataException; import helpers.DataConversionHelper; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * A class for keeping packets to be sent to or recieved from the autonomous system. * * @author Henrik Nilsson */ public class PacketList implements Iterable<CommunicationPacket> { private List<CommunicationPacket> packets; /** * PacketList constructor */ public PacketList() { packets = new ArrayList<>(); } /** * PacketList constructor * @param pack Communication packet to be added directly to the list */ public PacketList(CommunicationPacket pack) { packets = new ArrayList<>(1); packets.add(pack); } /** * PacketList constructor * @param rawData Raw server data byte[] to be decoded into packet list * @throws IncorrectDataException Thrown if raw data could not be decoded correctly */ public PacketList(byte[] rawData) throws IncorrectDataException { packets = new ArrayList<>(); int numberOfPackets = DataConversionHelper.byteArrayToUnsignedInt(new byte[]{rawData[0]}); int offset = 1; while(offset < rawData.length) { CommunicationPacket pack = new CommunicationPacket(rawData, offset); this.addPacket(pack); offset += CommunicationPacket.HEADER_SIZE + pack.dataSize(); } if (numberOfPackets != packets.size()) throw new IncorrectDataException("Number of given and decoded packages does not match (" + numberOfPackets + " given, " + packets.size() + " decoded)."); } /** * Add communication packet to request * @param pack CommunicationPacket to be sent */ public void addPacket(CommunicationPacket pack) { packets.add(pack); } /** * Get number of requests * @return Number of packets */ public int numberOfPackets() { return packets.size(); } /** * Get total size in bytes * @return Size in number of bytes */ public int byteSize() { int size = 1; for (CommunicationPacket packet : packets) { size += packet.dataSize() + CommunicationPacket.HEADER_SIZE; } return size; } /** * Get bytes representation of packets * @return byte[] of packets */ public byte[] toBytes() { List<byte[]> byteLists = new ArrayList<>(); for (CommunicationPacket packet : packets) { byteLists.add(packet.toBytes()); } byte[] bytes = new byte[byteSize()]; bytes[0] = (byte) packets.size(); int offset = 1; for (byte[] packetBytes : byteLists) { System.arraycopy(packetBytes, 0, bytes, offset, packetBytes.length); offset += packetBytes.length; } return bytes; } @Override public String toString() { return "PacketList{" + "packets=" + packets + '}'; } /** * Returns an iterator over elements of type {@code T}. * * @return an Iterator. */ @Override public Iterator<CommunicationPacket> iterator() { return packets.iterator(); } public boolean contains(PacketCommand type) { for (CommunicationPacket pack : packets) { if (pack.getCommand() == type) return true; } return false; } public CommunicationPacket get(PacketCommand type) { for (CommunicationPacket pack : packets) { if (pack.getCommand() == type) return pack; } return null; } }
package site.xulian.learning.utils; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class RequestUtil { /** * 获取请求的IP地址 * @param request * @return */ public static String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("X-Forwarded-For"); 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(); } return ip; } /** * 获取当前应用部署的地址 * 如:http://localhost:8080 * 如果是80端口则不加端口号 * @param request * @return */ public static String getContextAllPath(HttpServletRequest request) { StringBuilder sb = new StringBuilder(); sb.append(request.getScheme()).append("://").append(request.getServerName()); if(request.getServerPort() != 80){ sb.append(":").append(request.getServerPort()); } sb.append(request.getContextPath()); String path = sb.toString(); sb = null; return path; } /** * 判断请求是否为ajax * @param request * @return */ public static boolean isAjax(HttpServletRequest request){ return (request.getHeader("X-Requested-With") != null && "XMLHttpRequest".equals( request.getHeader("X-Requested-With").toString())) ; } /** * 设置session及cookie值,放两处主要是防止 * @param request * @param response * @param key * @param value */ public static void setData(HttpServletRequest request, HttpServletResponse response, String key, String value){ request.getSession().setAttribute(key, value); Cookie cookie = new Cookie(key, value); response.addCookie(cookie); } /** * 获取设置的数据 * 优先拿session中的,如果session中不存在,则拿cookie中的 * @param request * @param response * @param key * @param value */ public static String getData(HttpServletRequest request, String key){ Object value = request.getSession().getAttribute(key); if(value != null){ return value.toString(); } Cookie[] cookies = request.getCookies(); if (cookies == null){ return null; } for (Cookie cookie : cookies){ if (cookie.getName().equals(key)){ return cookie.getValue(); } } return null; } /** * 当前请求客户端是否为微信 * @return */ public static boolean isWeixinClient(HttpServletRequest request){ String userAgent = request.getHeader("user-agent"); if(userAgent.toLowerCase().indexOf("micromessenger") != -1){// 微信浏览器 return true; } return false; } }
package eu.lsem.bakalarka.webfrontend.action.secure; import net.sourceforge.stripes.action.*; import net.sourceforge.stripes.integration.spring.SpringBean; import net.sourceforge.stripes.validation.Validate; import net.sourceforge.stripes.validation.ValidationMethod; import net.sourceforge.stripes.validation.ValidationErrors; import net.sourceforge.stripes.validation.SimpleError; import org.springframework.security.providers.encoding.MessageDigestPasswordEncoder; import org.springframework.security.context.SecurityContextHolder; import org.springframework.security.userdetails.UserDetails; import eu.lsem.bakalarka.dao.UserDao; import eu.lsem.bakalarka.model.User; import eu.lsem.bakalarka.service.ApplicationConfiguration; import eu.lsem.bakalarka.webfrontend.action.BaseActionBean; public class EditProfileActionBean extends BaseActionBean { @SpringBean("passwordEncoder") private MessageDigestPasswordEncoder passwordEncoder; @SpringBean("userDao") private UserDao userDao; @SpringBean("applicationConfiguration") private ApplicationConfiguration applicationConfiguration; private String oldPassword; private String newPassword; private String newPasswordRetype; public String getOldPassword() { return oldPassword; } public void setOldPassword(String oldPassword) { this.oldPassword = oldPassword; } public String getNewPassword() { return newPassword; } public void setNewPassword(String newPassword) { this.newPassword = newPassword; } public String getNewPasswordRetype() { return newPasswordRetype; } public void setNewPasswordRetype(String newPasswordRetype) { this.newPasswordRetype = newPasswordRetype; } @ValidationMethod(on = "edit") public void validate(ValidationErrors errors) { if (oldPassword == null) oldPassword = ""; if (newPassword == null) newPassword = ""; if (newPasswordRetype == null) newPasswordRetype = ""; String currentUserPassword = userDao.getUser(getCurrentUsername()).getPassword(); if (!passwordEncoder.encodePassword(getOldPassword().trim(), applicationConfiguration.getSystemWideSalt()).equals(currentUserPassword)) { errors.add("oldPassword", new SimpleError("Zadali jste špatné původní heslo")); } if (newPassword.length() < 5) { errors.add("newPassword", new SimpleError("Nové heslo musí být nejméně 5 znaků dlouhé")); } if (!newPassword.equals(newPasswordRetype)) { errors.add("newPasswordRetype", new SimpleError("Hesla nesouhlasí")); } } @DefaultHandler @DontBind public Resolution form() { return new ForwardResolution("/WEB-INF/pages/secure/editProfile.jsp"); } public Resolution edit() { String newHashedPassword = passwordEncoder.encodePassword(newPassword, applicationConfiguration.getSystemWideSalt()); String aktUsername = getCurrentUsername(); int result = userDao.updatePassword(userDao.getUser(aktUsername).getId(), newHashedPassword); if (result == 0) { getContext().getMessages().add(new SimpleMessage("Heslo nebylo zmněněno.")); } else { getContext().getMessages().add(new SimpleMessage("Heslo bylo úspěšně změněno.")); } return new RedirectResolution(EditProfileActionBean.class); } private String getCurrentUsername() { return ((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername(); } }
package homework1; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class HexTest { @Test @DisplayName("Hex draw test") void drawTest() { // Hex hex = new Hex(0, 0, 0); // System.out.println(hex.draw()); } @Test @DisplayName("test straightDistance from {0, 0, 0} to {-1, 2, -1}") void testStraightDistance_0_0_0_to_m1_2_m1() { Hex hex1 = new Hex(0, 0, 0); Hex hex2 = new Hex(-1, 2, -1); assertEquals(2, hex1.straightDistance(hex2)); } @Test @DisplayName("Test neighbors of Hex {0, 0, 0}") void testNeighbors_0_0_0() { Hex hex = new Hex(0, 0, 0); List<Hex> neighbors = hex.neighbors(); assertAll("neigbors", () -> assertEquals(new Hex(-1, 0, 1), neighbors.get(0)), () -> assertEquals(new Hex(-1, 1, 0), neighbors.get(1)), () -> assertEquals(new Hex(0, 1, -1), neighbors.get(2)), () -> assertEquals(new Hex(1, 0, -1), neighbors.get(3)), () -> assertEquals(new Hex(1, -1, 0), neighbors.get(4)), () -> assertEquals(new Hex(0, -1, 1), neighbors.get(5)) ); } }
package tech.chazwarp923.unifieditems.crafting; import java.util.Map; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.oredict.OreDictionary; import tech.chazwarp923.unifieditems.block.UIBlockGemOre; import tech.chazwarp923.unifieditems.block.UIBlockMetalOre; import tech.chazwarp923.unifieditems.block.UIBlocks; import tech.chazwarp923.unifieditems.config.ConfigHandler; import tech.chazwarp923.unifieditems.item.UIItemDust; import tech.chazwarp923.unifieditems.item.UIItemIngot; import tech.chazwarp923.unifieditems.item.UIItems; import tech.chazwarp923.unifieditems.material.Material; public class Smelting { public static void init() { // Smelting recipes for the Ores for(Map.Entry<Material, UIBlockMetalOre> block : UIBlocks.metalOres.entrySet()) { GameRegistry.addSmelting(block.getValue(), new ItemStack(UIItems.ingots.get(block.getKey())), 0.5f); } for(Map.Entry<Material, UIBlockGemOre> block : UIBlocks.gemOres.entrySet()) { GameRegistry.addSmelting(block.getValue(), new ItemStack(UIItems.gems.get(block.getKey())), 0.5f); } //Adds the recipes for other mods' ingots into my ingots if(ConfigHandler.general.get("furnaceConvert")) { for(Map.Entry<Material, UIItemIngot> ingot : UIItems.ingots.entrySet()) { for(ItemStack stack : OreDictionary.getOres("ingot" + ingot.getKey().toString())) { GameRegistry.addSmelting(stack, new ItemStack(ingot.getValue()), 0.0f); } } } // Smelting recipes for the Dusts GameRegistry.addSmelting(UIItems.dusts.get(Material.IRON), new ItemStack(Items.IRON_INGOT), 0.0f); GameRegistry.addSmelting(UIItems.dusts.get(Material.GOLD), new ItemStack(Items.GOLD_INGOT), 0.0f); for(Map.Entry<Material, UIItemDust> item : UIItems.dusts.entrySet()) { UIItemIngot ingot = UIItems.ingots.get(item.getKey()); if(ingot != null) { GameRegistry.addSmelting(item.getValue(), new ItemStack(UIItems.ingots.get(item.getKey())), 0.0f); } } } }
package ejercicio11; import java.util.Scanner; public class Ejercicio11 { public static void main(String[] args) { menu(); } private static void menu() { int opcion=0; do { System.out.println("---MENU---"); System.out.println("1.-Introducir productos"); System.out.println("2.-Introducir clientes"); System.out.println("3.-Salir"); opcion=pideInt("opcion"); switch (opcion) { case 1: introducirProducto(); break; case 2: introducirCliente(); break; case 3: System.out.println("FIN DEL PROGRAMA"); break; default: System.out.println("Te has equivocado"); break; } }while(opcion!=3); } private static void introducirCliente() { // TODO Auto-generated method stub } private static void introducirProducto() { // TODO Auto-generated method stub } /** * Este metodo pide un String al usuario, recibe un String para indicar el tipo * de dato esperado Si se da una excepcion se vuelve a pedir * * @param string * dato esperadp * @return dato solicitado */ private static String pideString(String string) { String palabra = ""; Scanner sc = new Scanner(System.in); System.out.println("Introduce " + string); boolean correcto = false; do { try { palabra = sc.nextLine(); correcto = true; } catch (Exception e) { System.out.println("Introduce de nuevo " + palabra); } } while (!correcto); return palabra; } /** * Este metodo pide un entero al usuario por teclado Si se da una excepción se * vuelve a pedir * * @param tipo * indica el dato a introducir * @return dato introducido */ public static int pideInt(String tipo) { int entero = 0; Scanner sc = new Scanner(System.in); boolean correcto = false; System.out.println("Introduce " + tipo); do { try { entero = sc.nextInt(); correcto = true; } catch (NumberFormatException e) { System.out.println("Introduce de nuevo " + tipo); } } while (!correcto); return entero; } }
package org.ml4j.wit.api.impl.json; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class EntityUpdateRequest { private String doc; @JsonProperty("values") private List<ValueExpressions> valuesExpressions; public String getDoc() { return doc; } public void setDoc(String doc) { this.doc = doc; } public List<ValueExpressions> getValuesExpressions() { return valuesExpressions; } public void setValuesExpressions(List<ValueExpressions> valuesExpressions) { this.valuesExpressions = valuesExpressions; } @Override public String toString() { return "EntityUpdateRequest [doc=" + doc + ", valuesExpressions=" + valuesExpressions + "]"; } }
package SwordOffer; import java.util.HashMap; /** * @author renyujie518 * @version 1.0.0 * @ClassName RandomListNodeCopy_35.java * @Description 复杂链表的复制 * 输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的 head。 * * 思路: * 运用hashmap 建立 原节点 -> 新节点 的映射关系来建立新链表。 * 因为每个新节点都和原节点是对应的,建立这个映射关系后, * 新链表每个节点的 next 和 random 都可以通过对应原链表节点的 next 和 random 来获取。 * @createTime 2021年08月21日 19:18:00 */ public class RandomListNodeCopy_35 { public class RandomListNode { int val; RandomListNode next = null; RandomListNode random = null; RandomListNode(int val) { this.val = val; } } public RandomListNode RandomListNodeCopy(RandomListNode head) { if (head == null) { return null; } RandomListNode curr = head; HashMap<RandomListNode, RandomListNode> map = new HashMap<>(); //key =原链表节点 value =新链表对应节点 while (curr != null) { map.put(curr, new RandomListNode(curr.val)); curr = curr.next; } curr = head; //构建新链表的 next 和 random 指向 while (curr != null) { map.get(curr).next = map.get(curr.next); map.get(curr).random = map.get(curr.random); curr = curr.next; } //返回新链表头 return map.get(head); } }
/* * (C) Copyright 2016 Hewlett Packard Enterprise Development LP * * 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 monasca.api.domain.model.dimension; import javax.annotation.Nullable; import java.util.List; /** * Repository for dimensions. */ public interface DimensionRepo { /** * Finds dimension values given a dimension name and * optional metric name. */ List<DimensionValue> findValues(String metricName, String tenantId, String dimensionName, @Nullable String offset, int limit) throws Exception; /** * Finds dimension names given an optional metric name. */ List<DimensionName> findNames(String metricName, String tenantId, @Nullable String offset, int limit) throws Exception; }
/* * 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 threads; /** * * @author rafael */ public class PrioridadeThread extends Thread { PrioridadeThread(String name, int pri) { super(name); setPriority(pri); start(); } public void run() { System.out.println(getPriority()); } public static void main(String args[]) throws Exception { PrioridadeThread mt2 = new PrioridadeThread("Low Priority", Thread.NORM_PRIORITY - 1); PrioridadeThread mt1 = new PrioridadeThread("High Priority", Thread.NORM_PRIORITY + 1); mt1.join(); mt2.join(); } }
//**************** Oct 26- P5**************** package OOP_Encapsulation; public class BrowserUser { public static void main(String[] args) { Browser br=new Browser(); br.launchBrowser(); } }
package mvc_demo.models; public class Event extends Model{ }
package com.example.healthmanage.ui.activity.temperature; import java.util.List; public class InsertPrescriptionBean { /** * modelName : 中暑 * modelType : 0 * drugList : [{"id":18,"name":"名称","number":22,"unit":"药品单位","useMode":"服用方式","useTime":"2021-05-07 08:00:00","useFrequency":"服用频率"},{"id":19,"name":"名称","number":22,"unit":"药品单位","useMode":"服用方式","useTime":"2021-05-07 08:00:00","useFrequency":"服用频率"}] */ private String modelName; private int modelType; private String token; /** * id : 18 * name : 名称 * number : 22 * unit : 药品单位 * useMode : 服用方式 * useTime : 2021-05-07 08:00:00 * useFrequency : 服用频率 */ private List<DrugListBean> drugList; public String getModelName() { return modelName; } public void setModelName(String modelName) { this.modelName = modelName; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public int getModelType() { return modelType; } public void setModelType(int modelType) { this.modelType = modelType; } public List<DrugListBean> getDrugList() { return drugList; } public void setDrugList(List<DrugListBean> drugList) { this.drugList = drugList; } public static class DrugListBean { private int id; private String name; private int number; private String unit; private String useMode; private String useTime; private String useFrequency; public DrugListBean() { } public DrugListBean(String unit, String useMode, String useTime, String useFrequency) { this.unit = unit; this.useMode = useMode; this.useTime = useTime; this.useFrequency = useFrequency; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } public String getUseMode() { return useMode; } public void setUseMode(String useMode) { this.useMode = useMode; } public String getUseTime() { return useTime; } public void setUseTime(String useTime) { this.useTime = useTime; } public String getUseFrequency() { return useFrequency; } public void setUseFrequency(String useFrequency) { this.useFrequency = useFrequency; } } }
/* ***************************************************************************** * Name: Alan Turing * Coursera User ID: 123456 * Last modified: 1/1/2019 **************************************************************************** */ public class RevesPuzzle { private static void Tower(int n, int k, char e, char f, char g) { if (n == 0) return; Tower(n - 1, k, e, g, f); System.out.println("Move disc " + (n + k) + " from " + e + " to " + g); Tower(n - 1, k, f, e, g); } private static void Reves(int n, char a, char b, char c, char d) { if (n == 1) { System.out.println("Move disc " + n + " from " + a + " to " + d); return; } int k = (int) (Math.round(n + 1.0 - Math.sqrt(2 * n + 1.0))); Reves(k, a, d, c, b); Tower(n - k, k, a, c, d); Reves(k, b, a, c, d); } public static void main(String[] args) { int n = Integer.parseInt(args[0]); Reves(n, 'A', 'B', 'C', 'D'); } }
package com.goodhealth.algorithm.JDBC; import java.sql.*; public class Oracle { private static final int port = 1521; private static final String databaseName = "ghj"; private static final String URL = "jdbc:oracle:thin:@localhost:" + port + ":" + databaseName; private static final String USER = "sa"; private static final String PWD = "123456"; public void getConn() throws SQLException { Connection conn = null; Statement stmt; ResultSet rs; try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } try { conn = DriverManager.getConnection(URL, USER, PWD); stmt = conn.createStatement(); String sql = "select * from Admin"; rs = stmt.executeQuery(sql); while (rs.next()) { String id = rs.getString("ID"); String pwd = rs.getString("Pwd"); System.out.println(id + "," + pwd); } } catch (SQLException e) { e.printStackTrace(); } finally { if (conn != null) { } } } public static void main(String[] args) { Oracle oracleConnection = new Oracle(); try { oracleConnection.getConn(); } catch (SQLException e) { e.printStackTrace(); } } }
/* * Copyright: (c) 2004-2011 Mayo Foundation for Medical Education and * Research (MFMER). All rights reserved. MAYO, MAYO CLINIC, and the * triple-shield Mayo logo are trademarks and service marks of MFMER. * * Except as contained in the copyright notice above, or as used to identify * MFMER as the author of this software, the trade names, trademarks, service * marks, or product names of the copyright holder shall not be used in * advertising, promotion or otherwise in connection with this software without * prior written authorization of the copyright holder. * * 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 edu.mayo.cts2.framework.webapp.rest.converter; import edu.mayo.cts2.framework.core.xml.Cts2Marshaller; import edu.mayo.cts2.framework.core.xml.Cts2v10MarshallerDecorator; import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; import org.springframework.http.converter.AbstractHttpMessageConverter; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.HttpMessageNotWritableException; import javax.xml.transform.stream.StreamResult; import java.io.IOException; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; /** * @author <a href="mailto:kevin.peterson@mayo.edu">Kevin Peterson</a> */ public class Cts2v10XmlHttpMessageConverter extends AbstractHttpMessageConverter<Object> { public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); public static final String VERSION_PARAMETER = "version"; public static final String CTS2_10 = "1.0"; public static final Map<String,String> CTS2_10_PARAMETER = new HashMap<String,String>(); static { CTS2_10_PARAMETER.put(VERSION_PARAMETER, CTS2_10); } private Cts2Marshaller v10Cts2Marshaller; /** * Instantiates a new mapping gson http message converter. */ public Cts2v10XmlHttpMessageConverter() { super(new MediaType(new MediaType("application", "xml", DEFAULT_CHARSET), CTS2_10_PARAMETER)); } public void setCts2Marshaller(Cts2Marshaller cts2Marshaller) { this.v10Cts2Marshaller = new Cts2v10MarshallerDecorator(cts2Marshaller); } /* (non-Javadoc) * @see org.springframework.http.converter.AbstractHttpMessageConverter#supports(java.lang.Class) */ @Override protected boolean supports(Class<?> clazz) { return true; } /* (non-Javadoc) * @see org.springframework.http.converter.AbstractHttpMessageConverter#readInternal(java.lang.Class, org.springframework.http.HttpInputMessage) */ @Override protected Object readInternal( Class<? extends Object> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { throw new UnsupportedOperationException("Cannot accept CTS2 1.0 XML."); } /* (non-Javadoc) * @see org.springframework.http.converter.AbstractHttpMessageConverter#writeInternal(java.lang.Object, org.springframework.http.HttpOutputMessage) */ @Override protected void writeInternal( Object t, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { this.v10Cts2Marshaller.marshal(t, new StreamResult(outputMessage.getBody())); } }
package Six; /** * package:包,对应到文件系统就是多级目录 * 为了解决两个问题: * 1、文件同名问题 * 2、为了方便管理类,将具体处理功能的代码放到同一个目录下 * 使用: * 一般定义package会放置在Java文件的第一行 * package 域名倒写 * package com.mashibng. * 完全限定名:包名+类名 * * * JDK中常用的包: * lang: 不需要手动导入,自动加载 * util:工具包 * net:网络包 * io:输入输出流包 * * * * * * * * * * */ public class PackageDemo { }
package com.drzewo97.ballotbox.panel.controller.election; import com.drzewo97.ballotbox.core.model.election.Election; import com.drzewo97.ballotbox.core.model.election.ElectionRepository; import com.drzewo97.ballotbox.core.model.poll.Poll; import com.drzewo97.ballotbox.core.model.poll.PollRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import javax.validation.Valid; @Controller @RequestMapping("/panel/election/create") public class ElectionCreationController { @Autowired private ElectionRepository electionRepository; @Autowired private PollRepository pollRepository; @ModelAttribute("election") private Election election(){ return new Election(); } @GetMapping private String showElectionCreate(Model model){ // TODO: only null election polls model.addAttribute("polls", pollRepository.findAll()); return "panel/election_create"; } @PostMapping private String createElection(@ModelAttribute("election") @Valid Election election, BindingResult result){ if(electionRepository.existsByName(election.getName())){ result.rejectValue("name", "name.exist", "Election already exists."); } if(result.hasErrors()){ return "panel/election_create"; } for(Poll poll : election.getPolls()){ poll.setElection(election); } electionRepository.save(election); pollRepository.saveAll(election.getPolls()); return "redirect:create?success"; } }
package com.duanxr.yith.midium; /** * @author 段然 2021/3/12 */ public class OneAwayLcci { /** * There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away. * *   * * Example 1: * * Input: * first = "pale" * second = "ple" * Output: True * Example 2: * * Input: * first = "pales" * second = "pal" * Output: False * * 字符串有三种编辑操作:插入一个字符、删除一个字符或者替换一个字符。 给定两个字符串,编写一个函数判定它们是否只需要一次(或者零次)编辑。 * *   * * 示例 1: * * 输入: * first = "pale" * second = "ple" * 输出: True *   * * 示例 2: * * 输入: * first = "pales" * second = "pal" * 输出: False * */ class Solution { public boolean oneEditAway(String first, String second) { if (Math.abs(first.length() - second.length()) > 1) { return false; } if (first.length() == 0 || second.length() == 0) { return true; } char[] charsA = first.toCharArray(); char[] charsB = second.toCharArray(); int a = 0; int b = 0; boolean found = false; while (a < charsA.length) { if (b == charsB.length) { return !found; } char ca = charsA[a]; char cb = charsB[b]; if (ca != cb) { if (found) { return false; } if (charsA.length > charsB.length) { found = true; b--; } else if (charsA.length < charsB.length) { found = true; a--; } else { found = true; } } a++; b++; } return true; } } }
package fiscal; // Generated 10/07/2009 10:49:54 by Hibernate Tools 3.2.0.b9 import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; /** * EquipamentoServico generated by hbm2java */ @Entity @Table(name = "TBEQUIPAMENTO_SERVICO") public class FiscalEquipamentoServico implements java.io.Serializable { private Long id; private FiscalEquipamento equipamento; private FiscalTipoServico tipoServico; private Long porta; private String enderecoIp; public FiscalEquipamentoServico() { } public FiscalEquipamentoServico(Long id, FiscalTipoServico tipoServico) { this.id = id; this.tipoServico = tipoServico; } public FiscalEquipamentoServico(Long id, FiscalEquipamento equipamento, FiscalTipoServico tipoServico, Long porta, String enderecoIp) { this.id = id; this.equipamento = equipamento; this.tipoServico = tipoServico; this.porta = porta; this.enderecoIp = enderecoIp; } @Id @GeneratedValue @Column(name = "EQUIPAMENTO_SERVICO_ID", unique = true, nullable = false, precision = 38, scale = 0) public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "EQUIPAMENTO_ID") public FiscalEquipamento getEquipamento() { return this.equipamento; } public void setEquipamento(FiscalEquipamento equipamento) { this.equipamento = equipamento; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "TIPO_SERVICO_ID", nullable = false) public FiscalTipoServico getTipoServico() { return this.tipoServico; } public void setTipoServico(FiscalTipoServico tipoServico) { this.tipoServico = tipoServico; } @Column(name = "PORTA", precision = 38, scale = 0) public Long getPorta() { return this.porta; } public void setPorta(Long porta) { this.porta = porta; } @Column(name = "ENDERECO_IP", length = 16) public String getEnderecoIp() { return this.enderecoIp; } public void setEnderecoIp(String enderecoIp) { this.enderecoIp = enderecoIp; } // The following is extra code specified in the hbm.xml files private static final long serialVersionUID = 1L; // end of extra code specified in the hbm.xml files }
package com.baomidou.mybatisplus.samples.quickstart.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.samples.quickstart.domain.User; import com.baomidou.mybatisplus.samples.quickstart.mapper.UserMapper; import com.baomidou.mybatisplus.samples.quickstart.service.UserSerivce; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @SuppressWarnings("all") @Service @Slf4j public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserSerivce { @Autowired private UserMapper userMapper; @Override public boolean insertBatch(List<User> userList) { return false; } @Override public User selectByNameAge(String name, Integer age) { if (StringUtils.isNoneBlank(name)){ return userMapper.selectByNameAndAge(name,age); } return null; } }
package com.ericlam.mc.minigames.core.factory.scoreboard; import com.ericlam.mc.minigames.core.factory.Factory; import com.ericlam.mc.minigames.core.game.GameTeam; import org.bukkit.scoreboard.Team; /** * 計分版工廠 */ public interface ScoreboardFactory extends Factory<GameBoard> { /** * 添加隊伍設定 * @param gameTeam 隊伍 * @param option 設定 * @param status 狀態 * @return this */ ScoreboardFactory addTeamSetting(GameTeam gameTeam, Team.Option option, Team.OptionStatus status); /** * 添加全局設定 * <p> * 注意,此設定僅限能套用在<b>沒有隊伍</b>的玩家。 * @param option 設定 * @param status 狀態 * @return this */ ScoreboardFactory addSetting(Team.Option option, Team.OptionStatus status); /** * 設置計分版標題, 支援顏色代碼 * @param title 標題 * @return this */ ScoreboardFactory setTitle(String title); /** * 設置計分版內容 * @param key 此行內容的標識文字 * @param text 文字, 支援顏色 * @param score 分數 * @return this */ ScoreboardFactory setLine(String key, String text, int score); /** * 添加計分版內容而不標識文字 * @param text 文字, 支援顏色 * @param score 分數 * @return this */ ScoreboardFactory addLine(String text, int score); }
package IO; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.nio.Buffer; import org.junit.Test; public class TestOtherStream { @Test public void testOtherStream1() { BufferedReader br = null; BufferedWriter bw = null; try { File file = new File("hello1.txt"); FileInputStream fis = new FileInputStream (file); InputStreamReader isr = new InputStreamReader(fis, "GBK"); br = new BufferedReader(isr); FileOutputStream fow = new FileOutputStream(file); OutputStreamWriter osw = new OutputStreamWriter(fow, "GBK"); bw = new BufferedWriter(osw); String str; while((str = br.readLine()) != null) { bw.write(str); bw.newLine(); bw.flush(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if(bw != null) { try { bw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(br != null) { try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } @Test public void testOtherStream2() { BufferedReader br = null; try { InputStream in = System.in; OutputStream out = System.out; InputStreamReader isr = new InputStreamReader(in); br = new BufferedReader(isr); String str; while(true) { System.out.println("ÇëÊäÈë×Ö·û´®£º"); str = br.readLine(); if(str.equalsIgnoreCase("e") || str.equalsIgnoreCase("exit")) { break; } System.out.println(str.toUpperCase()); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if(br != null) { try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
/* * 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 model; import contrat.Metier; import java.io.Serializable; /** * * @author bynan */ public class UserModel extends Metier implements Serializable { private int id; private String full_name; private String login; private String password; private String email; private String phone_number; int role_id; public UserModel(int id, int role_id, String full_name, String phone_number) { this.full_name = full_name; this.phone_number = phone_number; this.role_id = role_id; this.id = id; } public UserModel(int id, String full_name, String login, String password, String email, String phone_number, int role_id) { this.id = id; this.full_name = full_name; this.login = login; this.password = password; this.email = email; this.phone_number = phone_number; this.role_id = role_id; } public UserModel(String full_name, int id) { this.full_name = full_name; this.id = id; } public UserModel(int id){ this.id = id; } public UserModel() { } public UserModel(String full_name, int idRole, String login, String hashed, String email, String mobile) { this.full_name = full_name; this.role_id =idRole; this.login = login; this.password = hashed; this.email = email; this.phone_number = mobile; } public int getId() { return id; } public String getFull_name() { return full_name; } public void setFull_name(String full_name) { this.full_name = full_name; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone_number() { return phone_number; } public void setPhone_number(String phone_number) { this.phone_number = phone_number; } public Integer getRole_id() { return role_id; } public void setRole_id(Integer role_id) { this.role_id = role_id; } @Override public String toString() { return this.full_name; } }
package com.tencent.mm.plugin.walletlock.b; import com.tencent.mm.g.a.sd; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.walletlock.gesture.a.d; import com.tencent.mm.plugin.walletlock.gesture.a.e; import com.tencent.mm.protocal.c.ayz; import com.tencent.mm.sdk.b.b; import com.tencent.mm.sdk.b.c; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.aa.a; class f$3 extends c<sd> { final /* synthetic */ f pIs; f$3(f fVar) { this.pIs = fVar; this.sFo = sd.class.getName().hashCode(); } public final /* synthetic */ boolean a(b bVar) { ayz ayz = ((sd) bVar).ccW.ccX; g gVar = g.pIt; g.bRv(); if (e.b(ayz)) { x.i("MicroMsg.WalletLockInitTask", "tom update PatternLockInfo, sign_len:%d,valid:%b,status:%d,ver:%d", new Object[]{Integer.valueOf(ayz.sbL.siI), Boolean.valueOf(e.b(ayz)), Integer.valueOf(ayz.sbM), Integer.valueOf(ayz.sbK)}); d.a(ayz); } else { x.w("MicroMsg.WalletLockInitTask", "UserInfoExt.PatternLockInfo is null or invalid."); } x.i("MicroMsg.WalletLockInitTask", "alvinluo after update gesture server info, isUserSetGesturePwd: %b", new Object[]{Boolean.valueOf(e.bRE())}); g.Ei().DT().a(a.sYC, Boolean.valueOf(r0)); ((com.tencent.mm.plugin.walletlock.a.b) g.l(com.tencent.mm.plugin.walletlock.a.b.class)).init(); return false; } }
package com.xkzhangsan.time.nlp; import java.util.List; import java.util.concurrent.Callable; /** * TimeNLP Callable * @author xkzhangsan */ public class TimeNLPCallable implements Callable<List<TimeNLP>>{ private String text; private String timeBase; public TimeNLPCallable(String text, String timeBase) { super(); this.text = text; this.timeBase = timeBase; } @Override public List<TimeNLP> call() throws Exception { List<TimeNLP> timeNLPList = TimeNLPUtil.parse(text, timeBase); return timeNLPList; } }
package com.mx.profuturo.bolsa.model.service.hiringform.vo; import com.mx.profuturo.bolsa.model.service.hiringform.dto.FormularioEtapa1DTO; import com.mx.profuturo.bolsa.model.service.hiringform.dto.FormularioEtapa2DTO; import com.mx.profuturo.bolsa.model.service.hiringform.dto.FormularioEtapa3DTO; import com.mx.profuturo.bolsa.model.service.hiringform.dto.FormularioEtapa4DTO; public class DatosFormularioVO { private FormularioEtapa1DTO etapa1; private FormularioEtapa2DTO etapa2; private FormularioEtapa3DTO etapa3; private FormularioEtapa4DTO etapa4; public FormularioEtapa1DTO getEtapa1() { return etapa1; } public void setEtapa1(FormularioEtapa1DTO etapa1) { this.etapa1 = etapa1; } public FormularioEtapa2DTO getEtapa2() { return etapa2; } public void setEtapa2(FormularioEtapa2DTO etapa2) { this.etapa2 = etapa2; } public FormularioEtapa3DTO getEtapa3() { return etapa3; } public void setEtapa3(FormularioEtapa3DTO etapa3) { this.etapa3 = etapa3; } public FormularioEtapa4DTO getEtapa4() { return etapa4; } public void setEtapa4(FormularioEtapa4DTO etapa4) { this.etapa4 = etapa4; } }
package co.nos.noswallet.ui.home.v2.transactionDetail; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.FragmentActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import javax.inject.Inject; import co.nos.noswallet.NOSApplication; import co.nos.noswallet.R; import co.nos.noswallet.network.nosModel.AccountHistory; import co.nos.noswallet.network.websockets.CurrencyHandler; import co.nos.noswallet.network.websockets.WebsocketMachine; import co.nos.noswallet.persistance.IndexedWallet; import co.nos.noswallet.persistance.currency.CryptoCurrency; import co.nos.noswallet.ui.common.ActivityWithComponent; import co.nos.noswallet.ui.common.BaseDialogFragment; import co.nos.noswallet.ui.common.WindowControl; import co.nos.noswallet.util.refundable.Refundable; import co.nos.noswallet.util.refundable.RefundableBundle; public class TransactionDetailFragment extends BaseDialogFragment implements TransactionDetailView { public static final String CURRENCY = "CURRENCY"; public static final String ENTRY = "ENTRY"; public static final String WALLET = "WALLET"; public static String TAG = TransactionDetailFragment.class.getSimpleName(); @Nullable private CryptoCurrency cryptoCurrency; @Nullable private AccountHistory entry; @Nullable private IndexedWallet wallet; private RelativeLayout rootView; private TextView exchangeAddress, blockLabel, exchangeStatusLabel, refundButton, timestamp; private ImageView exchangeStatusImage, copyExchangeAddress, blockImage; private Handler handler; @Inject TransactionDetailPresenter presenter; public static TransactionDetailFragment newInstance(CryptoCurrency currency, IndexedWallet wallet, AccountHistory entry) { Bundle args = new Bundle(); TransactionDetailFragment fragment = new TransactionDetailFragment(); args.putSerializable(CURRENCY, currency); args.putSerializable(ENTRY, entry); args.putSerializable(WALLET, wallet); fragment.setArguments(args); return fragment; } public static void showFrom(CryptoCurrency cryptoCurrency, AccountHistory entry, IndexedWallet indexedWallet, FragmentActivity activity) { if (activity instanceof WindowControl) { TransactionDetailFragment dialog = TransactionDetailFragment.newInstance(cryptoCurrency, indexedWallet, entry); dialog.show(((WindowControl) activity).getFragmentUtility().getFragmentManager(), TransactionDetailFragment.TAG); // make sure that dialog is not null ((WindowControl) activity).getFragmentUtility().getFragmentManager().executePendingTransactions(); } } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); cryptoCurrency = getSerializableArgument(CURRENCY); entry = getSerializableArgument(ENTRY); wallet = getSerializableArgument(WALLET); handler = new Handler(Looper.getMainLooper()); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { if (getActivity() instanceof ActivityWithComponent) { ((ActivityWithComponent) getActivity()).getActivityComponent().inject(this); } view = inflater.inflate(R.layout.fragment_transaction_detail, container, false); if (entry == null || cryptoCurrency == null) { dismiss(); return view; } setStatusBar(); setupToolbar(view); rootView = view.findViewById(R.id.rootView); refundButton = view.findViewById(R.id.refund_button); exchangeAddress = view.findViewById(R.id.exchange_address); exchangeStatusLabel = view.findViewById(R.id.amount_transferred_label); blockLabel = view.findViewById(R.id.blockhash); copyExchangeAddress = view.findViewById(R.id.copy_exchange_address); blockImage = view.findViewById(R.id.blockhash_url); exchangeStatusImage = view.findViewById(R.id.fragment_transaction_detail_receive_icon); timestamp = view.findViewById(R.id.timestamp); presenter.attachView(this); copyExchangeAddress.setOnClickListener(v -> { boolean copied = copyToClipBoard(entry.account); if (copied) { showSnackBar(getString(R.string.address_copied_to_clipboard), rootView).show(); } }); blockImage.setOnClickListener(v -> { presenter.openBlockHashLink(cryptoCurrency, entry.hash); }); presenter.renderPendingTransaction(entry, cryptoCurrency, true); return view; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); FragmentActivity activity = getActivity(); WebsocketMachine machine = WebsocketMachine.obtain(activity); if (machine != null) { CurrencyHandler handler = machine.getMatchingHandler(cryptoCurrency); if (handler != null && entry != null) { presenter.subscribeTransactionData(entry, cryptoCurrency, handler.observeTransactionData()); handler.requestTransactionData(entry.hash, wallet); } else { Log.e(TAG, "onViewCreated: currency handler or entry are null"); } } } private boolean copyToClipBoard(String account) { Context context = NOSApplication.get(); ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText(getString(R.string.account_address), account); if (clipboardManager != null) { clipboardManager.setPrimaryClip(clip); return true; } return false; } private void setupToolbar(View view) { Toolbar toolbar = view.findViewById(R.id.dialog_appbar); if (toolbar != null) { final TransactionDetailFragment window = this; TextView title = view.findViewById(R.id.dialog_toolbar_title); title.setText(R.string.transaction_details); toolbar.setNavigationOnClickListener(v1 -> window.dismiss()); } } @Override public void dismiss() { super.dismiss(); presenter.dispose(); handler.removeCallbacksAndMessages(null); } @Override public void onBlockHashLinkReceived(String url) { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); if (i.resolveActivity(NOSApplication.get().getPackageManager()) != null) { startActivity(i); } } @Override public void onReceiveTransferParams(int drawableRes, String receiveSendMessage, boolean shouldShowRefundButton, String hash, String address) { exchangeAddress.setText(address); blockLabel.setText(hash); exchangeStatusImage.setImageResource(drawableRes); exchangeStatusLabel.setText(receiveSendMessage); if (shouldShowRefundButton) { refundButton.setVisibility(View.VISIBLE); refundButton.setOnClickListener(v -> { presenter.attemptRefund(cryptoCurrency, entry); }); } else { refundButton.setVisibility(View.GONE); } } @Override public void navigateToRefundScreen(RefundableBundle refundableBundle) { if (getActivity() instanceof Refundable) { ((Refundable) getActivity()).attemptRefund(refundableBundle); } dismiss(); } @Override public void onReceiveTimestampData(String readableDate) { if (readableDate == null) { timestamp.setText(""); } else { timestamp.setText(readableDate); } } }
package com.stackroute.jdbc; import java.sql.*; public class DatabaseMetadataDemo { private Connection connection; private Statement statement; private ResultSet resultSet; public void getEmployeeDetails() { try { Class.forName("com.mysql.cj.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/EMPLOYEE", "root", "Root@123"); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("Select * from EMPLOYEE");) { DatabaseMetaData metaData=connection.getMetaData(); System.out.println("whether the current user can call all the procedures"); System.out.println(metaData.allProceduresAreCallable()); System.out.println("URL"); System.out.println(metaData.getURL()); System.out.println("UserName"); System.out.println(metaData.getUserName()); System.out.println("name of this database product"); System.out.println(metaData.getDatabaseProductName()); System.out.println("Database Version"); System.out.println(metaData.getDatabaseProductVersion()); System.out.println("Driver Name"); System.out.println(metaData.getDriverName()); /*Load driver and register with DriverManager*/ /*Use DriverManager to get Connection*/ //connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/employeedb", "root", "Root@123"); // statement = connection.createStatement(); // // resultSet = statement.executeQuery("Select * from employee"); } catch (SQLException e) { e.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } // finally { // try { // connection.close(); // statement.close(); // resultSet.close(); // } catch (SQLException e) { // e.printStackTrace(); // } } }
package com.fleet.easyexcel.controller; import com.alibaba.excel.EasyExcel; import com.fleet.easyexcel.entity.User; import com.fleet.easyexcel.listener.UserListener; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @author April Han */ @RestController @RequestMapping("/excel") public class ExcelController { @RequestMapping("/read") public List<User> read(@RequestParam(value = "file") MultipartFile file) throws Exception { if (file == null) { return null; } String fileName = file.getOriginalFilename(); if (fileName == null) { return null; } String suffix = fileName.substring(fileName.lastIndexOf(".") + 1); if (!"xls".equals(suffix) && !"xlsx".equals(suffix)) { return null; } UserListener userListener = new UserListener(); EasyExcel.read(file.getInputStream(), User.class, userListener).sheet().doRead(); return userListener.getList(); } @RequestMapping("/export") public void export(HttpServletResponse response) throws Exception { response.setHeader("Content-Disposition", "attachment;filename=" + new String("用户.xlsx".getBytes(), StandardCharsets.ISO_8859_1)); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setCharacterEncoding("utf-8"); OutputStream os = response.getOutputStream(); List<User> list = new ArrayList<>(); for (int i = 0; i < 25; i++) { User user = new User(); user.setId((long) i); user.setName("张三"); user.setSex(i % 2); user.setAvatar("D:\\avatar.jpg"); user.setBirth(new Date("1992/10/23")); user.setIdNo("20201918"); user.setScore(60.0203); list.add(user); } EasyExcel.write(os, User.class).sheet("用户").doWrite(list); } }
package engine.network; public class AbstractDelta implements Comparable<AbstractDelta>{ protected long time; public AbstractDelta(long time){ this.time = time; } @Override public int compareTo(AbstractDelta delta) { return Long.compare(time, delta.time); } public long getTime(){ return time; } }
import java.sql.Connection; import java.sql.DriverManager; public class Database_Connection { Connection connect() { try{ Class.forName("com.mysql.jdbc.Driver"); Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/exam","root",""); System.out.println("Database is connected successfully"); return con; }catch(Exception e){ System.out.println(e);} return null; } }
package classes; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.charset.Charset; public class Registro { String chave; String nome; String email; String telefone; public void setChave(String chave){ this.chave = chave; } public String getChave(){ return chave; } public void setNome(String nome){ this.nome = nome; } public String getNome(){ return nome; } public void setEmail(String email){ this.email = email; } public String getEmail(){ return email; } public void setTelefone(String telefone){ this.telefone = telefone; } public String getTelefone(){ return telefone; } public void leRegistro(DataInput di) throws IOException{ String linha = di.readLine(); System.out.println(linha); String colunas[] = linha.split(","); this.chave = colunas[0]; this.nome = colunas[1]; this.email = colunas[2]; this.telefone = colunas[3]; } // public void leRegistro(DataInput di) throws IOException{ // byte chave[] = new byte[2]; // byte nome[] = new byte[72]; // byte email[] = new byte[72]; // byte telefone[] = new byte[8]; // // di.readFully(chave); // di.readFully(nome); // di.readFully(email); // di.readFully(telefone); // di.readByte(); // Ultimo espaco em branco // di.readByte(); // Quebra de linha // // //Necessita mesmo do CHARSET?? // // Charset enc = Charset.forName("ISO-8859-1"); // // this.chave = new String(chave, enc); // this.nome = new String(nome, enc); // this.email = new String(email, enc); // this.telefone = new String(telefone, enc); // } public void escreveRegistro(RandomAccessFile dop) throws IOException{ dop.writeBytes(this.chave); dop.write(','); dop.writeBytes(this.nome); dop.write(','); dop.writeBytes(this.email); dop.write(','); dop.writeBytes(this.telefone); dop.writeChar('\n'); } }
package com.example.storage; import java.io.File; import java.util.ArrayList; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.ImageView; import android.widget.Toast; import android.widget.AdapterView.OnItemSelectedListener; import com.example.storage.util.FileUtil; /** * Created by ouyangshen on 2017/10/1. */ public class ImageReadActivity extends AppCompatActivity implements OnClickListener { private final static String TAG = "ImageReadActivity"; private ImageView iv_image; private Spinner sp_file; private String mPath; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_image_read); iv_image = findViewById(R.id.iv_image); sp_file = findViewById(R.id.sp_file); findViewById(R.id.btn_delete).setOnClickListener(this); // 获取当前App的私有存储目录 mPath = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString() + "/"; if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { refreshSpinner(); } else { showToast("未发现已挂载的SD卡,请检查"); } } private void refreshSpinner() { // 获得指定目录下面的所有图片文件 ArrayList<File> fileAlllist = FileUtil.getFileList(mPath, new String[]{".png", ".jpg"}); if (fileAlllist.size() > 0) { fileArray = new String[fileAlllist.size()]; for (int i = 0; i < fileAlllist.size(); i++) { fileArray[i] = fileAlllist.get(i).getName(); } ArrayAdapter<String> typeAdapter = new ArrayAdapter<String>(this, R.layout.item_select, fileArray); typeAdapter.setDropDownViewResource(R.layout.item_dropdown); sp_file.setPrompt("请选择图片文件"); sp_file.setAdapter(typeAdapter); sp_file.setSelection(0); sp_file.setOnItemSelectedListener(new FileSelectedListener()); } else { fileArray = null; fileArray = new String[1]; fileArray[0] = ""; ArrayAdapter<String> typeAdapter = new ArrayAdapter<String>(this, R.layout.item_select, fileArray); sp_file.setPrompt(null); sp_file.setAdapter(typeAdapter); sp_file.setOnItemSelectedListener(null); iv_image.setImageDrawable(null); } } private String[] fileArray; class FileSelectedListener implements OnItemSelectedListener { public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // 打开并显示选中的图片文件位图 String file_path = mPath + fileArray[arg2]; Bitmap bitmap = FileUtil.openImage(file_path); iv_image.setImageBitmap(bitmap); } public void onNothingSelected(AdapterView<?> arg0) { } } @Override public void onClick(View v) { if (v.getId() == R.id.btn_delete) { for (int i = 0; i < fileArray.length; i++) { String file_path = mPath + fileArray[i]; File f = new File(file_path); if (!f.delete()) { Log.d(TAG, "file_path=" + file_path + ", delete failed"); } } refreshSpinner(); showToast("已删除临时目录下的所有图片文件"); } } private void showToast(String desc) { Toast.makeText(this, desc, Toast.LENGTH_SHORT).show(); } }
package com.tencent.mm.ui.chatting.viewitems; import android.os.Bundle; import com.tencent.mm.R; import com.tencent.mm.ar.r; import com.tencent.mm.kernel.g; import com.tencent.mm.model.au; import com.tencent.mm.model.c; import com.tencent.mm.model.s; import com.tencent.mm.plugin.messenger.a.e; import com.tencent.mm.storage.bd; import com.tencent.mm.ui.chatting.AppBrandServiceChattingUI; import com.tencent.mm.ui.chatting.viewitems.ae.a; import com.tencent.mm.ui.chatting.viewitems.ae.b; import java.lang.ref.WeakReference; final class ag implements a { ag() { } public final void b(b.a aVar, int i, com.tencent.mm.ui.chatting.c.a aVar2, bd bdVar) { String str; int i2; Bundle bundle; String talkerUserName = aVar2.getTalkerUserName(); b bVar = (b) aVar; Bundle bundle2 = new Bundle(); bundle2.putString("conv_talker_username", talkerUserName); if (aVar2.tTq instanceof AppBrandServiceChattingUI.a) { str = "scene"; i2 = 10; bundle = bundle2; } else if (aVar2.cwr()) { str = "scene"; i2 = 2; bundle = bundle2; } else { str = "scene"; if (s.hf(talkerUserName)) { i2 = 7; bundle = bundle2; } else { i2 = 1; bundle = bundle2; } } bundle.putInt(str, i2); bundle2.putLong("msg_id", bdVar.field_msgId); bundle2.putLong("msg_sever_id", bdVar.field_msgSvrId); bundle2.putString("send_msg_username", bdVar.field_talker); e eVar = (e) g.l(e.class); long j = bdVar.field_msgId; str = bdVar.field_content; WeakReference weakReference = new WeakReference(aVar2.tTq.getContext()); WeakReference weakReference2 = new WeakReference(bVar.ucQ); CharSequence a = eVar.a(str, bundle2, weakReference); if (a == null || a.length() == 0) { bVar.jEz.setVisibility(8); } else { bVar.jEz.setVisibility(0); bVar.ucQ.setText(a); bVar.ucQ.setMovementMethod(ay.getInstance()); } com.tencent.mm.ar.a mw = r.Qq().mw(talkerUserName); au.HU(); i2 = ((Integer) c.DT().get(12311, Integer.valueOf(-2))).intValue(); if ((mw == null || mw.ecv == -2) && (mw != null || i2 == -2)) { bVar.ucQ.setTextColor(aVar2.tTq.getContext().getResources().getColor(R.e.white_text_color)); bVar.ucQ.setBackground(aVar2.tTq.getContext().getResources().getDrawable(R.g.chat_tips_bg)); } else { bVar.ucQ.setTextColor(aVar2.tTq.getContext().getResources().getColor(R.e.black_text_color)); bVar.ucQ.setBackground(aVar2.tTq.getContext().getResources().getDrawable(R.g.chat_tips_light_bg)); } bVar.ucQ.setOnClickListener(new 1(this)); bVar.ucQ.invalidate(); } }
package br.com.tomioka.vendashortalicas.controllers; import br.com.tomioka.vendashortalicas.models.Pedido; import br.com.tomioka.vendashortalicas.services.PedidoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/pedidos") public class PedidoController { @Autowired private PedidoService service; @GetMapping public ResponseEntity<List<Pedido>> findAll() { List<Pedido> pedidos = service.findAll(); return ResponseEntity.ok().body(pedidos); } }
package com.dazhi.naming.pojo; public class CommonParams { public static final String CODE = "code"; public static final String SERVICE_NAME = "serviceName"; public static final String CLUSTER_NAME = "clusterName"; public static final String NAMESPACE_ID = "namespaceId"; public static final String GROUP_NAME = "groupName"; public static final String LIGHT_BEAT_ENABLED = "lightBeatEnabled"; }
package com.wt.jiaduo.dao; import org.springframework.data.jpa.repository.JpaRepository; import com.wt.jiaduo.dto.jpa.XiaomaiTiaoxiubingHouqi; public interface XiaomaiTiaoxiubingHouqiDao extends JpaRepository<XiaomaiTiaoxiubingHouqi, Integer> { }
package org.apex.main; import java.io.*; public class FileRead { public static void main(String[] args) { // TODO Auto-generated method stub // String fileName = "Temp.text"; String line = null; try { FileReader fileReader = new FileReader("C:\\Users\\Mridula\\Documents\\Java\\Temp.txt"); BufferedReader bufferedReader = new BufferedReader(fileReader); while ((line =bufferedReader.readLine()) != null) { System.out.println(line); } bufferedReader.close(); } catch(FileNotFoundException e) { System.out.println("File doesn't exist"); } catch(IOException ex) { ex.printStackTrace(); } } }
package com.qtrj.simpleframework.ssh.controller; import com.oreilly.servlet.MultipartRequest; import java.io.File; public abstract class UploadFileNewCall { public abstract <T> void file(T paramT, File paramFile, String paramString1, String paramString2, long paramLong, String paramString3) throws Exception; public <T> void form(T obj, MultipartRequest multipartRequest) throws Exception {} }
package com.blueeaglecreditunion.script; /** * ADT to hold the member information */ public class MemberInformation { private String cardPrefix; private String cardStatus; private String cardNumber; private String cardExpirationDate; private String memberNumber; private String primaryAccountNumber; private String statusCode; private String memberName; private String memberPhoneNumber; private String primaryAddressLineOne; private String primaryAddressLineTwo; private String city; private String state; private String postalCode; private String primaryCountry; private String description; private String dateCardIssued; private String email; private int accountNumber; private String lastActivityDate; public MemberInformation() { } public MemberInformation(String cardPrefix, String cardNumber, String cardExpirationDate, String memberNumber, String primaryAccountNumber, String cardStatus, String statusCode1, String name, String memberPhoneNumber, String primaryAddressLineOne, String primaryAddressLineTwo, String city, String state, String postalCode, String primaryCountry, int statusCode, String description, String dateCardIssued, String email, int accountNumber, String lastActivityDate){ this.cardPrefix = cardPrefix; this.cardNumber = cardNumber; this.cardExpirationDate = cardExpirationDate; this.memberNumber = memberNumber; this.primaryAccountNumber = primaryAccountNumber; this.cardStatus = cardStatus; this.statusCode = statusCode1; this.memberName = name; this.memberPhoneNumber = memberPhoneNumber; this.primaryAddressLineOne = primaryAddressLineOne; this.primaryAddressLineTwo = primaryAddressLineTwo; this.city = city; this.state = state; this.postalCode = postalCode; this.primaryCountry = primaryCountry; this.description = description; this.dateCardIssued = dateCardIssued; this.email = email; this.accountNumber = accountNumber; this.lastActivityDate = lastActivityDate; } public String getCardPrefix() { return cardPrefix; } public void setCardPrefix(String cardPrefix) { this.cardPrefix = cardPrefix; } public String getCardNumber() { return cardNumber; } public void setCardNumber(String cardNumber) { this.cardNumber = cardNumber; } public String getCardExpirationDate() { return cardExpirationDate; } public void setCardExpirationDate(String cardExpirationDate) { this.cardExpirationDate = cardExpirationDate; } public String getMemberNumber() { return memberNumber; } public void setMemberNumber(String memberNumber) { this.memberNumber = memberNumber; } public String getPrimaryAccountNumber() { return primaryAccountNumber; } public void setPrimaryAccountNumber(String primaryAccountNumber) { this.primaryAccountNumber = primaryAccountNumber; } public String getCardStatus() { return cardStatus; } public void setCardStatus(String cardStatus) { this.cardStatus = cardStatus; } public String getMemberName() { return memberName; } public void setMemberName(String memberName) { this.memberName = memberName; } public String getMemberPhoneNumber() { return memberPhoneNumber; } public void setMemberPhoneNumber(String memberPhoneNumber) { this.memberPhoneNumber = memberPhoneNumber; } public String getPrimaryAddressLineOne() { return primaryAddressLineOne; } public void setPrimaryAddressLineOne(String primaryAddressLineOne) { this.primaryAddressLineOne = primaryAddressLineOne; } public String getPrimaryAddressLineTwo() { return primaryAddressLineTwo; } public void setPrimaryAddressLineTwo(String primaryAddressLineTwo) { this.primaryAddressLineTwo = primaryAddressLineTwo; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public String getPrimaryCountry() { return primaryCountry; } public void setPrimaryCountry(String primaryCountry) { this.primaryCountry = primaryCountry; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getDateCardIssued() { return dateCardIssued; } public void setDateCardIssued(String dateCardIssued) { this.dateCardIssued = dateCardIssued; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getAccountNumber() { return accountNumber; } public void setAccountNumber(int accountNumber) { this.accountNumber = accountNumber; } public String getStatusCode() { return statusCode; } public void setStatusCode(String statusCode) { this.statusCode = statusCode; } public String getLastActivityDate() { return lastActivityDate; } public void setLastActivityDate(String lastActivityDate) { this.lastActivityDate = lastActivityDate; } }
package com.openfaas.function; import com.openfaas.model.IHandler; import com.openfaas.model.IResponse; import com.openfaas.model.IRequest; import com.openfaas.model.Response; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateExceptionHandler; import java.io.ByteArrayOutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.HashMap; import java.util.Map; public class Handler extends com.openfaas.model.AbstractHandler { /** * * @param req * @return */ public IResponse Handle(IRequest req) { Response res = new Response(); try { res.setContentType("text/html"); res.setBody(cargarTemplate()); }catch (Exception e){ e.printStackTrace(); res.setStatusCode(500); res.setBody("Error: "+e.getMessage()); } return res; } /** * * @return * @throws Exception */ private Configuration getConfiguracion() throws Exception{ Configuration cfg = new Configuration(Configuration.VERSION_2_3_27); cfg.setClassForTemplateLoading(this.getClass(), "/"); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); cfg.setLogTemplateExceptions(false); cfg.setWrapUncheckedExceptions(true); return cfg; } /** * * @return * @throws Exception */ private String cargarTemplate() throws Exception { Configuration cfg = getConfiguracion(); Map mapa = new HashMap(); mapa.put("mensaje", "Hola Mundo"); mapa.put("titulo", "Prueba"); Template template = cfg.getTemplate("index.ftl"); ByteArrayOutputStream output = new ByteArrayOutputStream(); Writer out = new OutputStreamWriter(output); template.process(mapa, out); out.close(); return output.toString("UTF-8"); } }
public class AreaDemo { public static void main(String[] args) { System.out.println("The are of the circle with a radius of 20 is " + Area.getArea(20.0) ); System.out.println("The are of the rectangle with length of 10 and width of 20 is "+ Area.getArea(10, 20)); System.out.println("The area of the cylinder with a radius of 10 and height of 20 is " + Area.getArea(10.0, 20.0)); } }
package edu.illinois.finalproject.PlayerProfile; import android.content.Context; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.squareup.picasso.Picasso; import net.rithms.riot.constant.Platform; import edu.illinois.finalproject.ExtendedSummoner; import edu.illinois.finalproject.R; public class PlayerProfile extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_player_profile); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ImageView searchImg = (ImageView) findViewById(R.id.searchIcon); final Context context = this; searchImg.setOnClickListener(new View.OnClickListener() { ExtendedSummoner eSummoner = null; @Override public void onClick(View view) { EditText enteredText = (EditText) findViewById(R.id.profileSearch); String summonerName = enteredText.getText().toString(); // summonerId to request Platform platform = Platform.NA; // platform to request try { eSummoner = GetPlayerData.getData(summonerName, platform); } catch (InterruptedException e) { e.printStackTrace(); } if (eSummoner != null) { // setting headers TextView summonerNameView = findViewById(R.id.Summoner_Name_View); summonerNameView.setText(eSummoner.summoner.getName()); // getting and setting the summoner icon ImageView summonerIcon = findViewById(R.id.summonerIcon); String summonerIconUrl = "http://ddragon.leagueoflegends.com/cdn/" + eSummoner.relm.getDd() + "/img/profileicon/" + eSummoner.summoner.getProfileIconId() + ".png"; Picasso.with(PlayerProfile.this).load(summonerIconUrl).into(summonerIcon); // populating match data for given player final RecyclerView recyclerLayout = (RecyclerView) findViewById(R.id.single_match_rview); MatchAdapter matchAdapter = new MatchAdapter(eSummoner); recyclerLayout.setAdapter(matchAdapter); recyclerLayout.setLayoutManager( new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)); } else { Toast.makeText(context , "No such summoner" , Toast.LENGTH_SHORT).show(); } } }); } }
package com.smartwerkz.bytecode.vm.methods; import com.smartwerkz.bytecode.classfile.Classfile; import com.smartwerkz.bytecode.classfile.MethodInfo; import com.smartwerkz.bytecode.classfile.Methods; import com.smartwerkz.bytecode.controlflow.FrameExit; import com.smartwerkz.bytecode.primitives.JavaObject; import com.smartwerkz.bytecode.primitives.JavaObjectReference; import com.smartwerkz.bytecode.vm.ClassArea; import com.smartwerkz.bytecode.vm.Frame; import com.smartwerkz.bytecode.vm.OperandStack; import com.smartwerkz.bytecode.vm.RuntimeConstantPool; import com.smartwerkz.bytecode.vm.RuntimeDataArea; import com.smartwerkz.bytecode.vm.VMLog; import com.smartwerkz.bytecode.vm.VirtualMachine; public class AccessControllerDoPrivileged implements NativeMethod { private final VMLog log = new VMLog(AccessControllerDoPrivileged.class.getName()); @Override public void execute(RuntimeDataArea rda, Frame frame, OperandStack operandStack) { JavaObjectReference targetObject = (JavaObjectReference) frame.getLocalVariables().getLocalVariable(0); JavaObject result = perform(rda, frame, targetObject); // log.debug("PrivilegedAction '%s' returned '%s'", targetObject, result); operandStack.push(result); } public JavaObject perform(RuntimeDataArea rda, Frame frame, JavaObjectReference targetObject) { Classfile classFile = targetObject.getClassFile(); // if (!classFile.doesImplement("java.security.PrivilegedAction")) { // throw new IllegalStateException(); // } // TODO: Invoke the 'run()' method VirtualMachine vm = rda.vm(); Methods methods2 = classFile.getMethods(vm); MethodInfo invokeMethodInfo = methods2.findMethodInfo(vm, "run"); ClassArea classArea = rda.getMethodArea().getClassArea(classFile.getThisClassName()); RuntimeConstantPool rcp = classArea.getRuntimeConstantPool(); Frame newFrame = new Frame(vm, frame.getVirtualThread(), rda, rcp, invokeMethodInfo); newFrame.getLocalVariables().setLocalVariable(0, targetObject); FrameExit frameResult = newFrame.execute(); if (!frameResult.hasReturnValue()) { throw new IllegalStateException(); } return frameResult.getResult(); } }
/** */ package ConceptMapDSL; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Map Elements</b></em>'. * <!-- end-user-doc --> * * * @see ConceptMapDSL.ConceptMapDSLPackage#getMapElements() * @model * @generated */ public interface MapElements extends NamedElement { } // MapElements
/* * * * Copyright 2009-2018. * * * * 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.github.pampas.common.exec.payload; import io.netty.channel.ChannelHandlerContext; import io.opentracing.Span; import io.opentracing.Tracer; import java.util.Map; /** * Created by darrenfu on 18-1-24. * * @param <T> the type parameter * @author: darrenfu * @date: 18 -1-24 */ public interface PampasRequest<T> extends Operation { /** * Id long. * * @return the long */ long id(); /** * 请求的key * * @return the string */ String key(); /** * Timestamp long. * * @return the long */ long timestamp(); /** * Gets channel handler context. * * @return the channel handler context */ ChannelHandlerContext channelHandlerContext(); /** * Gets tracer. * * @return the tracer */ Tracer tracer(); /** * Gets span. * * @return the span */ Span span(); /** * Gets request. * * @return the request */ T requestData(); /** * 相对URI (eg. /resty/user/get?name=darrenfu) * * @return the originUri */ String originUri(); /** * 无参数请求路径 (eg. /resty/user/get) * * @return the requestPath */ String path(); /** * Parameters map. * * @return the map */ Map<String, String> parameters(); /** * RestyCommand的请求方式(GET/POST) * * @return the http method */ String httpMethod(); /** * RestyCommand对应的服务名称 * * @return the service name */ String serviceName(); /** * Is keepalive boolean. * * @return the boolean */ boolean isKeepalive(); }
/* * 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 helpers; /** * * @author ChrisMac */ public class OverloadedCounter { private int initial; private boolean check; private int value; public OverloadedCounter(int initial, boolean check) { this.initial = initial; this.check = check; this.value = initial; } public OverloadedCounter(int initial) { this(initial, false); } public OverloadedCounter(boolean check) { this(0, check); } public OverloadedCounter() { this(0, false); } public int getValue() { return this.value; } public void increase(int amount) { this.value += amount; } public void increase() { this.increase(1); } public void decrease(int amount) { if (check && this.value == 0) { return; } this.value -= amount; } public void decrease() { this.decrease(1); } public void reset() { this.value = this.initial; } }
package GUI_Sudoku; import javax.swing.JLabel; import Sudoku_Logica.Celda; @SuppressWarnings("serial") public class MiLabel extends JLabel { //Atributos protected Celda c; //Constructor public MiLabel(Celda cel) { super(); c=cel; } //Metodos public void setcelda(Celda cel) { c=cel; } public Celda getcelda() { return c; } }
package org.sbbs.dao; import java.util.List; import java.util.Map; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import org.hibernate.HibernateException; import org.hibernate.proxy.HibernateProxy; import org.junit.Assert; import org.junit.Test; import org.sbbs.demo.dao.DemoEntityDao; import org.sbbs.demo.model.DemoEntity; import org.sbbs.demo.model.Dictionary; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.IncorrectResultSizeDataAccessException; import com.googlecode.genericdao.dao.hibernate.GeneralDAO; import com.googlecode.genericdao.search.Field; import com.googlecode.genericdao.search.Search; import com.googlecode.genericdao.search.SearchFacade; import com.googlecode.genericdao.search.SearchResult; import com.googlecode.genericdao.search.Sort; public class DemoEntityDaoTest extends BaseDaoTestCase { @Autowired DemoEntityDao demoEntityDao; @Autowired GeneralDAO generalDAO; @Autowired SearchFacade searchFacade; @Test public void testFind() { Long id = -1l; DemoEntity de = this.demoEntityDao.find( id ); Assert.assertNotNull( de ); de = this.demoEntityDao.find( 1l ); Assert.assertNull( de ); } /** * */ @Test public void testFindByIds() { Long[] ids = { -1l, -7l, -200l }; DemoEntity[] de = this.demoEntityDao.find( ids ); Assert.assertTrue( de.length == 3 ); Long[] ids1 = { 1l, 2l }; de = this.demoEntityDao.find( ids1 ); Assert.assertTrue( de.length == 2 ); Assert.assertNull( de[0] ); Assert.assertNull( de[1] ); Long[] ids2 = { -1l, 2l }; de = this.demoEntityDao.find( ids2 ); Assert.assertTrue( de.length == 2 ); Assert.assertNotNull( de[0] ); Assert.assertNull( de[1] ); } @Test public void testGetReference() { Long id1 = -1l;// , id2 = 1l; DemoEntity de0 = this.demoEntityDao.find( -2l ); DemoEntity de = this.demoEntityDao.getReference( id1 ); Assert.assertNotNull( de ); Assert.assertTrue( de instanceof HibernateProxy ); Assert.assertTrue( !( de0 instanceof HibernateProxy ) ); } @Test( expected = HibernateException.class ) public void testGetReferenceException() throws Exception { DemoEntity de = this.demoEntityDao.getReference( 1l ); Assert.assertNotNull( de ); try { int intv = de.getIntField(); } catch ( Exception e ) { logger.debug( e.getStackTrace() ); throw e; } } @Test public void testGetReferences() { Long[] ids0 = { -1l, -2l };// , ids1 = { 1l, 2l }; DemoEntity[] des = this.demoEntityDao.getReferences( ids0 ); Assert.assertTrue( des.length == 2 ); Assert.assertTrue( des[0] instanceof HibernateProxy ); int iv = des[0].getIntField(); } /** * */ @Test( expected = HibernateException.class ) public void testGetReferencesException() { Long[] ids0 = { 1l, 2l }; DemoEntity[] des = this.demoEntityDao.getReferences( ids0 ); Assert.assertTrue( des.length == 2 ); Assert.assertTrue( des[0] instanceof HibernateProxy ); int iv = des[0].getIntField(); } @Test public void testSave_Update() { DemoEntity de = this.demoEntityDao.find( -1l ); de.setIntField( 100 ); boolean saveType = this.demoEntityDao.save( de ); Assert.assertTrue( !saveType ); DemoEntity de1 = this.demoEntityDao.find( -1l ); Assert.assertEquals( 100, de1.getIntField() ); this.demoEntityDao.flush(); int jdbcv = this.jdbcTemplate.queryForInt( "SELECT a.intField from t_demo_entity a where demoId=-1 " ); Assert.assertTrue( jdbcv == de1.getIntField() ); } @Test public void testSave_insert() { DemoEntity de = new DemoEntity(); de.setIntField( 99 ); de.setStringField( "aaa" ); boolean saveType = this.demoEntityDao.save( de ); Assert.assertTrue( saveType ); Assert.assertNotNull( de.getDemoId() ); // this.demoEntityDao.flush(); int jdbcv = this.jdbcTemplate.queryForInt( "SELECT a.intField from t_demo_entity a where demoId=" + de.getDemoId() ); Assert.assertTrue( jdbcv == de.getIntField() ); List l = this.demoEntityDao.findAll(); Assert.assertTrue( l.size() == 201 ); } @Test public void testRemove() { Long id = -1l; boolean rs = this.demoEntityDao.removeById( id ); List l = this.demoEntityDao.findAll(); Assert.assertTrue( l.size() == 199 ); Assert.assertTrue( rs ); Long id1 = 1l; boolean rs1 = this.demoEntityDao.removeById( id1 ); List l1 = this.demoEntityDao.findAll(); Assert.assertTrue( l1.size() == 199 ); Assert.assertTrue( !rs1 ); } @Test public void testRemove1() { Long id = -1l; DemoEntity de = this.demoEntityDao.find( id ); boolean rs = this.demoEntityDao.remove( de ); List l = this.demoEntityDao.findAll(); Assert.assertTrue( l.size() == 199 ); Assert.assertTrue( rs ); rs = this.demoEntityDao.remove( de ); l = this.demoEntityDao.findAll(); Assert.assertTrue( l.size() == 199 ); Assert.assertTrue( !rs ); } @Test public void testRemoveByIds() { Long[] ids1 = { -1l, -2l, -3l }, ids2 = { -4l, 1l }; this.demoEntityDao.removeByIds( ids1 ); List l = this.demoEntityDao.findAll(); Assert.assertTrue( l.size() == 197 ); this.demoEntityDao.removeByIds( ids2 ); l = this.demoEntityDao.findAll(); Assert.assertTrue( l.size() == 196 ); } @Test public void testRemoveEntities() { List l = this.demoEntityDao.getHibernateTemplate().find( "from DemoEntity where demoId>=-50 and demoId<=-1" ); Assert.assertTrue( l.size() == 50 ); DemoEntity[] des = new DemoEntity[l.size()]; l.toArray( des ); this.demoEntityDao.remove( des ); List all = this.demoEntityDao.findAll(); Assert.assertTrue( all.size() == 150 ); } @Test public void testFindAll() { List l = this.demoEntityDao.findAll(); Assert.assertTrue( l.size() == 200 ); } @Test public void testSearch() { Search s = new Search(); s.addFilterLessThan( "demoId", -1l ); s.addFilterGreaterThan( "demoId", -50l ); List l = this.demoEntityDao.search( s ); Assert.assertTrue( l.size() == 48 ); } @Test public void testCount() { Search s = new Search(); s.addFilterLessThan( "demoId", -1l ); s.addFilterGreaterThan( "demoId", -50l ); int c = this.demoEntityDao.count( s ); Assert.assertTrue( c == 48 ); } @Test public void testSearchUnique() { Search s = new Search(); s.addFilterLessThan( "demoId", -1l ); s.addFilterGreaterThan( "demoId", -3l ); Object o = this.demoEntityDao.searchUnique( s ); Assert.assertNotNull( o ); } @Test public void testSearchUniqueNull() { Search s = new Search(); s.addFilterLessThan( "demoId", -1l ); s.addFilterGreaterThan( "demoId", -2l ); Object o = this.demoEntityDao.searchUnique( s ); Assert.assertNull( o ); } @Test( expected = IncorrectResultSizeDataAccessException.class ) public void testSearchUniqueException() { Search s = new Search(); s.addFilterLessThan( "demoId", -1l ); s.addFilterGreaterThan( "demoId", -5l ); Object o = this.demoEntityDao.searchUnique( s ); Assert.assertNotNull( o ); } @Test public void testSearchSort() { Search s = new Search(); s.addFilterLessThan( "demoId", -1l ); s.addFilterGreaterThan( "demoId", -50l ); s.addSort( "demoId", true ); List l = this.demoEntityDao.search( s ); Assert.assertTrue( l.size() == 48 ); Assert.assertTrue( ( (DemoEntity) l.get( 0 ) ).getDemoId() == -2l ); s.removeSort( "demoId" ); s.addSort( "demoId", false ); l = this.demoEntityDao.search( s ); Assert.assertTrue( l.size() == 48 ); Assert.assertTrue( ( (DemoEntity) l.get( 0 ) ).getDemoId() == -49l ); } @Test /** * TODO 还没有搞明白具体的使用方式 */ public void testSearchResultMode() { Search s = new Search(); s.addFilterLessThan( "demoId", -1l ); s.addFilterGreaterThan( "demoId", -50l ); // s.setResultMode( Search.RESULT_ARRAY ); // List l = this.demoEntityDao.search( s ); // s.setResultMode( Search.RESULT_LIST ); // List l1 = this.demoEntityDao.search( s ); s.addField( "demoId" ); s.setResultMode( Search.RESULT_MAP ); List l2 = this.demoEntityDao.search( s ); // s.setResultMode( Search.RESULT_SINGLE ); // List l3 = this.demoEntityDao.search( s ); Assert.assertTrue( l2.size() == 48 ); // Assert.assertTrue(((DemoEntity) l.get( 0 )).getDemoId()==-2l ); } @Test public void testSearchPaging() { Search s = new Search(); s.addFilterLessOrEqual( "demoId", -1l ); s.addFilterGreaterOrEqual( "demoId", -50l ); s.addSort( Sort.desc( "demoId" ) ); List l = this.demoEntityDao.search( s ); Assert.assertTrue( l.size() == 50 ); s.setMaxResults( 3 ); l = this.demoEntityDao.search( s ); Assert.assertTrue( l.size() == 3 ); s.setFirstResult( 4 ); l = this.demoEntityDao.search( s ); Assert.assertTrue( l.size() == 3 ); Assert.assertTrue( ( (DemoEntity) l.get( 0 ) ).getDemoId() == -5 ); s.setMaxResults( -1 ); l = this.demoEntityDao.search( s ); Assert.assertTrue( ( (DemoEntity) l.get( 0 ) ).getDemoId() == -5 ); Assert.assertTrue( l.size() == 46 ); s.setMaxResults( 4 ); s.setPage( 1 ); s.setFirstResult( 2 ); l = this.demoEntityDao.search( s ); s.setPage( 0 ); s.setFirstResult( -1 ); l = this.demoEntityDao.search( s ); Assert.assertTrue( l.size() == 4 ); } @Test public void testSearchPaging_1() { Search s = new Search(); s.addFilterLessOrEqual( "demoId", -1l ); s.addFilterGreaterOrEqual( "demoId", -50l ); s.addSort( Sort.desc( "demoId" ) ); s.setMaxResults( 4 ); s.setPage( 0 ); List l = this.demoEntityDao.search( s ); Assert.assertTrue( l.size() == 4 ); Assert.assertTrue( ( (DemoEntity) l.get( 0 ) ).getDemoId() == -1 ); s.setPage( 2 ); l = this.demoEntityDao.search( s ); Assert.assertTrue( l.size() == 4 ); Assert.assertTrue( ( (DemoEntity) l.get( 0 ) ).getDemoId() == -9 ); s.setPage( 10 ); // s.setFirstResult(2 ); l = this.demoEntityDao.search( s ); Assert.assertTrue( l.size() == 4 ); Assert.assertTrue( ( (DemoEntity) l.get( 0 ) ).getDemoId() == -41 ); } /* * @Test public void testFetching(){ Search s = new Search(); s.addFilterLessThan( "demoId", -1l ); * s.addFilterGreaterThan( "demoId", -50l ); // s.addFetch( "demoId" ); List l = this.demoEntityDao.search( s ); * Assert.assertTrue( l.size()==48 ); } */ @Test public void testFields() { List<Object[]> resultArray; List<List<?>> resultList; List<Map<String, Object>> resultMap; Search s = new Search(); s.addFilterLessOrEqual( "demoId", -1l ); s.addFilterGreaterOrEqual( "demoId", -50l ); s.addSort( Sort.desc( "demoId" ) ); s.addField( "intField" ); s.addField( "demoId" ); // s.addField("firstName", "first"); // s.addField("lastName"); // s.addField("age"); // s.addField(Field.ROOT_ENTITY); //same as s.addField(""); s.setResultMode( Search.RESULT_ARRAY ); resultArray = this.demoEntityDao.search( s ); Assert.assertTrue( resultArray.size() == 50 ); s.setResultMode( Search.RESULT_LIST ); resultList = this.demoEntityDao.search( s ); Assert.assertTrue( resultList.size() == 50 ); s.setResultMode( Search.RESULT_MAP ); resultMap = this.demoEntityDao.search( s ); Assert.assertTrue( resultMap.size() == 50 ); s.clearFields(); s.addField( Field.ROOT_ENTITY ); resultMap = this.demoEntityDao.search( s ); Assert.assertTrue( resultMap.size() == 50 ); } @Test public void testSearchAndCount() { Search s = new Search(); s.addFilterLessOrEqual( "demoId", -1l ); s.addFilterGreaterOrEqual( "demoId", -50l ); s.addSort( Sort.desc( "demoId" ) ); /* * s.addField( "intField" ); s.addField( "demoId" ); */ s.setPage( 0 ); s.setMaxResults( 20 ); SearchResult sr = this.demoEntityDao.searchAndCount( s ); Assert.assertTrue( sr.getTotalCount() == 50 ); Assert.assertTrue( sr.getResult().size() == 20 ); Assert.assertTrue( ( (DemoEntity) sr.getResult().get( 0 ) ).getDemoId() == -1l ); } @Test public void testSearchFetchs() { Search s = new Search( Dictionary.class ); List l0 = this.searchFacade.search( s ); List l = this.generalDAO.search( s ); Assert.assertTrue( l.size() == 36 ); } @Test public void testHv() { DemoEntity de = new DemoEntity(); de.setIntField( -1 ); de.setStringField( null ); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<DemoEntity>> constraintViolations = validator.validate( de ); Assert.assertEquals(2, constraintViolations.size()); // Assert.assertEquals("may not be null", constraintViolations.iterator().next().getMessage()); } }
package com.kashu.test.domain; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.CollectionTable; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import org.hibernate.annotations.Type; //@Entity //@Table (name="TB_USERS") public class User implements Serializable { private static final long serialVersionUID = 1L; //@Id //@Column(name="username") private String username; //@Column(name="password") private String password; //@Transient private String cpassword; //@Column(name="email") private String email; //@Column(name="nickname") private String nickname; //@Column(name="realname") private String realname; //@Column(name="gender") private String gender; //@Column(name="birthday") private Date birthday; //@Column(name="telephone") private String telephone; //@Column(name="mobile") private String mobile; //@Column(name="zipcode") private String zipcode; //@Column(name="address") private String address; //@Column(name="createdTime") private Date createdTime; //@Column(name="lastModified") private Date lastModified; //@Column(name="errorCounters",columnDefinition = "TINYINT") private Integer errorCounters; //@Column(name="enabled",columnDefinition = "TINYINT") //@Type(type = "org.hibernate.type.NumericBooleanType") private Boolean enabled; //@ElementCollection //@CollectionTable(name = "Role", joinColumns = @JoinColumn(name = "ROLE")) //@OneToMany(fetch = FetchType.EAGER, mappedBy="user", cascade = CascadeType.ALL, orphanRemoval = true) @OneToMany(fetch = FetchType.EAGER, mappedBy="user", cascade = CascadeType.ALL,orphanRemoval = true) private List<Role> roles = new ArrayList<Role>(); //private Set<Role> roles = new HashSet<Role>(); public User(){ } public User(String username,String password,String email){ this.username = username; this.password = password; this.email = email; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getCpassword() { return cpassword; } public void setCpassword(String cpassword) { this.cpassword = cpassword; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getRealname() { return realname; } public void setRealname(String realname) { this.realname = realname; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getZipcode() { return zipcode; } public void setZipcode(String zipcode) { this.zipcode = zipcode; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Date getCreatedTime() { return createdTime; } public void setCreatedTime(Date createdTime) { this.createdTime = createdTime; } public Date getLastModified() { return lastModified; } public void setLastModified(Date lastModified) { this.lastModified = lastModified; } public Integer getErrorCounters() { return errorCounters; } public void setErrorCounters(Integer errorCounters) { this.errorCounters = errorCounters; } public Boolean getEnabled() { return enabled; } public void setEnabled(Boolean enabled) { this.enabled = enabled; } public List<Role> getRoles() { return roles; } public void setRoles(List<Role> roles) { this.roles = roles; } public void addRole(Role role){ role.setUser(this); roles.add(role); } /* public void removeRole(Role role){ //look here //http://stackoverflow.com/questions/19494541/i-am-trying-to-remove-item-from-list-but-i-am-gettin-concurrent-modification-exc //http://www.iteye.com/topic/124788 String roleNameToBeRemoved = role.getROLE(); Iterator<Role> it = getRoles().iterator(); while(it.hasNext()){ Role roleTemp = it.next(); if(roleTemp.getROLE().equals(roleNameToBeRemoved)){ //roleTemp.setUser(this); it.remove(); } } */ public void removeRole(Role role){ role.setUser(null); roles.remove(role); //http://www.iteye.com/topic/124788 } }
/* * 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 sketchit; import javafx.scene.paint.Color; import javafx.scene.shape.Shape; /** * * @author Mason */ public abstract class Brush { protected double stroke; protected Color color; public abstract Shape startBrush(double x, double y); public abstract Shape brush(double x, double y); public abstract Shape stopBrush(double x, double y); public double getStroke() { return stroke; } public void setStroke(double stroke) { this.stroke = stroke; } public Color getColor() { return color; } public void setColor(Color color) { this.color = color; } }
package leetcode; import java.util.*; /** * @Author: Mr.M * @Date: 2019-03-01 21:24 * @Description: https://leetcode-cn.com/problems/lru-cache/ **/ class task { int nums; int key; public task(int nums, int key) { this.nums = nums; this.key = key; } } // 没有考虑到多个相同频率的事物,但是调用的时间不同,也就是最近时间不同的情况如何区分. class LRUCache { private PriorityQueue<task> p; private PriorityQueue<task> xiao; private HashMap<Integer, Integer> hm; private int ca = 0; public static Comparator<task> daComparator = new Comparator<task>() { @Override public int compare(task c1, task c2) { return (int) (c1.nums - c2.nums); } }; public static Comparator<task> xiaoComparator = new Comparator<task>() { @Override public int compare(task c1, task c2) { return (int) (c2.nums - c1.nums); } }; public LRUCache(int capacity) { p = new PriorityQueue<>(capacity, daComparator); hm = new HashMap<>(capacity); xiao = new PriorityQueue<>(capacity, xiaoComparator); ca = capacity; } public int get(int key) { if (p.size() > 0 && hm.containsKey(key)) { System.out.println(hm.get(key)); return hm.get(key); } else { System.out.println(-1); return -1; } } public void put(int key, int value) { if (p.size() >= ca) { hm.remove(xiao.peek().key); p.remove(xiao.peek()); xiao.remove(); } p.add(new task(1, key)); xiao.add(new task(1, key)); hm.put(key, value); } public static void main(String[] args) { LRUCache cache = new LRUCache(2); cache.put(1, 1); cache.put(2, 2); cache.get(1); // 返回 1 cache.put(3, 3); // 该操作会使得密钥 2 作废 cache.get(2); // 返回 -1 (未找到) cache.put(4, 4); // 该操作会使得密钥 1 作废 cache.get(1); // 返回 -1 (未找到) cache.get(3); // 返回 3 cache.get(4); // 返回 4 } } class Node { int key; int value; Node pre; Node next; public Node(int key, int value) { this.key = key; this.value = value; } } class LRUCache1 { HashMap<Integer, Node> map; int capicity, count; Node head, tail; public LRUCache1(int capacity) { this.capicity = capacity; map = new HashMap<>(); head = new Node(0, 0); tail = new Node(0, 0); head.next = tail; tail.pre = head; head.pre = null; tail.next = null; count = 0; } public void deleteNode(Node node) { node.pre.next = node.next; node.next.pre = node.pre; } public void addToHead(Node node) { node.next = head.next; node.next.pre = node; node.pre = head; head.next = node; } public int get(int key) { if (map.get(key) != null) { Node node = map.get(key); int result = node.value; deleteNode(node); addToHead(node); System.out.println(result); return result; } System.out.println(-1); return -1; } public void put(int key, int value) { if (map.get(key) != null) { Node node = map.get(key); node.value = value; deleteNode(node); addToHead(node); } else { Node node = new Node(key, value); map.put(key, node); if (count < capicity) { count++; addToHead(node); } else { map.remove(tail.pre.key); deleteNode(tail.pre); addToHead(node); } } } } class LRUCache2 { HashMap<Integer, Integer> map; // 不能这样使用,因为这样的情况下,只有map而没有链表,主要node提供pre与next的功能 int capicity, count; Node head, tail; }
package com.company.controllers; import com.company.dao.DishDao; import com.company.dao.EmployeeDao; import com.company.dao.OrderDao; import com.company.model.Dish; import com.company.model.Order; import org.springframework.transaction.annotation.Transactional; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Created by Yevhen on 06.06.2016. */ public class OrderController { private EmployeeDao employeeDao; private DishDao dishDao; private OrderDao orderDao; public void setEmployeeDao(EmployeeDao employeeDao) { this.employeeDao = employeeDao; } public void setDishDao(DishDao dishDao) { this.dishDao = dishDao; } public void setOrderDao(OrderDao orderDao) { this.orderDao = orderDao; } private List<Dish> createDishes(List<String> dishes) { List<Dish> result = new ArrayList<>(); for (String dishName: dishes) { result.add(dishDao.findByName(dishName)); } return result; } @Transactional public void createOrder(String waiterName, List<String> dishes, int tableNumber) { Order order = new Order(); order.setWaiter(employeeDao.findByName(waiterName)); order.setDishes(createDishes(dishes)); order.setTableNumber(tableNumber); order.setOrderDateTime(new Timestamp(new Date().getTime())); orderDao.save(order); } @Transactional public List<Order> getAllOrders() { return orderDao.findAllOrders(); } @Transactional public void printAllOrders() { getAllOrders().forEach(System.out::println); } @Transactional public void initOrders() { List<String> dishes1 = new ArrayList<>(); dishes1.add("Plov"); dishes1.add("Salad"); createOrder("John", dishes1, 1); List<String> dishes2 = new ArrayList<>(); dishes2.add("Potato"); dishes2.add("Salad"); createOrder("John", dishes2, 2); } @Transactional public void removeAllOrders() { orderDao.removeAll(); } }
package paiva.pedro.at_desenvolvimento_android.Utility; import android.content.Context; import android.widget.Toast; public class DefaultAttributes { public static int SPLASH_TIME_OUT = 3000; public static final String URL = "http://demo1846932.mockable.io/"; public static final String UsersDB = "Users"; public static void toastMessage(Context context, String message){ Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } }
package com.xiaoxiao.search.service; import com.xiaoxiao.utils.Result; /** * _ooOoo_ * o8888888o * 88" . "88 * (| -_- |) * O\ = /O * ____/`---'\____ * .' \\| |// `. * / \\||| : |||// \ * / _||||| -:- |||||- \ * | | \\\ - /// | | * | \_| ''\---/'' | | * \ .-\__ `-` ___/-. / * ___`. .' /--.--\ `. . __ * ."" '< `.___\_<|>_/___.' >'"". * | | : `- \`.;`\ _ /`;.`/ - ` : | | * \ \ `-. \_ __\ /__ _/ .-` / / * ======`-.____`-.___\_____/___.-`____.-'====== * `=---=' * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ * 佛祖保佑 永无BUG * 佛曰: * 写字楼里写字间,写字间里程序员; * 程序人员写程序,又拿程序换酒钱。 * 酒醒只在网上坐,酒醉还来网下眠; * 酒醉酒醒日复日,网上网下年复年。 * 但愿老死电脑间,不愿鞠躬老板前; * 奔驰宝马贵者趣,公交自行程序员。 * 别人笑我忒疯癫,我笑自己命太贱; * 不见满街漂亮妹,哪个归得程序员? * * @project_name:xiaoxiao_final_blogs * @date:2019/12/13:13:58 * @author:shinelon * @Describe: */ public interface ArticleSolrService { /** * 导入文章 * @return */ Result importArticleToSolr(); /** * 查询文章 * 减速od * @param query * @param page * @param rows * @return */ Result searchArticle(String query, Long page, Integer rows); /** * 插入到solr * @param articleId * @throws Exception */ void insertArticleToSolr(Long articleId)throws Exception; /** * 删除 * @param articleId * @throws Exception */ void deleteArticleToSolr(Long articleId) throws Exception; }
package com.ugarit.java.designpatterns.bridge.impl; import java.util.Random; /** * Random integer strategy implementation to generate an integer from a range * * @author durrah (mhd.durrah@gmail.com) on 5/16/15. */ public class RangeRandomIntGenerator implements RandomIntGenerator { /** * range min */ private final int low; /** * range max */ private final int high; public RangeRandomIntGenerator(int low, int high) { this.low = low; this.high = high; } /** * generator implementation * * @return a random integer between {@link #low} and {@link #high} */ @Override public int generateInteger() { return new Random().nextInt(low) + (high - low); } }
package com.naver.dao; import java.util.ArrayList; import java.util.HashMap; public interface CommandDAO { int deleteDateWords(long id, int date, int bottype); int deleteWords(long id, String word, int bottype); ArrayList<HashMap> selectPeriodWords(long id, String predate, String afterdate, int bottype); ArrayList<HashMap> selectWrongWords(long id, String predate, String afterdate, int bottype); }
package com.gtfs.service.interfaces; import java.io.Serializable; import java.util.List; import com.gtfs.bean.BranchMst; import com.gtfs.bean.LicPremPaymentDtls; public interface LicPremPaymentDtlsService extends Serializable { List<LicPremPaymentDtls> findLicPremPaymentDtls(Long id, BranchMst branchMst); }
/* * 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 pruebas; import javax.swing.JOptionPane; /** * * @author Arturo */ public class Pruebas { /** * @param args the command line arguments */ public static void main(String[] args) { String option = JOptionPane.showInputDialog("Ingrese una opción:\n"+ "1. Ingresar cliente.\n"+ "2. Consultar cliente.\n"+ "3. Modificar cliente.\n"+ "4. Eliminar cliente.\n"); switch (option){ case "1": break; case "2": //TODO break; case "3": //TODO break; case "4": //TODO break; } } }
package com.anywaycloud.dao; import com.anywaycloud.model.UserFile; public interface UserFileMapper { int deleteByPrimaryKey(Integer id); int insert(UserFile record); int insertSelective(UserFile record); UserFile selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(UserFile record); int updateByPrimaryKey(UserFile record); }
package com.bcgbcg.br.controller; import java.io.File; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; 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.multipart.MultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.bcgbcg.br.command.GoodsCommand; import com.bcgbcg.br.dto.GoodsDto; import com.bcgbcg.br.dto.PurchaseDto; import com.bcgbcg.br.dto.UserDto; import com.bcgbcg.br.util.UploadFileUtils; @Controller public class GoodsController { @Autowired private GoodsCommand goodsCommand; @RequestMapping(value="goodsPayStateMent") public String goodsPayStateMent(Model model) { return "goods/goodsPayStateMent"; } @RequestMapping("adminGoodsPage") public String adminGoods(Model model) { return "goods/adminGoods"; } @Resource(name="uploadPath") private String uploadPath; @RequestMapping(value="GoodsPostPage" , method = RequestMethod.POST) public String postGoods(GoodsDto gdto, MultipartFile file) throws Exception { String imgUploadPath = uploadPath + File.separator + "imgUpload"; String ymdPath = UploadFileUtils.calcPath(imgUploadPath); String fileName = null; if(file != null) { fileName = UploadFileUtils.fileUpload(imgUploadPath, file.getOriginalFilename(), file.getBytes(), ymdPath); } else { fileName = uploadPath + File.separator + "images" + File.separator + "none.png"; } gdto.setgImage(File.separator + "imgUpload" + ymdPath + File.separator + fileName); goodsCommand.Goods(gdto); return "redirect:/adminGoodsViewPage"; } @RequestMapping("adminGoodsViewPage") public String GoodsList(Model model) throws Exception { goodsCommand.GoodsSoldOut(); List<GoodsDto> list = goodsCommand.Goodslist(); model.addAttribute("list", list); return "goods/adminGoodsView"; } @RequestMapping("goodsViewPage") public String GoodsUserList(Model model) throws Exception { goodsCommand.GoodsSoldOut(); List<GoodsDto> list = goodsCommand.Goodslist(); model.addAttribute("list", list); return "goods/goodsView"; } @RequestMapping(value="adminGoodsModifyPage" , method = RequestMethod.GET) public String GoodsDes(@RequestParam("gIdx") int gIdx , Model model) throws Exception { GoodsDto gdto = goodsCommand.GoodsDes(gIdx); model.addAttribute("gdto", gdto); return "goods/adminGoodsModify"; } @RequestMapping(value="adminModifyRegPage", method = RequestMethod.POST) public String GoodsModify(GoodsDto gdto) throws Exception { goodsCommand.GoodsModify(gdto); goodsCommand.GoodsSoldOut(); return "redirect:/adminGoodsViewPage"; } @RequestMapping("adminGoodsDeletePage") public String GoodsDelete(@RequestParam("gIdx") int gIdx , Model model) throws Exception { goodsCommand.GoodsDelete(gIdx); return "redirect:/adminGoodsViewPage"; } @RequestMapping("goodsBuyPage") public String GoodsBuyDes(@RequestParam("gIdx") int gIdx , Model model) throws Exception { GoodsDto gdto = goodsCommand.GoodsBuyMove(gIdx); model.addAttribute("gdto", gdto); return "goods/goodsBuyDes"; } @RequestMapping("goodsPayPage") public String GoodsPayPage(@RequestParam("gIdx") int gIdx , Model model) throws Exception { GoodsDto gdto = goodsCommand.GoodsPayMove(gIdx); model.addAttribute("gdto", gdto); return "goods/goodsPayDes"; } @RequestMapping(value="payDecision", method = RequestMethod.POST) public String PayDecision(@RequestParam("gIdx") int gIdx, @RequestParam("gPrice") int gPrice, @RequestParam("uIdx") int uIdx, @RequestParam("uId_") String uId_, PurchaseDto pdto, HttpServletRequest request, RedirectAttributes rttr, Model model) throws Exception { goodsCommand.PayDecision(gIdx); // 재고수량 1개 빠짐. goodsCommand.PayDecision_User(gPrice, uIdx); //고객정보에서 포인트 차감 goodsCommand.PurchaseInsert(pdto); GoodsDto gdto = goodsCommand.GoodsDes(gIdx); // 물품정보 저장 HttpSession session = request.getSession(); // 현재 세션 정보를 가져옴. session.setAttribute("gdto", gdto); // 구매한 물품값 넘기기 session.setAttribute("pdto", pdto); // 배송정보 넘기기 UserDto loginDto = new UserDto(); session.removeAttribute("loginDto"); loginDto = goodsCommand.loginUpdate(uIdx); session.setAttribute("loginDto", loginDto); return "redirect:/goodsPayStateMent"; } }
package com.penzias.service; import com.penzias.core.interfaces.BasicService; import com.penzias.entity.ApoplexyConclusionInfo; import com.penzias.entity.ApoplexyConclusionInfoExample; public interface ApoplexyConclusionInfoService extends BasicService<ApoplexyConclusionInfoExample, ApoplexyConclusionInfo> { }
public class Node<E> { protected Node<E> left, right; protected E data; public Node() { left = null; right = null; data = null; } public Node(E n) { left = null; right = null; this.data = n; } public E getData() { return data; } public Node<E> getRight() { return right; } public Node<E> getLeft() { return left; } }
package apache_POI; public class DataReadingFromExcel { }
package com.example.demo.dao; import com.example.demo.entity.SysUserRole; import com.example.demo.mapper.IMapper; public interface SysUserRoleMapper extends IMapper<SysUserRole> { }
package demo06; import java.util.Iterator; import java.util.concurrent.PriorityBlockingQueue; public class UsePriorityBlockingQueue { public static void main(String[] args) throws InterruptedException { PriorityBlockingQueue<Task> p =new PriorityBlockingQueue<Task>(); Task t1 = new Task(); t1.setId(3); t1.setName("任务1"); Task t2 = new Task(); t2.setId(6); t2.setName("任务2"); Task t3 = new Task(); t3.setId(1); t3.setName("任务3"); p.add(t1); p.add(t2); p.add(t3); System.out.println("容器:"+p); System.out.println(p.take().getId()); System.out.println("容器:"+p); /*for (Iterator iterator = p.iterator(); iterator.hasNext();) { Task task = (Task) iterator.next(); System.out.println(task.getName()); }*/ } }
package com.leetcode.wangruns; //20、palindrome-partitioning-ii[动态规划] /** * Given a string s, partition s such that every substring of the partition is a palindrome. * Return the minimum cuts needed for a palindrome partitioning of s. * For example, given s ="aab", * Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut. * * a,using 0 cut * aa,using 0 cut * aab,using 1 cut * aabb,using 1 cut * aabbh,using 2 cut * ... * 尝试当前状态和之前的状态的关系,联想到动态规划 * dp[i]表示0到下标i这个字符的最小分割数,所dp[s.length()-1]就是最佳解 * 那么dp[i]和dp[i-1]有什么关系呢? * 如s="aab" * dp[0]=0 * dp[1]=0 * dp[2]=1 * 可以发现对于dp[i]来说 * 如果s[0:i]是回文:那么dp[i]=0 * 如果s[0:i]不是回文: * 1<=j<=i * 如果s[j:i]是回文,那么dp[i]=dp[j-1]+1 * 如果s[j:i]不是回文,那么dp[i]=dp[j-1]+i-j+1 */ public class PalindromePartitioningii020 { public int minCut(String s) { int len=s.length(); int dp[]=new int[len]; //对于每一个长度a,aa,aab得到对应的dp[i] for(int i=0;i<len;i++){ String curStr=s.substring(0, i+1); //如果当前的字符串是回文,则dp[i]直接赋值0 if(isPalindrome(curStr)) dp[i]=0; else{ //最多i次分割(初始化成最大的便于比较得到最小的) dp[i]=i; //如果当前字符串不是回文的话,则需要观看之前的记录来确定当前字符串的最小分割数 for(int j=1;j<=i;j++){ if(isPalindrome(s.substring(j,i+1))){ //如果存在1<=k<=i,使得s[k:i]是回文,那么dp[i]=d[k-1]+1 dp[i]=Math.min(dp[i], dp[j-1]+1); }else{ //如果不存在,那么dp[i]=dp[k-1]+i-k+1;如 acd -> a|c|d dp[i]=Math.min(dp[i], dp[j-1]+i-j+1); } } } } return dp[len-1]; } //判定一个字符串是不是回文 private boolean isPalindrome(String s) { int l=0,r=s.length()-1; while(l<r){ if(s.charAt(l)!=s.charAt(r)) return false; l++;r--; } return true; } }
/* * 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 safeflyeu.view; import safeflyeu.controller.ObradaOsiguranje; /** * * @author labak */ public class SplashScreen extends javax.swing.JFrame { /** * Creates new form SplashScreen */ public SplashScreen() { initComponents(); ProvjeriSpajanjeNaBazu p = new ProvjeriSpajanjeNaBazu(); p.start(); } private class ProvjeriSpajanjeNaBazu extends Thread { @Override public void run() { lblPoruka.setText("Inicijaliziram..."); for(int i=1;i<50;i++){ jProgressBar1.setValue(i); try { Thread.sleep(50); } catch (Exception e) { } } lblPoruka.setText("Spajam se na bazu...."); if(new ObradaOsiguranje().getLista().size()>-1){ lblPoruka.setText("Uspješno startam program"); for(int i=75;i<=100;i++){ jProgressBar1.setValue(i); try { Thread.sleep(30); } catch (Exception e) { } } new Login().setVisible(true); dispose(); }else { } } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); lblPoruka = new javax.swing.JLabel(); jProgressBar1 = new javax.swing.JProgressBar(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/safeflyeu/view/avion.jpg"))); // NOI18N jLabel1.setText("jLabel1"); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setUndecorated(true); setType(java.awt.Window.Type.POPUP); getContentPane().setLayout(null); lblPoruka.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N lblPoruka.setForeground(new java.awt.Color(0, 0, 0)); getContentPane().add(lblPoruka); lblPoruka.setBounds(40, 190, 330, 20); getContentPane().add(jProgressBar1); jProgressBar1.setBounds(0, 230, 400, 10); jLabel2.setForeground(new java.awt.Color(0, 0, 0)); jLabel2.setText("Great application for finding flights in Europe"); getContentPane().add(jLabel2); jLabel2.setBounds(0, 0, 320, 30); jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/safeflyeu/view/avion.jpg"))); // NOI18N jLabel3.setText("jLabel3"); getContentPane().add(jLabel3); jLabel3.setBounds(0, 0, 400, 250); setSize(new java.awt.Dimension(397, 250)); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JProgressBar jProgressBar1; private javax.swing.JLabel lblPoruka; // End of variables declaration//GEN-END:variables }
package networking.mail.examples; import javax.mail.*; import javax.mail.internet.*; import javax.swing.JOptionPane; import javax.swing.JPasswordField; import java.util.*; public class SendSMTPMail { public static void main(String[] args) { // TODO Auto-generated method stub String username = "chrisxstone1@gmail.com"; String password = ""; String smtphost = "smtp.gmail.com"; // Step 1: Set all Properties // Get system properties Properties props = System.getProperties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", smtphost); props.put("mail.smtp.port", "587"); // Input password JPasswordField pwd = new JPasswordField(10); int action = JOptionPane.showConfirmDialog(null, pwd,"Enter Password",JOptionPane.OK_CANCEL_OPTION); if(action < 0) { JOptionPane.showMessageDialog(null,"Cancel, X or escape key selected"); System.exit(0); } else password = new String(pwd.getPassword()); // Set Property with username and password for authentication props.setProperty("mail.user", username); props.setProperty("mail.password", password); //Step 2: Establish a mail session (java.mail.Session) Session session = Session.getDefaultInstance(props); try { // Step 3: Create a message MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress("heshan@gmail.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("heshan@gmail.com")); message.setSubject("Testing"); message.setText("Dear SSC student," + "\n\n Try this example, please!"); message.saveChanges(); // Step 4: Send the message by javax.mail.Transport . Transport tr = session.getTransport("smtp"); // Get Transport object from session tr.connect(smtphost, username, password); // We need to connect tr.sendMessage(message, message.getAllRecipients()); // Send message System.out.println("Done"); } catch (MessagingException e) { throw new RuntimeException(e); } } }
package cn.cj.spring_boot.dao; import java.util.List; import org.springframework.stereotype.Component; import cn.cj.spring_boot.domain.BaseDict; @Component public interface BaseDictDao { List<BaseDict> getDictListByTypeCode(String typeCode); }
package saim_only_03_27; public class OddNumberDivisible3_5 { public static void main(String[] args) { for(int num=1; num<=100; num++){ if(num %2 !=0 && num %3==0 && num %5 ==0 ){ System.out.println("Odd numbers "+num +" can be divided by 3 and 5 "); } } } }
package com.usecasepoint.service; import com.usecasepoint.exception.EntityNotFoundEx; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public class AbstractService<T> implements ServiceInterface<T, String>{ protected final JpaRepository<T, String> repository; public AbstractService(JpaRepository<T, String> repository) { this.repository = repository; } @Override public T findById(String id) { return repository.findById(id).orElseThrow(EntityNotFoundEx::new); } @Override public List<T> findAll() { return repository.findAll(); } @Override public T deleteById(String id) { T entity = findById(id); repository.deleteById(id); return entity; } @Override public T save(T entity) { return repository.save(entity); } }
package Types; import java.util.List; public class Expr { public int value; Variables vars; int depth; Term term; String connector; Expr expr; List tokens; public Expr(List tokens,Variables vars, int depth) { this.tokens = tokens; this.depth = depth; this.vars = vars; } public void Parse() { if(Print.printTree) Print.tree(this.getClass().getName(),tokens, depth); int index = 0; int parenCount = 0; if(tokens.contains("PLUS") || tokens.contains("MINUS")) { while(parenCount > 0 || (!(tokens.get(index).equals("PLUS") || tokens.get(index).equals("MINUS")))){ if(tokens.get(index).equals("LEFTPAREN")) { parenCount++; }else if(tokens.get(index).equals("RIGHTPAREN")) { parenCount--; } if(index == tokens.size()-1) { if (parenCount > 0) { Print.error(this.getClass().getName() + " ERROR: Mismatching parenthesis"); } term = new Term(tokens.subList(0, tokens.size()),vars,depth+1); term.Parse(); return; } index++; } term = new Term(tokens.subList(0, index),vars,depth+1); expr = new Expr(tokens.subList(index+1, tokens.size()),vars,depth+1); term.Parse(); expr.Parse(); if(tokens.get(index).equals("PLUS")) { connector = "+"; }else { connector = "-"; } }else { term = new Term(tokens,vars,depth+1); term.Parse(); } } public void Exec() { term.Exec(); if (expr != null) { expr.Exec(); if (connector == "+") { value = term.value + expr.value; } else { value = term.value - expr.value; } } else { value = term.value; } } }
package interaccionobjetos; public class PersonaPrivada { private String nombre; private int edad; public PersonaPrivada(String nombre, int edad) { this.nombre = nombre; this.edad = edad; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public int getEdad() { return edad; } public void setEdad(int edad) { this.edad = edad; } public String saludar() { return "Hola, mi nombre es "+nombre+" y soy un objeto Privado"; } public String saludoInicialMutuo(String nombreSaludado) { return "Hola "+nombreSaludado+", Como estas?"; } public String saludoRespuestaMutuo(String nombreSaludado, String estadoAnimo) { return "Hola "+nombreSaludado+" estoy "+estadoAnimo+", muchas gracias!"; } }
package com.yoeki.kalpnay.hrporatal.Jobposting; public class Jobpostingmodel { String nocadicdates; String opening; String hiringlead; String createdon; String status; public String getNocadicdates() { return nocadicdates; } public void setNocadicdates(String nocadicdates) { this.nocadicdates = nocadicdates; } public String getOpening() { return opening; } public void setOpening(String opening) { this.opening = opening; } public String getHiringlead() { return hiringlead; } public void setHiringlead(String hiringlead) { this.hiringlead = hiringlead; } public String getCreatedon() { return createdon; } public void setCreatedon(String createdon) { this.createdon = createdon; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
package com.zstu.Filter; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.io.IOException; public class OneFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request =(HttpServletRequest) servletRequest; HttpSession session =null; String url =request.getRequestURI(); if (url.indexOf("login")!=-1||"/zstuexam/".equals(url)){ filterChain.doFilter( servletRequest, servletResponse); return; } session=request.getSession(false); if(session!=null){ filterChain.doFilter( servletRequest, servletResponse); return; } request.getRequestDispatcher("/login.html").forward(servletRequest,servletResponse); } }
package com.intraway.exception; import javax.validation.ConstraintViolationException; public class TransactionRefuseException extends RuntimeException { public TransactionRefuseException(ConstraintViolationException e){ super(e.getMessage()); } }
package by.imag.app; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.CursorAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.ProgressBar; import com.google.gson.Gson; import com.squareup.picasso.Picasso; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import by.imag.app.classes.Constants; import by.imag.app.classes.HtmlParserThread; import by.imag.app.classes.MagItem; import by.imag.app.json.Doc; import by.imag.app.json.JsonResponse; import by.imag.app.json.Response; public class FragmentMag extends BaseFragment{ //http://search.issuu.com/api/2_0/document?q=username:vovic2000&sortBy=epoch&pageSize=6 //http://search.issuu.com/api/2_0/document?q=documentId:140109103402-1931c53b51bfbd91c262c9e0f3308319&responseParams=* //http://search.issuu.com/api/2_0/document?q=username:vovic2000&sortBy=epoch&pageSize=6&responseParams=* private final String magPageUrl = "http://i-mag.by/?page_id=641"; private final String issuuUrl = "http://search.issuu.com/api/2_0/" + "document?q=username:vovic2000&sortBy=epoch&pageSize="; private int magCount; private boolean update; private AppDb appDb; private SharedPreferences preferences; private SharedPreferences defaultPrefs; private GridView gridView; private ProgressBar pbMag; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_mag, container, false); appDb = new AppDb(getActivity().getApplicationContext()); preferences = getActivity().getPreferences(Context.MODE_PRIVATE); defaultPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext()); gridView = (GridView) rootView.findViewById(R.id.gridMag); pbMag = (ProgressBar) rootView.findViewById(R.id.pbMag); loadPreferences(); // logMsg("update: "+update); if (isOnline() && update) { new MagListLoader().execute(); } setActionBarSubtitle(3); // setView(); return rootView; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } @Override public void onResume() { super.onResume(); setView(); } private void setView() { Cursor cursor = appDb.getMagCursor(); MagCursorAdapter magCursorAdapter = new MagCursorAdapter(getActivity(), cursor, true); gridView.setAdapter(magCursorAdapter); gridView.setNumColumns(getNumColumns()); onMagClick(); } private void onMagClick() { gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long _id) { MagItem magItem = appDb.getMagItem(_id); Intent magIntent; String prefsKey = getActivity().getResources().getString(R.string.pref_mag_style_key); // logMsg("prefsKey: "+prefsKey); String style = defaultPrefs.getString(prefsKey, "200"); // logMsg("prefs: "+style); int pref = Integer.parseInt(style); switch (pref) { case Constants.MAG_STYLE_BUTTONS: magIntent = new Intent(getActivity(), ActivityMag.class); break; case Constants.MAG_STYLE_SLIDE: magIntent = new Intent(getActivity(), ActivityMagPager.class); break; default: magIntent = new Intent(getActivity(), ActivityMag.class); } // logMsg("magItem: "+magItem); // magIntent = new Intent(getActivity(), ActivityMag.class); // magIntent = new Intent(getActivity(), ActivityMagPager.class); Bundle magBundle = new Bundle(); magBundle.putString(Constants.MAG_ID, magItem.getMagId()); String magTitle = magItem.getMagTitle(); // logMsg("magTitle: " + magTitle); magTitle = magTitle.replace("Журнал \"Я\" ", ""); // logMsg("magTitle: "+magTitle); magBundle.putString(Constants.MAG_TITLE, magTitle); magBundle.putString(Constants.MAG_URL, magItem.getMagUrl()); magBundle.putInt(Constants.MAG_POST_COUNT, magItem.getMagPageCount()); magIntent.putExtra(Constants.MAG_INTENT, magBundle); startActivity(magIntent); } }); } @SuppressWarnings("deprecation") private int getNumColumns() { float gridSize = getResources().getDimension(R.dimen.mag_item_width); int number = getActivity().getWindowManager().getDefaultDisplay().getWidth(); int columns = (int) ((float) number / gridSize); return columns; } private void savePreferences() { SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean(Constants.UPDATE_MAGS, false); editor.commit(); } private void loadPreferences() { update = preferences.getBoolean(Constants.UPDATE_MAGS, true); } // private boolean isOnline() { // ConnectivityManager connectivityManager = // (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); // NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); // if (networkInfo != null && networkInfo.isConnected()) { // // networkInfo.isConnected // // networkInfo.isConnectedOrConnecting() // return true; // } // return false; // } // // private void logMsg(String msg) { // Log.d(Constants.LOG_TAG, ((Object) this).getClass().getSimpleName() + ": " + msg); // } private class MagListLoader extends AsyncTask<Void, Void, Boolean> { @Override protected void onPreExecute() { super.onPreExecute(); pbMag.setVisibility(View.VISIBLE); } @Override protected Boolean doInBackground(Void... voids) { boolean result = false; Document document = null; ExecutorService executorService = Executors.newFixedThreadPool(1); Future<Document> documentFuture = executorService.submit( new HtmlParserThread(magPageUrl)); try { document = documentFuture.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } executorService.shutdown(); if (document != null) { Elements elements = document.select(".issuuembed"); if (elements.size() > 0) { // logMsg("text: "+elements.get(0).toString()); magCount = elements.size(); } } String magUrl = "http://search.issuu.com/api/2_0/document?" + "q=username:vovic2000&sortBy=epoch&pageSize=" + magCount + "&responseParams=*"; try { URL url = new URL(magUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(30000); connection.setReadTimeout(30000); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { Gson gson = new Gson(); InputStreamReader inputStreamReader = new InputStreamReader(url.openStream()); // logMsg("stream:"+inputStreamReader); JsonResponse jsonResponse = gson.fromJson(inputStreamReader, JsonResponse.class); // logMsg("jsonResponse: "+jsonResponse); Response response = jsonResponse.getResponse(); // logMsg("response: "+response); ArrayList<Doc> docs = response.getDocs(); // logMsg("docs: "+docs); ArrayList<MagItem> magItems = new ArrayList<MagItem>(); for (Doc d: docs) { MagItem magItem = new MagItem( d.getId(), d.getTitle(), d.getUrl(), d.getPageCount() ); magItems.add(magItem); } result = appDb.writeMagTable(magItems); connection.disconnect(); // logMsg("result: "+result); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); // logMsg("result: "+result); if (result) { if (isAdded()) { setView(); } savePreferences(); } pbMag.setVisibility(View.GONE); } } private class MagCursorAdapter extends CursorAdapter { public MagCursorAdapter(Context context, Cursor c, boolean autoRequery) { super(context, c, autoRequery); } @Override public View newView(Context context, Cursor cursor, ViewGroup viewGroup) { LayoutInflater layoutInflater = LayoutInflater.from(context); View view = layoutInflater.inflate(R.layout.mag_grid_item, viewGroup, false); bindView(view, context, cursor); return view; } @Override public void bindView(View view, Context context, Cursor cursor) { ImageView imageView = (ImageView) view.findViewById(R.id.imgMag); String imageUrl = cursor.getString(cursor.getColumnIndex(AppDb.MAG_IMG_URL)); Picasso.with(context).load(imageUrl).placeholder(R.drawable.placeholder) .error(R.drawable.logo_red) .into(imageView); } } }
package com.zyq.service.impl; import com.zyq.mapper.LoginMapper; import com.zyq.pojo.User; import com.zyq.service.LoginService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @author 邹雨樵 * @date 2019/7/22 * @since 1.0.0 */ @Service public class LoginServiceImpl implements LoginService { private final LoginMapper loginMapper; @Autowired public LoginServiceImpl(LoginMapper loginMapper) { this.loginMapper = loginMapper; } /** * 登录方法 * * @param loginName 登录名 * @param passWord 密码 * @return 返回对象 */ public User login(String loginName, String passWord) { return loginMapper.login(loginName, passWord); } }
package com.java8.lambda.cart; import lombok.Getter; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; @Getter public class CartService { // 加一点假数据 public List<Product> cartList = new ArrayList<Product>() { { add(Product.builder().productId(110) .productName("helicopter") .productPrice(100.00) .totalNum(1) .productCategory(ProductCategoryEnum.ELECTRONICS) .totalPrice(100.00).build()); add(Product.builder().productId(120) .productName("iphone") .productPrice(200.00) .totalNum(2) .productCategory(ProductCategoryEnum.ELECTRONICS) .totalPrice(400.00).build()); add(Product.builder().productId(130) .productName("t-shirt") .productPrice(10.00) .totalNum(2) .totalPrice(20.00) .productCategory(ProductCategoryEnum.CLOTHING) .build()); add(Product.builder().productId(140) .productName("javaBook") .productPrice(100.00) .totalNum(1) .productCategory(ProductCategoryEnum.BOOKS) .totalPrice(100.00).build()); add(Product.builder().productId(150) .productName("soccer") .productPrice(10.00) .totalNum(2) .totalPrice(20.00) .productCategory(ProductCategoryEnum.SPORTS) .build()); } }; // 需求1:找出购物车中所有电子产品 public static List<Product> getAllElectricProduct(List<Product> cartList) { List<Product> result = new ArrayList<>(); for (Product product : cartList) { if (product.getProductCategory().equals("数码")) { result.add(product); } } return result; } // 需求2:购物车中某种类型的商品有哪些 public static List<Product> getSpecificProductByCategory(ProductCategoryEnum productCategoryEnum, List<Product> cartList) { List<Product> result = new ArrayList<>(); for (Product product : cartList) { if (product.getProductCategory().equals(productCategoryEnum.ELECTRONICS)) { result.add(product); } } return result; } // 需求3:根据不同的product判断标准,对cartList列表进行过滤 public static List<Product> getSpecificProduct(List<Product> cartList, Predicate<Product> productPredicate) { List<Product> result = new ArrayList<>(); for (Product product : cartList) { // 判断是否符合过滤标准 if (productPredicate.test(product)) { result.add(product); } } return result; } }
package Kap2.Aufgabe1; import javax.json.bind.annotation.JsonbPropertyOrder; import java.util.ArrayList; import java.util.List; @JsonbPropertyOrder({"id", "name", "hobbies"}) public class Person { private int id; private String name; private List<String> hobbies; public Person() { } public Person(int id, String name) { this.id = id; this.name = name; hobbies = new ArrayList<>(); } public void addHobby(String hobby) { hobbies.add(hobby); } public int getId() { return id; } public List<String> getHobbies() { return hobbies; } public void setHobbies(List<String> hobbies) { this.hobbies = hobbies; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Person{" + "id=" + id + ", name='" + name + '\'' + ", hobbies=" + hobbies + '}'; } }
package com.awsp8.wizardry.Items; import com.awsp8.wizardry.Wizardry; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.World; /** * Can be planted on Dirt, Grass, or Mycelium * @author Awesome_Spider * */ public class MaztrixSapling extends Item{ public MaztrixSapling(int maxStackSize, int texture, String name) { setMaxStackSize(maxStackSize); setUnlocalizedName(name); setTextureName("wizardry:maztrixSapling"); } @Override public boolean onItemUseFirst(ItemStack item, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ){ boolean result = false; if (world.getBlock(x, y, z) == Blocks.dirt){ //Check if the block is dirt player.inventory.consumeInventoryItem(item.getItem()); world.setBlock(x, y + 1, z, Wizardry.blockMaztrixSapling); result = true; } else if (world.getBlock(x, y, z) == Blocks.grass){ //If it isn't, check if the block is grass player.inventory.consumeInventoryItem(item.getItem()); world.setBlock(x, y + 1, z, Wizardry.blockMaztrixSapling); result = true; } else if (world.getBlock(x, y, z) == Blocks.mycelium){ //If it still isn't, check if the block is mycelium player.inventory.consumeInventoryItem(item.getItem()); world.setBlock(x, y + 1, z, Wizardry.blockMaztrixSapling); result = true; } return result; } }
package com.streming.kafka.intercept; import org.apache.kafka.clients.consumer.ConsumerInterceptor; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.OffsetAndMetadata; import org.apache.kafka.common.TopicPartition; import java.util.Map; /** * @fileName: CustomInterceptor.java * @description: CustomInterceptor.java类说明 * @author: by echo huang * @date: 2020-08-02 21:35 */ public class CustomInterceptor implements ConsumerInterceptor<String, String> { @Override public ConsumerRecords<String, String> onConsume(ConsumerRecords<String, String> records) { return null; } @Override public void onCommit(Map<TopicPartition, OffsetAndMetadata> offsets) { } @Override public void close() { } @Override public void configure(Map<String, ?> configs) { } }
package PresentationLayer.Controller; import BusinessLayer.DeliveryService; import PresentationLayer.View.RaportView; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.FileNotFoundException; /** * The type Raport controller. */ public class RaportController { /** * The Raport view. */ RaportView raportView ; /** * The Delivery service. */ DeliveryService deliveryService ; /** * Instantiates a new Raport controller. * * @param deliveryService the delivery service */ public RaportController(DeliveryService deliveryService){ raportView = new RaportView(); this.deliveryService = deliveryService; raportView.generateRepBtn(new GenerateListener()); } /** * The type Generate listener. */ class GenerateListener implements ActionListener { @Override public void actionPerformed(ActionEvent actionEvent) { System.out.println("Pressed Generate Report ADMIN"); int intervalMin , intervalMax , valueHigher,day , clientsOrdered , productsOrdered; intervalMin = Integer.parseInt(raportView.getIntervalMin()); intervalMax = Integer.parseInt(raportView.getIntervalMax()); productsOrdered = Integer.parseInt(raportView.getProductsOrderedMore()); clientsOrdered = Integer.parseInt(raportView.getClientsOrdered()); valueHigher = Integer.parseInt(raportView.getValueHigher()); day = Integer.parseInt(raportView.getIntervalDay()); try { deliveryService.generateReports(intervalMin , intervalMax , productsOrdered , clientsOrdered , valueHigher , day); } catch (FileNotFoundException e) { e.printStackTrace(); } System.out.println(intervalMin +" "+ intervalMax+ " "+ productsOrdered +" "+ clientsOrdered +" "+ valueHigher +" "+ day); } } }
/* * 2012-3 Red Hat Inc. and/or its affiliates and other contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.overlord.rtgov.call.trace.descriptors; import org.overlord.rtgov.activity.model.ActivityType; /** * This class provides a factory for task descriptors. * */ public final class TaskDescriptorFactory { private static TaskDescriptor _defaultDescriptor=new DefaultTaskDescriptor(); private static java.util.List<TaskDescriptor> _descriptors= new java.util.ArrayList<TaskDescriptor>(); static { _descriptors.add(new LogMessageTaskDescriptor()); } /** * Private constructor. */ private TaskDescriptorFactory() { } /** * This method returns a task descriptor appropriate for the * supplied activity type. * * @param at The activity type * @return The task descriptor */ public static TaskDescriptor getTaskDescriptor(ActivityType at) { TaskDescriptor ret=_defaultDescriptor; for (TaskDescriptor td : _descriptors) { if (td.isSupported(at)) { ret = td; break; } } return (ret); } }
class PenBuilder { private PenImpl pen = new PenImpl(); PenBuilder withColor(PenColor color) { pen.setColor(color); return this; } PenBuilder withWidth(PenWidth width) { pen.setWidth(width); return this; } Pen build() { return pen; } }
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; public class MiniMapModel extends Model { //updateLocationAndDirection() will contain the logic that allows the bird to move in the x or y direction based on user input @Override public void updateLocationAndDirection() { } //Will update the minimap image based on the travel path of both birds, and will generate a point where the bird currently is on the map public void plotPoint() { } } //----------------------------------------------------------------------------------------------------- //JUnit Tests class MiniMapModelTest { @Test public void testUpdateLocationAndDirection() { MiniMapModel test = new MiniMapModel(); test.setXloc(0); test.setxVector(1); test.updateLocationAndDirection(); assertNotEquals(0, test.getXloc()); assertNotEquals(1, test.getxVector()); } @Test public void testPlotPoint() { //can't test at this time } }
package org.twittercity.twitterdataminer.searchtwitter; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; import org.twittercity.twitterdataminer.TwitterException; import org.twittercity.twitterdataminer.http.HttpResponse; import org.twittercity.twitterdataminer.json.ParseUtil; /** * Data object tha represents a Result for SearchAPI request * */ public class SearchResult { private String refreshUrl; private String nextResults; private List<Status> tweets; public SearchResult(HttpResponse res) throws TwitterException { try { JSONObject json = res.asJSONObject(); refreshUrl = ParseUtil.getString("refresh_url", json.getJSONObject("search_metadata")); nextResults = ParseUtil.getString("next_results", json.getJSONObject("search_metadata")); JSONArray array = json.getJSONArray("statuses"); tweets = new ArrayList<Status>(array.length()); for (int i = 0; i < array.length(); i++) { JSONObject tweet = array.getJSONObject(i); tweets.add(new Status(tweet)); } } catch (TwitterException te) { throw new TwitterException(te.getMessage()); } } public boolean hasNextResults() { return (nextResults != null) ? true : false; } public String getRefreshUrl() { return refreshUrl; } public String getNextResults() { return nextResults; } public List<Status> getTweets() { return tweets; } @Override public String toString() { return "Refresh Url: " + refreshUrl + "Next Results: " + nextResults; } }
package ga.islandcrawl.building; import ga.islandcrawl.draw.Oval; import ga.islandcrawl.form.Campfire; import ga.islandcrawl.form.Form; import ga.islandcrawl.object.Item; import ga.islandcrawl.object.Tag; import ga.islandcrawl.object.unit.Man; import ga.islandcrawl.other.WordMap; import ga.islandcrawl.state.Fire; /** * Created by Ga on 7/10/2015. */ public class Cauldron extends Constructor implements Construction { private Item fuel, content; public Cauldron(String seed) { super(seed, new FormCauldron()); getForm().rotatable = false; pos.r = .12f; state.setStat("health", 300); } @Override public void interact(Man t) { Item item = t.getItem(); if (item != null) { boolean dead = (fuel == null || !fuel.alive); if (t.getItemTag(Tag.Combustible)) { t.drop().place(pos); if (dead) fuel = item; else fuel.state.addHealth(item.state.getStat("health")); item.setDepth(10, 5); item.state.addEffect("Fire", new Fire(1, -1)); t.say("Kindled cauldron."); } else if (dead) { t.say("I should burn some more wood first."); } else if (fuel.alive) { if (content == null || !content.alive){ t.say(WordMap.word(content.name) + " is currently occupying the cauldron."); } else if (!item.tag.has(Tag.Alchemical)) { t.say(WordMap.word(item.name) + " is not an alchemical item."); } else { t.drop().place(pos); content = item; item.setDepth(10, -1); fuel.hit(2, null); t.say("Threw in " + WordMap.word(item.name) + "."); } } } } } class FormCauldron extends Form { Form campfire; Oval bowl, hole; public FormCauldron(){ organs.add(campfire = new Campfire()); organs.add(bowl = new Oval(.08f,.08f,new float[]{.33f,.33f,.33f,1})); organs.add(hole = new Oval(.06f,.05f,new float[]{0,0,0,1})); hole.offsetR.y = -.037f; bowl.offsetR.y = -.007f; } }
package com.tencent.mm.plugin.gallery; import com.tencent.mm.bt.h.d; import com.tencent.mm.model.ar; import java.util.HashMap; class Plugin$2 implements ar { final /* synthetic */ Plugin jAc; Plugin$2(Plugin plugin) { this.jAc = plugin; } public final HashMap<Integer, d> Ci() { return null; } public final void gi(int i) { } public final void bn(boolean z) { } public final void bo(boolean z) { } public final void onAccountRelease() { } }
package com.lfd.day0130_03_anim; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.graphics.drawable.AnimationDrawable; import android.view.Menu; import android.view.View; import android.widget.ImageView; public class MainActivity extends Activity { private ImageView iv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void frameanim(View view){ startActivity(new Intent(this,FrameActivity.class)); } public void tweenanim(View view){ startActivity(new Intent(this, TweenActivity.class)); } }