text
stringlengths
10
2.72M
/** https://www.hackerrank.com/challenges/bfsshortreach/problem #bfs #shortest-path */ import java.util.ArrayList; import java.util.Deque; import java.util.LinkedList; import java.util.Scanner; public class NormalBFS { static void BFS( int startNode, ArrayList<ArrayList<Integer>> graph, ArrayList<Integer> path, ArrayList<Boolean> visited) { Deque<Integer> queue = new LinkedList<Integer>(); queue.addLast(startNode); visited.set(startNode, true); while (!queue.isEmpty()) { int node = queue.pollFirst(); for (int i : graph.get(node)) { if (visited.get(i) == false) { path.set(i, node); visited.set(i, true); queue.addLast(i); } } } } static int getVisitedNode(int s, int f, ArrayList<Integer> path) { if (s == f) { return 0; } if (path.get(f) == -1) { return 0; } else { return 1 + getVisitedNode(s, path.get(f), path); } } static String getResult(int startNode, int targetNode, ArrayList<Integer> path) { String rs = ""; if (startNode != targetNode) { int temp = getVisitedNode(startNode, targetNode, path); rs = String.valueOf((temp != 0) ? (temp * 6) : -1) + " "; } return rs; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int q = sc.nextInt(); ArrayList<String> rt = new ArrayList<>(); for (int k = 0; k < q; k++) { int n = sc.nextInt(); int m = sc.nextInt(); ArrayList<Integer> path = new ArrayList<>(n + 1); ArrayList<Boolean> visited = new ArrayList<>(n + 1); ArrayList<ArrayList<Integer>> graph = new ArrayList<ArrayList<Integer>>(n + 1); for (int i = 0; i < n + 1; ++i) { graph.add(new ArrayList<Integer>()); path.add(-1); visited.add(false); } for (int i = 0; i < m; ++i) { int u = sc.nextInt(); int v = sc.nextInt(); graph.get(u).add(v); graph.get(v).add(u); } int startNode = sc.nextInt(); BFS(startNode, graph, path, visited); StringBuilder sb = new StringBuilder(); for (int i = 1; i < n + 1; ++i) { sb.append(getResult(startNode, i, path)); } rt.add(sb.toString()); } for (String s : rt) { System.out.println(s); } } }
package controller; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import socialnetwork.domain.Conversation; import socialnetwork.domain.Message; import socialnetwork.domain.Utilizator; import socialnetwork.repository.exceptions.RepoException; import socialnetwork.service.*; import java.io.IOException; import java.time.LocalDateTime; import java.util.*; public class MessengerController { private Stage primaryStage; private UtilizatorService utilizatorService; private PrietenieService friendshipsService; private MessageService messagesService; private RequestService friendRequestsService; private EventService eventService; Conversation useri; ObservableList<Message> modelGrade = FXCollections.observableArrayList(); ObservableList<Conversation> modelGrade1 = FXCollections.observableArrayList(); Utilizator user; @FXML TableView<Conversation> conversationsTable; @FXML TableColumn<Conversation, String> ColumnConv; @FXML TableView<Message> MessageTable; @FXML TableColumn<Message,String> FromColumn; @FXML TableColumn<Message,String> MessageColumn; @FXML TextField txtReply; @FXML TextField txtMessage; @FXML TextField txtTo; @FXML TableColumn <Message,String> TimeColumn; public void setPrimaryStage(Stage primaryStage){ this.primaryStage = primaryStage; } public void setUser(Utilizator user){ this.user = user; } public void initialize() { ColumnConv.setCellValueFactory(new PropertyValueFactory<Conversation,String>("users_string")); FromColumn.setCellValueFactory(new PropertyValueFactory<Message,String>("nume")); MessageColumn.setCellValueFactory(new PropertyValueFactory<Message,String>("message")); TimeColumn.setCellValueFactory(new PropertyValueFactory<Message, String>("date_format")); conversationsTable.setItems(modelGrade1); MessageTable.setItems(modelGrade); } public void setServices(UtilizatorService utilizatorService, PrietenieService friendshipsService, MessageService messagesService, RequestService friendRequestsService, EventService eventService){ this.utilizatorService= utilizatorService; this.friendshipsService = friendshipsService; this.messagesService = messagesService; this.friendRequestsService = friendRequestsService; this.eventService = eventService; //modelGrade.setAll(getUsersList()); modelGrade1.setAll(getConversations()); } public List<Message> getMessageList(List<Utilizator> useri){ return messagesService.getConversation(useri); } public List<Conversation> getConversations(){ List<List<Utilizator>> conversations = messagesService.getConversations(user.getId()); List<Conversation> conversations1 = new ArrayList<>(); conversations.forEach(x->conversations1.add(new Conversation(x))); return conversations1; } public void handlerSelect(MouseEvent mouseEvent) { Conversation usesi = conversationsTable.getSelectionModel().getSelectedItem(); this.useri = usesi; modelGrade.setAll(getMessageList(usesi.getUsers())); } public void handleButtonReply(ActionEvent actionEvent) { //Message m = MessageTable.getSelectionModel().getSelectedItem(); messagesService.sendMessage(user,useri.getUsers(),txtReply.getText()); //messagesService.replyTo(user,m.getId(),txtReply.getText()); modelGrade.setAll(getMessageList(useri.getUsers())); } public void handleButtonSend(ActionEvent actionEvent) { String aux = txtTo.getText(); String mesaj = txtMessage.getText(); List<Utilizator> utilizators = new ArrayList<>(); String [] aux1 = aux.split(" "); boolean ok = true; for(int i=0;i< aux1.length;i=i+2){ String nume = aux1[i]; String prenume = aux1[i+1]; Optional<Utilizator> userr = utilizatorService.findd(nume, prenume); if(userr.isEmpty()){ ok=false; AlertBox alertBox = new AlertBox("Error!", "Nu exista!"); alertBox.display(); } else{ Utilizator userrr = userr.get(); utilizators.add(userrr); } } if(ok==true) messagesService.sendMessage(user,utilizators,mesaj); utilizators.add(user); modelGrade.setAll(getMessageList(utilizators)); modelGrade1.setAll(getConversations()); } public void handleBack(ActionEvent actionEvent) throws IOException { FXMLLoader loader; loader = new FXMLLoader(); loader.setLocation(getClass().getResource("/view/UserMenu.fxml")); AnchorPane root = loader.load(); Scene userScene = new Scene(root, 700, 500); UserMenuController userMenuController = loader.getController(); userMenuController.setPrimaryStage(primaryStage); userMenuController.setUser(user); userMenuController.setServices(utilizatorService,friendshipsService,messagesService,friendRequestsService, eventService); primaryStage.setTitle("User Menu"); primaryStage.setScene(userScene); primaryStage.show(); } }
package com.metoo.foundation.domain; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.OneToOne; import javax.persistence.Table; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import com.metoo.core.constant.Globals; import com.metoo.core.domain.IdEntity; /** * * <p> * Title: Subject.java * </p> * * <p> * Description: 商城主题类 * </p> * * <p> * Copyright: Copyright (c) 2015 * </p> * * <p> * Company: 沈阳网之商科技有限公司 www.koala.com * </p> * * @author hezeng * * @date 2014-11-11 * * @version koala_b2b2c 2.0 */ @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @Entity @Table(name = Globals.DEFAULT_TABLE_SUFFIX + "subject") public class Subject extends IdEntity { private String title;// 主题名称 @Column(columnDefinition = "int default 0") private int sequence;// 序号 @OneToOne(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) private Accessory banner;// 主题横幅 @Column(columnDefinition = "int default 1") private int display;// 是否显示 @Column(columnDefinition = "LongText") private String subject_detail;// 专题详情,使用json管理[{"type":"goods","goods_ids":",16,14,11,4,5"}, // {"type":"img","img_url":"http://localhost/upload/subject/85c8f939-b099-4821-9f9a-e88dfe3f8ae0.jpg","id":938,"areaInfo":"226_65_366_168=http://www.baidu.com-"}] public Subject() { super(); // TODO Auto-generated constructor stub } public Subject(Long id, Date addTime) { super(id, addTime); // TODO Auto-generated constructor stub } public int getSequence() { return sequence; } public void setSequence(int sequence) { this.sequence = sequence; } public int getDisplay() { return display; } public void setDisplay(int display) { this.display = display; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Accessory getBanner() { return banner; } public void setBanner(Accessory banner) { this.banner = banner; } public String getSubject_detail() { return subject_detail; } public void setSubject_detail(String subject_detail) { this.subject_detail = subject_detail; } }
package com.salesfloors.aws; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import org.codehaus.jackson.JsonParser; import org.codehaus.jackson.map.ObjectMapper; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.PropertiesCredentials; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.CannedAccessControlList; import com.amazonaws.services.s3.model.GetObjectRequest; import com.amazonaws.services.s3.model.PutObjectRequest; import com.amazonaws.services.s3.model.PutObjectResult; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.AmazonSQSAsyncClient; public class AwsClient { public static final String defaultBucketName = "FacePics"; public static final String queueUrl = "https://queue.amazonaws.com/701065011543/PhotoQueue"; private AmazonS3 s3; private AmazonSQS sqs; private ObjectMapper mapper; public AwsClient() throws IOException { PropertiesCredentials props = new PropertiesCredentials(this.getClass().getClassLoader().getResourceAsStream("aws.properties")); s3 = new AmazonS3Client(props); sqs = new AmazonSQSAsyncClient(props); mapper = new ObjectMapper(); mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); } public AmazonS3 getS3() { return s3; } public AmazonSQS getSqs() { return sqs; } public PutObjectResult uploadFileToS3(File file) throws AmazonServiceException, AmazonClientException, FileNotFoundException, InterruptedException { return uploadFileToS3(file, CannedAccessControlList.PublicRead); } public PutObjectResult uploadFileToS3(File file, CannedAccessControlList controlList) { return uploadFileToS3(file, controlList, defaultBucketName); } public PutObjectResult uploadFileToS3(File file, CannedAccessControlList controlList, String bucketName) { PutObjectRequest por = new PutObjectRequest(bucketName, file.getName(), file); por.setCannedAcl(controlList); return s3.putObject(por); } public S3Object readFileFromS3(String fileName) { return readFileFromS3(fileName, defaultBucketName); } public S3Object readFileFromS3(String fileName, String bucketName) { return s3.getObject(new GetObjectRequest(bucketName, fileName)); } public void deleteFileOnS3(String fileName) throws AmazonServiceException, AmazonClientException, FileNotFoundException, InterruptedException { s3.deleteObject(defaultBucketName, fileName); } }
package presentation.customer.view; import businesslogic.hotelbl.Hotel; import businesslogicservice.hotelblservice.HotelBLService; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import vo.CustomerVO; import vo.HotelInfoVO; import java.util.List; /** * Created by 啊 on 2016/12/8. */ public class LivedHotelController { private presentation.customer.MainAPP mainAPP; private CustomerVO customerVO; private HotelBLService hotelBLService; @FXML private TableView<ViewHotel> livedHotelTable; @FXML private TableColumn<ViewHotel,String> hotelNameColumn; @FXML private TableColumn<ViewHotel,String> cityColumn; @FXML private TableColumn<ViewHotel,String> areaColumn; @FXML private TableColumn<ViewHotel,String> addressColumn; @FXML private TableColumn<ViewHotel,String> levelColumn; @FXML private TableColumn<ViewHotel,String> scoreColumn; @FXML private TableColumn<ViewHotel,String> lowestPriceColumn; public void setMainAPP(presentation.customer.MainAPP mainAPP){ this.mainAPP=mainAPP; initialize(); } public void setCustomerVO(CustomerVO customerVO) { this.customerVO=customerVO; } private void initialize(){ hotelNameColumn.setCellValueFactory(cellData->cellData.getValue().hotelNameProperty()); levelColumn.setCellValueFactory(cellData->cellData.getValue().hotelLevelProperty()); scoreColumn.setCellValueFactory(cellData->cellData.getValue().gradesProperty()); lowestPriceColumn.setCellValueFactory(cellData->cellData.getValue().lowestPriceProperty()); addressColumn.setCellValueFactory(cellData->cellData.getValue().addressProperty()); cityColumn.setCellValueFactory(cellData->cellData.getValue().cityProperty()); areaColumn.setCellValueFactory(cellData->cellData.getValue().areaProperty()); hotelBLService=new Hotel(); setLivedHotelTable(); } private void setLivedHotelTable(){ List<HotelInfoVO>hotelInfoVOList=hotelBLService.getHistoryHotelList(customerVO.getUserName()); HotelInfoVO hotelInfoVOs=hotelInfoVOList.get(0); if(hotelInfoVOs==null){ mainAPP.informationAlert("您还未有酒店订单"); } ObservableList<ViewHotel> tempViewList= FXCollections.observableArrayList(); for(HotelInfoVO hotelInfoVO:hotelInfoVOList){ tempViewList.add(new ViewHotel(hotelInfoVO.getCity(),hotelInfoVO.getBusinessCircle(),hotelInfoVO.getHotelName(), String.valueOf(hotelInfoVO.getStarLevel()), String.valueOf(hotelInfoVO.getScore()), String.valueOf(hotelInfoVO.getLowestPrice()),hotelInfoVO.getAddress())); } livedHotelTable.setItems(tempViewList); } @FXML private void setHotelOrderButton(){ ViewHotel hotel=livedHotelTable.getSelectionModel().getSelectedItem(); if(hotel==null){ mainAPP.errorAlert("请先选择"); } else{ mainAPP.showOrderInfoView(customerVO,hotelBLService.getHotelInfo(hotel.getHotelName())); } } @FXML private void orderThis(){ ViewHotel hotel=livedHotelTable.getSelectionModel().getSelectedItem(); HotelBLService hotelBLService=new Hotel(); HotelInfoVO hotelInfoVO=hotelBLService.getHotelInfo(hotel.getHotelName()); mainAPP.showOrderGeneratedView(customerVO,hotelInfoVO,null); } @FXML private void hotelInfo(){ ViewHotel hotel=livedHotelTable.getSelectionModel().getSelectedItem(); HotelBLService hotelBLService=new Hotel(); HotelInfoVO hotelInfoVO=hotelBLService.getHotelInfo(hotel.getHotelName()); mainAPP.showHotelInfoView(customerVO,hotelInfoVO.getHotelName(),null); } }
import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ListIntro1 { public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add("William"); list.add("John"); list.add("Amanda"); System.out.println(list); System.out.println(list.size()); System.out.println(list.get(2)); Iterator listIterator = list.iterator(); while (listIterator.hasNext()){ Object element = listIterator.next(); System.out.println(element); } list.clear(); System.out.println(); } }
/** * */ package com.zh.interview.jvm; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.MemoryUsage; import java.util.List; /** * * @desc * @author Z^H * @email 85754324@qq.com * @date 2018年3月23日 下午11:29:44 * */ public class GetJVMInfo { public static void main(String[] args) { MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); MemoryUsage usage = memoryMXBean.getHeapMemoryUsage(); System.out.println("INT HEAP:" + usage.getInit()/1024/1024 + "Mb"); System.out.println("MAX HEAP:" + usage.getMax()/1024/1024 + "Mb"); System.out.println("USED HEAP:" + usage.getUsed()/1024/1024 + "Mb"); System.out.println("\nFull Information:"); System.out.println("Heap Memory Usage:" + memoryMXBean.getHeapMemoryUsage()); System.out.println("Non-Heap Memory Usage:" + memoryMXBean.getNonHeapMemoryUsage()); List<String> inputArguments = ManagementFactory.getRuntimeMXBean().getInputArguments(); System.out.println("=====================java options=================="); System.out.println(inputArguments); System.out.println("=====================通过java来获取相关系统状态===================="); long i = Runtime.getRuntime().totalMemory()/1024/1024;//Java 虚拟机中的内存总量,以字节为单位 System.out.println("总的内存量为:" + i + "Mb"); long j = Runtime.getRuntime().freeMemory()/1024/1024;//Java 虚拟机中的空闲内存量 System.out.println("空闲内存量:" + j + "Mb"); long k = Runtime.getRuntime().maxMemory()/1024/1024; System.out.println("最大可用内存量:" + k + "Mb"); } }
package com.git.cloud.resmgt.compute.model.po; public class DuPoByRmHost { private String AppDuId; private String AppDuName; public String getAppDuId() { return AppDuId; } public void setAppDuId(String appDuId) { AppDuId = appDuId; } public String getAppDuName() { return AppDuName; } public void setAppDuName(String appDuName) { AppDuName = appDuName; } }
/******************************************************************************* * Copyright (c) 2011 The University of York. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Louis Rose - initial API and implementation ******************************************************************************/ package simulator.persistence; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.Serializable; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import simulator.util.EmfUtil; public class EObjectSerializer implements Serializable { // Generated by Eclipse private static final long serialVersionUID = 5261606297382792696L; public String serialize(EObject object) throws SerializationException { try { final ByteArrayOutputStream destination = new ByteArrayOutputStream(); EmfUtil.serialise(object, destination); return new String(destination.toByteArray(), "UTF-8"); } catch (IOException e) { throw new SerializationException("Error encountered whilst serializing " + object, e); } } public EObject deserialize(EPackage metamodel, String serialised) throws SerializationException { try { final ByteArrayInputStream source = new ByteArrayInputStream(serialised.getBytes("UTF-8")); return EmfUtil.deserialise(metamodel, source); } catch (IOException e) { throw new SerializationException("Error encountered whilst deserializing: " + serialised, e); } } }
package org.kuali.ole.service.impl; import org.kuali.rice.krad.maintenance.MaintenanceDocument; import org.kuali.rice.krad.service.DocumentService; import org.kuali.rice.krad.service.impl.MaintenanceDocumentServiceImpl; import org.kuali.rice.krad.util.KRADConstants; import org.kuali.rice.krad.util.ObjectUtils; import java.io.Serializable; import java.util.Map; /** * Created with IntelliJ IDEA. * User: ? * Date: 10/11/12 * Time: 7:16 PM * To change this template use File | Settings | File Templates. */ public class OlePatronBillMaintenanceDocumentServiceImpl extends MaintenanceDocumentServiceImpl { private DocumentService documentService; /** * Gets the value of documentService which is of type DocumentService * @return documentService(DocumentService) */ protected DocumentService getDocumentService() { return this.documentService; } /** * Sets the value for documentService which is of type DocumentService * @param documentService(DocumentService) */ public void setDocumentService(DocumentService documentService) { this.documentService = documentService; } public void setupMaintenanceObjectForDelete(MaintenanceDocument document, String maintenanceAction, Map<String, String[]> requestParameters) { document.getNewMaintainableObject().setMaintenanceAction(maintenanceAction); document.getOldMaintainableObject().setMaintenanceAction(maintenanceAction); Object oldDataObject = retrieveObjectForMaintenance(document, requestParameters); Object newDataObject = ObjectUtils.deepCopy((Serializable) oldDataObject); document.getOldMaintainableObject().setDataObject(oldDataObject); document.getNewMaintainableObject().setDataObject(newDataObject); } }
package edu.uha.miage.core.repository; import edu.uha.miage.core.entity.Personne; import org.springframework.data.jpa.repository.JpaRepository; public interface PersonneRepository extends JpaRepository<Personne, Long> { Personne findByNom(String nom); Personne findByNomAndPrenomAndEmailAndAdresse(String Nom, String prenom, String email, String adresse); }
package com.zxz.flavordemo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); System.out.println("heheh"); // master 2248 // master 2255 // master 2301 // master 2303 // origin/b1 0823 // b1 0824 // master 0911 } }
package pruebasUnitarias.pruebasPatronesMovimiento; import movimiento.*; import movimiento.patrones.Huir; import org.junit.*; import auxiliares.Vector; public class HuirTest { private PatronMovimiento movimiento; private Posicion posInicial, posIntermedia, posFinal; private Vector velocidad; @Before public void setUp() { movimiento = new Huir(); posInicial = new Posicion(50, 53); posIntermedia = new Posicion(50, 50); posFinal = new Posicion(50, 47); velocidad = new Vector(0, -3); } @Test public void testHuir() { Posicion posRetorno; posRetorno = movimiento.calcularNuevaPosicion(posInicial, velocidad); Assert.assertTrue(posRetorno.equals(posIntermedia)); posRetorno = movimiento.calcularNuevaPosicion(posRetorno, velocidad); Assert.assertTrue(posRetorno.equals(posFinal)); System.out.println("El movimiento de huida funciona bien"); } }
package md2k.mCerebrum.cStress; import md2k.mCerebrum.cStress.Autosense.AUTOSENSE; import md2k.mCerebrum.cStress.Features.AccelerometerFeatures; import md2k.mCerebrum.cStress.Features.ECGFeatures; import md2k.mCerebrum.cStress.Features.RIPFeatures; import md2k.mCerebrum.cStress.Library.DataStream; import md2k.mCerebrum.cStress.Library.DataStreams; import md2k.mCerebrum.cStress.Library.FeatureVector; import md2k.mCerebrum.cStress.Structs.DataPoint; import libsvm.*; import md2k.mCerebrum.cStress.Structs.StressProbability; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import java.util.Date; /** * Copyright (c) 2015, The University of Memphis, MD2K Center * - Timothy Hnat <twhnat@memphis.edu> * - Karen Hovsepian <karoaper@gmail.com> * All rights reserved. * <p/> * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * <p/> * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * <p/> * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * <p/> * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public class cStress { long windowStartTime = -1; long windowSize; private String participant; private DataStreams datastreams = new DataStreams(); public cStress(long windowSize, String svmModelFile, String featureVectorParameterFile, String participant) { this.windowSize = windowSize; this.participant = participant; //Configure Data Streams datastreams.get("org.md2k.cstress.data.ecg").metadata.put("frequency", 64.0); datastreams.get("org.md2k.cstress.data.ecg").metadata.put("channelID", AUTOSENSE.CHEST_ECG); datastreams.get("org.md2k.cstress.data.rip").metadata.put("frequency", 64.0 / 3.0); datastreams.get("org.md2k.cstress.data.rip").metadata.put("channelID", AUTOSENSE.CHEST_RIP); datastreams.get("org.md2k.cstress.data.accelx").metadata.put("frequency", 64.0 / 6.0); datastreams.get("org.md2k.cstress.data.accelx").metadata.put("channelID", AUTOSENSE.CHEST_ACCEL_X); datastreams.get("org.md2k.cstress.data.accely").metadata.put("frequency", 64.0 / 6.0); datastreams.get("org.md2k.cstress.data.accely").metadata.put("channelID", AUTOSENSE.CHEST_ACCEL_X); datastreams.get("org.md2k.cstress.data.accelz").metadata.put("frequency", 64.0 / 6.0); datastreams.get("org.md2k.cstress.data.accelz").metadata.put("channelID", AUTOSENSE.CHEST_ACCEL_X); resetDataStreams(); // try { // Model = svm.svm_load_model(svmModelFile); // } catch (Exception e) { // e.printStackTrace(); // } // this.featureVectorMean = new double[37]; // this.featureVectorStd = new double[37]; // loadFVParameters(featureVectorParameterFile); } // private void loadFVParameters(String featureVectorParameterFile) { // // BufferedReader br = null; // String line = ""; // String csvSplitBy = ","; // int count; // try { // br = new BufferedReader(new FileReader(featureVectorParameterFile)); // count = 0; // while ((line = br.readLine()) != null) { // String[] meanstd = line.split(csvSplitBy); // this.featureVectorMean[count] = Double.parseDouble(meanstd[0]); // this.featureVectorStd[count] = Double.parseDouble(meanstd[1]); // count++; // } // } catch (Exception e) { // e.printStackTrace(); // } finally { // if (br != null) { // try { // br.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // } // private StressProbability evaluteStressModel(AccelerometerFeatures accelFeatures, ECGFeatures ecgFeatures, RIPFeatures ripFeatures, double bias) { // // StressProbability stressResult = new StressProbability(-1, 0.0); // // // featureVector = normalizeFV(featureVector); // // boolean invalid = false; // for(double d: featureVector) { // if (Double.isInfinite(d) || Double.isNaN(d)) { // invalid = true; // } // } // // if (!activityCheck(accelFeatures) && !invalid) { // //SVM evaluation // svm_node[] data = new svm_node[featureVector.length]; // for (int i = 0; i < featureVector.length; i++) { // data[i] = new svm_node(); // data[i].index = i; // data[i].value = featureVector[i]; // } // // stressResult.probability = svm.svm_predict(Model, data); // if (stressResult.probability < bias) { // stressResult.label = AUTOSENSE.NOT_STRESSED; // } else { // stressResult.label = AUTOSENSE.STRESSED; // } // } // // //Basic Features // DataPoint[] af = accelFeatures.rawFeatures(); // DataPoint[] rr_intervals = ecgFeatures.rawFeatures(); // DataPoint[] peaks = ripFeatures.rawPeakFeatures(); // DataPoint[] valleys = ripFeatures.rawValleyFeatures(); // // return stressResult; // } // // private double[] normalizeFV(double[] featureVector) { // double[] result = new double[featureVector.length]; // // for (int i = 0; i < featureVector.length; i++) { // result[i] = (featureVector[i] - this.featureVectorMean[i]) / this.featureVectorStd[i]; // } // return result; // } // // private boolean activityCheck(AccelerometerFeatures accelFeatures) { // return accelFeatures.Activity; // } public StressProbability process() { StressProbability probabilityOfStress = null; //TODO: This should be moved outside of the stress applications to intercept data before arriving here // //This check must happen before any normalization. It operates on the RAW signals. // RipQualityCalculation ripQuality = new RipQualityCalculation(5, 50, 4500, 20, 2, 20, 150); // ECGQualityCalculation ecgQuality = new ECGQualityCalculation(3, 50, 4500, 20, 2, 47); // // if (!ripQuality.computeQuality(rip, 5 * 1000, 0.67) || !ecgQuality.computeQuality(ecg, 5 * 1000, 0.67)) { //Check for 67% of the data to be of Quality within 5 second windows. // return probabilityOfStress; //data quality failure // } // // AccelerometerFeatures af = new AccelerometerFeatures(datastreams, AUTOSENSE.ACTIVITY_THRESHOLD, AUTOSENSE.ACCEL_WINDOW_SIZE); ECGFeatures ef = new ECGFeatures(datastreams); RIPFeatures rf = new RIPFeatures(datastreams); FeatureVector fv = computeStressFeatures(datastreams); if (fv != null) { fv.persist("/Users/hnat/Downloads/processedrawdata/" + participant + "/org.md2k.cstress.fv.csv"); } // probabilityOfStress = evaluteStressModel(accelFeatures, ecgFeatures, ripFeatures, AUTOSENSE.STRESS_PROBABILTY_THRESHOLD); return probabilityOfStress; } private FeatureVector computeStressFeatures(DataStreams datastreams) { try { /* List of features for SVM model ECG - RR interval variance ECG - RR interval quartile deviation ECG - RR interval low frequency energy ECG - RR interval medium frequency energy *ECG - RR interval high frequency energy *ECG - RR interval low-high frequency energy ratio *ECG - RR interval mean ECG - RR interval median *ECG - RR interval 80th percentile ECG - RR interval 20th percentile ECG - RR interval heart-rate */ DescriptiveStatistics RRint = new DescriptiveStatistics(datastreams.get("org.md2k.cstress.data.ecg.rr_value").getNormalizedValues()); double ECG_RR_Interval_Variance = RRint.getVariance(); double ECG_RR_Interval_Quartile_Deviation = (RRint.getPercentile(75) - RRint.getPercentile(25)) / 2.0; DataStream lombLE = datastreams.get("org.md2k.cstress.data.ecg.rr.LombLowFrequencyEnergy"); double ECG_RR_Interval_Low_Frequency_Energy = (lombLE.data.get(0).value-lombLE.stats.getMean()) / lombLE.stats.getStandardDeviation(); DataStream lombME = datastreams.get("org.md2k.cstress.data.ecg.rr.LombMediumFrequencyEnergy"); double ECG_RR_Interval_Medium_Frequency_Energy = (lombME.data.get(0).value-lombME.stats.getMean()) / lombME.stats.getStandardDeviation(); DataStream lombHE = datastreams.get("org.md2k.cstress.data.ecg.rr.LombHighFrequencyEnergy"); double ECG_RR_Interval_High_Frequency_Energy = (lombHE.data.get(0).value-lombHE.stats.getMean()) / lombHE.stats.getStandardDeviation(); DataStream lombLH = datastreams.get("org.md2k.cstress.data.ecg.rr.LowHighFrequencyEnergyRatio"); double ECG_RR_Interval_Low_High_Frequency_Energy_Ratio = (lombLH.data.get(0).value-lombLH.stats.getMean()) / lombLH.stats.getStandardDeviation(); double ECG_RR_Interval_Mean = RRint.getMean(); double ECG_RR_Interval_Median = RRint.getPercentile(50); double ECG_RR_Interval_80thPercentile = RRint.getPercentile(80); double ECG_RR_Interval_20thPercentile = RRint.getPercentile(20); DescriptiveStatistics heartrate = new DescriptiveStatistics(datastreams.get("org.md2k.cstress.data.ecg.rr.heartrate").getNormalizedValues()); double ECG_RR_Interval_Heart_Rate = heartrate.getMean(); /* RIP - Inspiration Duration - quartile deviation RIP - Inspiration Duration - mean RIP - Inspiration Duration - median RIP - Inspiration Duration - 80th percentile */ DescriptiveStatistics InspDuration = new DescriptiveStatistics(datastreams.get("org.md2k.cstress.data.rip.inspduration").getNormalizedValues()); double RIP_Inspiration_Duration_Quartile_Deviation = (InspDuration.getPercentile(75) - InspDuration.getPercentile(25)) / 2.0; double RIP_Inspiration_Duration_Mean = InspDuration.getMean(); double RIP_Inspiration_Duration_Median = InspDuration.getPercentile(50); double RIP_Inspiration_Duration_80thPercentile = InspDuration.getPercentile(80); /* RIP - Expiration Duration - quartile deviation RIP - Expiration Duration - mean RIP - Expiration Duration - median RIP - Expiration Duration - 80th percentile */ DescriptiveStatistics ExprDuration = new DescriptiveStatistics(datastreams.get("org.md2k.cstress.data.rip.exprduration").getNormalizedValues()); double RIP_Expiration_Duration_Quartile_Deviation = (ExprDuration.getPercentile(75) - ExprDuration.getPercentile(25)) / 2.0; double RIP_Expiration_Duration_Mean = ExprDuration.getMean(); double RIP_Expiration_Duration_Median = ExprDuration.getPercentile(50); double RIP_Expiration_Duration_80thPercentile = ExprDuration.getPercentile(80); /* RIP - Respiration Duration - quartile deviation RIP - Respiration Duration - mean RIP - Respiration Duration - median RIP - Respiration Duration - 80th percentile */ DescriptiveStatistics RespDuration = new DescriptiveStatistics(datastreams.get("org.md2k.cstress.data.rip.respduration").getNormalizedValues()); double RIP_Respiration_Duration_Quartile_Deviation = (RespDuration.getPercentile(75) - RespDuration.getPercentile(25)) / 2.0; double RIP_Respiration_Duration_Mean = RespDuration.getMean(); double RIP_Respiration_Duration_Median = RespDuration.getPercentile(50); double RIP_Respiration_Duration_80thPercentile = RespDuration.getPercentile(80); /* RIP - Inspiration-Expiration Duration Ratio - quartile deviation *RIP - Inspiration-Expiration Duration Ratio - mean RIP - Inspiration-Expiration Duration Ratio - median RIP - Inspiration-Expiration Duration Ratio - 80th percentile */ DescriptiveStatistics InspExprDuration = new DescriptiveStatistics(datastreams.get("org.md2k.cstress.data.rip.IERatio").getNormalizedValues()); double RIP_Inspiration_Expiration_Duration_Quartile_Deviation = (InspExprDuration.getPercentile(75) - InspExprDuration.getPercentile(25)) / 2.0; double RIP_Inspiration_Expiration_Duration_Mean = InspExprDuration.getMean(); double RIP_Inspiration_Expiration_Duration_Median = InspExprDuration.getPercentile(50); double RIP_Inspiration_Expiration_Duration_80thPercentile = InspExprDuration.getPercentile(80); /* RIP - Stretch - quartile deviation RIP - Stretch - mean *RIP - Stretch - median RIP - Stretch - 80th percentile */ DescriptiveStatistics Stretch = new DescriptiveStatistics(datastreams.get("org.md2k.cstress.data.rip.stretch").getNormalizedValues()); double RIP_Stretch_Quartile_Deviation = (Stretch.getPercentile(75) - Stretch.getPercentile(25)) / 2.0; double RIP_Stretch_Mean = Stretch.getMean(); double RIP_Stretch_Median = Stretch.getPercentile(50); double RIP_Stretch_80thPercentile = Stretch.getPercentile(80); /* *RIP - Breath-rate */ DataStream breathRate = datastreams.get("org.md2k.cstress.data.rip.BreathRate"); double RIP_Breath_Rate = (breathRate.data.get(0).value - breathRate.stats.getMean()) / breathRate.stats.getStandardDeviation(); /* *RIP - Inspiration Minute Volume */ DataStream minVent = datastreams.get("org.md2k.cstress.data.rip.MinuteVentilation"); double RIP_Inspiration_Minute_Ventilation = (minVent.data.get(0).value - minVent.stats.getMean()) / minVent.stats.getStandardDeviation(); /* RIP+ECG - Respiratory Sinus Arrhythmia (RSA) - quartile deviation RIP+ECG - Respiratory Sinus Arrhythmia (RSA) - mean RIP+ECG - Respiratory Sinus Arrhythmia (RSA) - median RIP+ECG - Respiratory Sinus Arrhythmia (RSA) - 80th percentile */ DescriptiveStatistics RSA = new DescriptiveStatistics(datastreams.get("org.md2k.cstress.data.rip.RSA").getNormalizedValues()); double RSA_Quartile_Deviation = (RSA.getPercentile(75) - RSA.getPercentile(25)) / 2.0; double RSA_Mean = RSA.getMean(); double RSA_Median = RSA.getPercentile(50); double RSA_80thPercentile = RSA.getPercentile(80); double[] featureVector = { ECG_RR_Interval_Variance, // 1 ECG_RR_Interval_Low_High_Frequency_Energy_Ratio, // 2 ECG_RR_Interval_High_Frequency_Energy, // 3 ECG_RR_Interval_Medium_Frequency_Energy, // 4 ECG_RR_Interval_Low_Frequency_Energy, // 5 ECG_RR_Interval_Mean, // 6 ECG_RR_Interval_Median, // 7 ECG_RR_Interval_Quartile_Deviation, // 8 ECG_RR_Interval_80thPercentile, // 9 ECG_RR_Interval_20thPercentile, // 10 ECG_RR_Interval_Heart_Rate, // 11 RIP_Breath_Rate, // 12 RIP_Inspiration_Minute_Ventilation, // 13 RIP_Inspiration_Duration_Quartile_Deviation, // 14 RIP_Inspiration_Duration_Mean, // 15 RIP_Inspiration_Duration_Median, // 16 RIP_Inspiration_Duration_80thPercentile, // 17 RIP_Expiration_Duration_Quartile_Deviation, // 18 RIP_Expiration_Duration_Mean, // 19 RIP_Expiration_Duration_Median, // 20 RIP_Expiration_Duration_80thPercentile, // 21 RIP_Respiration_Duration_Quartile_Deviation, // 22 RIP_Respiration_Duration_Mean, // 23 RIP_Respiration_Duration_Median, // 24 RIP_Respiration_Duration_80thPercentile, // 25 RIP_Inspiration_Expiration_Duration_Quartile_Deviation, // 26 RIP_Inspiration_Expiration_Duration_Mean, // 27 RIP_Inspiration_Expiration_Duration_Median, // 28 RIP_Inspiration_Expiration_Duration_80thPercentile, // 29 RIP_Stretch_Quartile_Deviation, // 30 RIP_Stretch_Mean, // 31 RIP_Stretch_Median, // 32 RIP_Stretch_80thPercentile, // 33 RSA_Quartile_Deviation, // 34 RSA_Mean, // 35 RSA_Median, // 36 RSA_80thPercentile // 37 }; FeatureVector fv = new FeatureVector(windowStartTime, featureVector); return fv; } catch (IndexOutOfBoundsException e) { e.printStackTrace(); } return null; } public StressProbability add(int channel, DataPoint dp) { StressProbability result = null; if (this.windowStartTime < 0) this.windowStartTime = nextEpochTimestamp(dp.timestamp); if ((dp.timestamp - windowStartTime) >= this.windowSize) { //Process the buffer every windowSize milliseconds result = process(); resetDataStreams(); this.windowStartTime += AUTOSENSE.SAMPLE_LENGTH_SECS * 1000; //Add 60 seconds to the timestamp } if (dp.timestamp >= this.windowStartTime) { switch (channel) { case AUTOSENSE.CHEST_ECG: datastreams.get("org.md2k.cstress.data.ecg").add(dp); break; case AUTOSENSE.CHEST_RIP: datastreams.get("org.md2k.cstress.data.rip").add(dp); break; case AUTOSENSE.CHEST_ACCEL_X: datastreams.get("org.md2k.cstress.data.accelx").add(dp); break; case AUTOSENSE.CHEST_ACCEL_Y: datastreams.get("org.md2k.cstress.data.accely").add(dp); break; case AUTOSENSE.CHEST_ACCEL_Z: datastreams.get("org.md2k.cstress.data.accelz").add(dp); break; default: System.out.println("NOT INTERESTED: " + dp); break; } } return result; } private long nextEpochTimestamp(long timestamp) { long previousMinute = timestamp / (60 * 1000); Date date = new Date((previousMinute + 1) * (60 * 1000)); return date.getTime(); } private void resetDataStreams() { datastreams.persist("/Users/hnat/Downloads/processedrawdata/" + participant + "/"); datastreams.reset(); } }
package com.iteima; /* 1、创建多线程的第一种方式 1)、创建Thread的子类,并重写run方法。 2)、创建Thread子类对象,并用该对象调用start方法 *Thread类构造器 1)、Thread(); 2)、Thread(String name);指定新线程的名字 3)、Thread(Runnable target);实现runnable接口中的run方法 4)、Thread(Runnable target,String name) 2、创建多线程的第二种方式-实现runnable接口 1)、定义子类实现Runnable接口 2)、重写Runnable接口中的run方法 3)、通过Thread含参构造器创造线程对象 4)、将Runnable接口中的子类对象作为实际参数传递给Thread类的构造器中。 5)、调用Thread的start方法,开启线程 3、Thread类的相关方法: start、run、String getName()、setName()、static Thread currentThread() static void yeild(释放当前线程的执行权)、join(在线程a中使用b线程调用join方法, 那么在b线程结束之前,a线程都不会被执行) static void sleep(long millis) boolean isAlive(); 注意:1)、每多创建一个线程,就要重新创建一个Thread子类对象.单个对象多次 调用start方法会抛出异常。 2)、不能直接调用run方法。 多线程应用场景: 1)、程序同时执行多个任务 2)、程序要实现一些等待的任务。如读写、输入、网络操作 3)、后台运行程序 */ public class MyThread { public static void main(String[] args) { Thread myThread1 = new MyThread1(); Thread myThread2 = new Thread(new MyThread2()); myThread1.start(); myThread2.start(); for (int i = 0; i < 100; i++) { if (i % 2 == 0) { System.out.println(i + "main"); } } } } class MyThread1 extends Thread { @Override public void run() { for (int i = 0; i < 100; i++) { if (i % 2 == 0) { System.out.println(Thread.currentThread().getName() + "Thread:" + i); } } } } class MyThread2 implements Runnable { @Override public void run() { for (int i = 0; i < 100; i++) { //mainrunnable:8 if (i % 2 == 0){ System.out.println(Thread.currentThread().getName() + "runnable:" + i); } //Thread.currentThread().getName()的输出对象是main。 } } }
package application; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class TaskListServer { private ServerSocket welcomesocket; private TaskList tasklist; public TaskListServer(TaskList tasklist,int port) { this.tasklist=tasklist; try { this.welcomesocket= new ServerSocket(port); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void execute() { try { for (int i = 0;i<5;i--) { Socket Socket= new Socket(); welcomesocket.accept(); welcomesocket.wait(); TaskListCommunicationThreadHandler obj = new TaskListCommunicationThreadHandler(Socket,tasklist); Thread serverAccessThread = new Thread(obj); serverAccessThread.start(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package id.muhamadridwan.oauth2.jwt.model.entity; import lombok.Data; import org.springframework.security.core.GrantedAuthority; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; @Entity @Data public class Role extends BaseID implements GrantedAuthority { private static final long serialVersionUID = 1L; @NotNull @Size(min = 6, max = 60) private String authority; }
package com.networks.ghosttears.gameplay_package; /** * Created by user on 2/8/2017. */ public class VacantGameroom { private String name; private String timeStamp; public VacantGameroom(){ } public VacantGameroom(String name, String timeStamp){ this.name = name; this.timeStamp = timeStamp; } public String getName(){ return name; } }
package model; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.stream.Collectors; import application.Main; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.concurrent.Task; import javafx.scene.Node; import javafx.scene.chart.BarChart; import javafx.scene.chart.CategoryAxis; import javafx.scene.chart.LineChart; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.scene.chart.XYChart.Data; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ProgressBar; import javafx.scene.control.Tooltip; import javafx.scene.layout.BorderPane; import javafx.scene.shape.Path; public class ChartMaker { private TextReader textReader; private HashMap<String, XYChart.Series<Number, Number>> allSeries; private LinkedHashMap<String, HashMap<Integer, Integer>> totalOccurrenceMaps; public ChartMaker(TextReader textReader) { this.textReader = textReader; allSeries = new HashMap<String, XYChart.Series<Number, Number>>(); } public void createLineChart(String typeOfChart, ArrayList<String> translators, boolean removeStopWords, BorderPane borderPane, ProgressBar progressBar, Button saveButton) { final NumberAxis xAxis = new NumberAxis(); xAxis.setLabel("Tokens"); final NumberAxis yAxis = new NumberAxis(); if (typeOfChart.equals("Type vs Token")) { yAxis.setLabel("Types"); } else if (typeOfChart.equals("Type-Token Ratio")) { yAxis.setLabel("Ratio"); xAxis.setForceZeroInRange(false); } final LineChart<Number, Number> lineChart = new LineChart<Number, Number>(xAxis, yAxis); String title = new String(); if (removeStopWords) { title = typeOfChart + " Without Stopwords"; } else { title = typeOfChart; } lineChart.setTitle(title); lineChart.setCreateSymbols(false); final Task<Void> task = new Task<Void>() { @Override protected Void call() throws Exception { int totalNumberOfWords = 0; int wordCounter = 0; LinkedHashMap<String, String> translatorsTextMap = new LinkedHashMap<String,String>(); // String dataFilePath = new String(); String savedSeriesName = new String(); int progressCounter = 1; // //calculates total number of words for progress bar for (String translator : translators) { if (removeStopWords) { // dataFilePath = "data/charts/" + typeOfChart + "/" + translator + " without stopwords.bin"; savedSeriesName = translator + " " + typeOfChart + " without stopwords"; } else { // dataFilePath = "data/charts/" + typeOfChart + "/" + translator + ".bin"; savedSeriesName = translator + " " + typeOfChart; } ///////////////////////////////if series already saved locally//////////////////////// // if (allSeries.containsKey(savedSeriesName)) { // // System.out.println(savedSeriesName + " saved locally"); // // lineChart.getData().add(allSeries.get(savedSeriesName)); // // } else { System.out.println(savedSeriesName + " not saved locally"); // File dataFile = new File(dataFilePath); ///////////////////try to read from data file////////////////////////////////////// // if (dataFile.exists()) { // // ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(dataFilePath)); // // // ObservableList<XYChart.Data<Number, Number>> observableList = FXCollections.observableArrayList((ArrayList<XYChart.Data<Number, Number>>) objectInputStream.readObject()); // // XYChart.Series<Number, Number> series = new XYChart.Series<Number, Number>(); // series.setName(translator); // // series.setData(observableList); // // HashMap<Number, Number> dataHashMap = (HashMap<Number, Number>) objectInputStream.readObject(); // // for (Map.Entry<Number, Number> entry : dataHashMap.entrySet()) { // // series.getData().add(new XYChart.Data<Number, Number>(entry.getKey(), entry.getValue())); // // System.out.println("reading ("+ entry.getKey() + "," + entry.getValue() + ") for " + translator); // } // // // // if (removeStopWords) { // allSeries.put(translator + " " + typeOfChart + " without stopwords", series); // } else { // allSeries.put(translator + " " + typeOfChart, series); // } // lineChart.getData().add(series); // // try { // objectInputStream.close(); // } catch (IOException e) { // e.printStackTrace(); // } // // updateProgress(progressCounter, translators.size()); // ++progressCounter; // // } else { System.out.println("SERIES NOT FOUND IN DATA"); String translatorsWholeText = textReader.getWholeFilteredText(translator, removeStopWords); translatorsTextMap.put(translator, translatorsWholeText); totalNumberOfWords += translatorsWholeText.split(" ").length; // } } // } ////////////////////////for each translator not found in data//////////////// for (Map.Entry<String, String> entry : translatorsTextMap.entrySet()) { String translator = entry.getKey(); String wholeTextOnlyWords = entry.getValue(); XYChart.Series<Number, Number> series = new XYChart.Series<Number, Number>(); series.setName(translator); String[] words = wholeTextOnlyWords.split(" "); ArrayList<String> tokens = new ArrayList<String>(); for (int j = 0; j < words.length; ++j) { String word = words[j]; if (tokens.stream().noneMatch(token -> token.equalsIgnoreCase(word))) { tokens.add(word); } if (typeOfChart.equals("Type vs Token")) { series.getData().add(new XYChart.Data<Number, Number>(j+1, tokens.size())); } else if (typeOfChart.equals("Type-Token Ratio")) { series.getData().add(new XYChart.Data<Number, Number>(j+1, (double)tokens.size()/(j+1))); } ++wordCounter; System.out.println(wordCounter + "/" + totalNumberOfWords); // updateProgress(wordCounter, totalNumberOfWords); } // System.out.println("ATTEMPTING TO WRITE TO FILE"); //////////////////////////////writing series from data file///////////////////////////// // if (removeStopWords) { // dataFilePath = "data/charts/" + typeOfChart + "/" + translator + " without stopwords.bin"; // } else { // dataFilePath = "data/charts/" + typeOfChart + "/"+ translator + ".bin"; // } // // System.out.println("0"); // // File dataFile = new File(dataFilePath); // dataFile.createNewFile(); // // System.out.println("1"); // // ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(dataFile)); // // System.out.println("2"); // //// ArrayList<XYChart.Data<Number, Number>> dataArrayList = (ArrayList<Data<Number, Number>>) series.getData().stream().collect(Collectors.toList()); // // HashMap<Number, Number> dataHashMap = new HashMap<Number, Number>(); // // for (XYChart.Data<Number, Number> data : series.getData()) { // // dataHashMap.put(data.getXValue(), data.getYValue()); // // System.out.println("writing for " + translator); // } // // // try { //// objectOutputStream.writeObject(series); // objectOutputStream.writeObject(dataHashMap); // } catch (Exception e) { // System.out.println(e.getMessage()); // } // // System.out.println("DATA WRITTEN IN FILE"); // // try { // objectOutputStream.close(); // } catch (IOException e) { // e.printStackTrace(); // } // /////////////////////////////////////////////////////////////////////////////////////////// if (removeStopWords) { allSeries.put(translator + " " + typeOfChart + " without stopwords", series); } else { allSeries.put(translator + " " + typeOfChart, series); } lineChart.getData().add(series); updateProgress(progressCounter, translators.size()); ++progressCounter; } ////////////////////////////////////////////////////////////////////////////////// Platform.runLater(new Runnable() { @Override public void run() { borderPane.setCenter(lineChart); boldenLineChartSeriesOnHover(lineChart, allSeries); boldenLineChartSeriesOnLegendHover(lineChart); saveButton.setDisable(false); System.out.println("allSeries.size() ============> " + allSeries.size()); } }); return null; } }; progressBar.progressProperty().bind(task.progressProperty()); final Thread thread = new Thread(task); thread.start(); } private void boldenLineChartSeriesOnHover(LineChart lineChart, HashMap<String, XYChart.Series<Number, Number>> allSeries) { for (Map.Entry<String, XYChart.Series<Number, Number>> entry : allSeries.entrySet()) { XYChart.Series<Number, Number> series = entry.getValue(); if (lineChart.getData().contains(series)) { Node seriesNode = series.getNode(); //seriesNode will be null if this method is called before the scene CSS has been applied if (seriesNode != null && seriesNode instanceof Path) { Path seriesPath = (Path) seriesNode; double initialStrokeWidth = seriesPath.getStrokeWidth(); seriesPath.setOnMouseEntered(event -> { seriesPath.setStrokeWidth(initialStrokeWidth * 10); seriesPath.toFront(); }); seriesPath.setOnMouseExited(event -> { seriesPath.setStrokeWidth(initialStrokeWidth * 3); }); //tooltip Set<Node> legendItems = lineChart.lookupAll("Label.chart-legend-item"); for (Node legendItem : legendItems) { Label legend = (Label) legendItem; if (series.getName().equals(legend.getText())) { Tooltip.install(seriesNode, new Tooltip(legend.getText())); } } } } } } private void boldenLineChartSeriesOnLegendHover(LineChart lineChart) { Set<Node> legendItems = lineChart.lookupAll("Label.chart-legend-item"); List<XYChart.Series> seriesList = lineChart.getData(); if (legendItems.isEmpty()) { return; } for (Node legendItem : legendItems) { Label legend = (Label) legendItem; XYChart.Series matchingSeries = new XYChart.Series<>(); for (XYChart.Series series : seriesList){ if (series.getName().equals(legend.getText())) { matchingSeries = series; } } Node seriesNode = matchingSeries.getNode(); if (seriesNode != null && seriesNode instanceof Path) { Path seriesPath = (Path) seriesNode; double initialStrokeWidth = seriesPath.getStrokeWidth(); legendItem.setOnMouseEntered(event -> { seriesPath.setStrokeWidth(initialStrokeWidth * 10); seriesPath.toFront(); }); legendItem.setOnMouseExited(event -> { seriesPath.setStrokeWidth(initialStrokeWidth * 3); }); } } } public void createLexicalFrequencyChart(String typeOfChart, ArrayList<String> translators, boolean normaliseFrequency, boolean removeStopWords, BorderPane borderPane, ProgressBar progressBar, Button saveButton) { final Task<Void> task = new Task<Void>() { @SuppressWarnings("unchecked") @Override protected Void call() throws Exception { HashMap<String, String> translatorsTextMap = new HashMap<String,String>(); for (int i = 0; i < translators.size(); ++i) { String translator = translators.get(i); String wholeFilteredText = textReader.getWholeFilteredText(translator, removeStopWords); translatorsTextMap.put(translator, wholeFilteredText); updateProgress(i+1, translators.size()); } if (!typeOfChart.equals("Frequency Distribution of Word Occurrence")) { final CategoryAxis xAxis = new CategoryAxis(); final NumberAxis yAxis = new NumberAxis(); BarChart<String,Number> barChart = new BarChart<String,Number>(xAxis,yAxis); String title = new String(); if (removeStopWords) { title = typeOfChart + " Without Stopwords"; } else { title = typeOfChart; } barChart.setTitle(title); xAxis.setLabel("Translator"); XYChart.Series<String, Number> ALFSeries = new XYChart.Series<String, Number>(); ALFSeries.setName("Average Lexical Frequency"); XYChart.Series<String, Number> variationRatioSeries = new XYChart.Series<String, Number>(); variationRatioSeries.setName("Coefficient of Variation"); XYChart.Series<String, Number> leftVariationRatioSeries = new XYChart.Series<String, Number>(); leftVariationRatioSeries.setName("Left Coefficient of Variation"); XYChart.Series<String, Number> rightVariationRatioSeries = new XYChart.Series<String, Number>(); rightVariationRatioSeries.setName("Right Coefficient of Variation"); for (int i = 0; i < translators.size(); ++i) { String translator = translators.get(i); HashMap<String, Integer> repetitionMap = new HashMap<String, Integer>(); for (String word : translatorsTextMap.get(translator).split(" ")) { if (repetitionMap.containsKey(word)) { repetitionMap.put(word, repetitionMap.get(word) + 1); } else { repetitionMap.put(word, 1); } } if (typeOfChart.equals("Frequency of Repeated Words")) { ////////removing 1////// repetitionMap.entrySet().removeIf(pair -> pair.getValue() == 1); ////////////////////////////////////////////////////// } int numberOfWords = repetitionMap.size(); int sumOfRepetitions = 0; for (Map.Entry<String, Integer> pair : repetitionMap.entrySet()) { sumOfRepetitions += pair.getValue(); } double ALF = (double)sumOfRepetitions/numberOfWords; ALFSeries.getData().add(new XYChart.Data<String, Number>(translator, ALF)); double sumOfError = 0; int leftNCounter = 0; int rightNCounter = 0; double leftSumOfError = 0; double rightSumOfError = 0; for (Map.Entry<String, Integer> pair : repetitionMap.entrySet()) { int frequency = pair.getValue(); sumOfError += Math.pow((frequency - ALF), 2); if (frequency <= ALF) { ++leftNCounter; leftSumOfError += Math.pow((frequency - ALF), 2); } else { ++rightNCounter; rightSumOfError += Math.pow((frequency - ALF), 2); } } double sigma = Math.sqrt(sumOfError/repetitionMap.size()); variationRatioSeries.getData().add(new XYChart.Data<String, Number>(translator, sigma/ALF)); double leftSigma = Math.sqrt(leftSumOfError/leftNCounter); leftVariationRatioSeries.getData().add(new XYChart.Data<String, Number>(translator, leftSigma/ALF)); double rightSigma = Math.sqrt(rightSumOfError/rightNCounter); rightVariationRatioSeries.getData().add(new XYChart.Data<String, Number>(translator, rightSigma/ALF)); } barChart.getData().addAll(ALFSeries, variationRatioSeries, leftVariationRatioSeries, rightVariationRatioSeries); Platform.runLater(new Runnable(){ @Override public void run() { borderPane.setCenter(barChart); saveButton.setDisable(false); } }); } else { ////////////////////////Frequency Distribution of Word Occurrence/////////////////////////// final NumberAxis xAxis = new NumberAxis(1, 15, 1); final NumberAxis yAxis = new NumberAxis(); LineChart<Number,Number> lineChart = new LineChart<Number,Number>(xAxis,yAxis); String title = new String(); if (removeStopWords) { title = typeOfChart + " Without Stopwords"; } else { title = typeOfChart; } lineChart.setTitle(title); xAxis.setLabel("Word Occurrence"); if (normaliseFrequency) { yAxis.setLabel("Frequency (%)"); } else { yAxis.setLabel("Frequency"); } allSeries = new HashMap<String, XYChart.Series<Number, Number>>(); // FileWriter fileWriter = new FileWriter("txt/maxWordDump.txt"); totalOccurrenceMaps = new LinkedHashMap<String, HashMap<Integer, Integer>>(); for (int i = 0; i < translators.size(); ++i) { String translator = translators.get(i); HashMap<String, Integer> repetitionMap = new HashMap<String, Integer>(); // fileWriter.write(translator + System.lineSeparator()); for (String word : translatorsTextMap.get(translator).split(" ")) { if (repetitionMap.containsKey(word)) { repetitionMap.put(word, repetitionMap.get(word) + 1); } else { repetitionMap.put(word, 1); } } HashMap<Integer, Integer> occurrenceMap = new HashMap<Integer, Integer>(); HashMap<Integer, Integer> totalOccurrenceMap = new HashMap<Integer, Integer>(); // String maxWord = new String(); int maxOcc = 0; for (Map.Entry<String,Integer> entry : repetitionMap.entrySet()) { int occurrence = entry.getValue(); if (occurrence > maxOcc) { // maxWord = entry.getKey(); maxOcc = occurrence; } if (occurrence <= 15 && occurrenceMap.containsKey(occurrence)) { occurrenceMap.put(occurrence, occurrenceMap.get(occurrence) + 1); } else if (occurrence <= 15) { occurrenceMap.put(occurrence, 1); } if (totalOccurrenceMap.containsKey(occurrence)) { totalOccurrenceMap.put(occurrence, totalOccurrenceMap.get(occurrence) + 1); } else { totalOccurrenceMap.put(occurrence, 1); } } totalOccurrenceMaps.put(translator, totalOccurrenceMap); XYChart.Series<Number, Number> series = new XYChart.Series<Number, Number>(); series.setName(translator); if (normaliseFrequency) { for (Map.Entry<Integer, Integer> entry : occurrenceMap.entrySet()) { series.getData().add(new XYChart.Data<Number, Number>(entry.getKey(), (double)entry.getValue()/translatorsTextMap.get(translator).split(" ").length*100)); } } else { for (Map.Entry<Integer, Integer> entry : occurrenceMap.entrySet()) { series.getData().add(new XYChart.Data<Number, Number>(entry.getKey(), entry.getValue())); } } if (removeStopWords) { allSeries.put(translator + " " + typeOfChart + " without stopwords", series); } else { allSeries.put(translator + " " + typeOfChart, series); } lineChart.getData().add(series); } Platform.runLater(new Runnable(){ @Override public void run() { boldenLineChartSeriesOnHover(lineChart, allSeries); boldenLineChartSeriesOnLegendHover(lineChart); borderPane.setCenter(lineChart); saveButton.setDisable(false); } }); } return null; } }; progressBar.progressProperty().bind(task.progressProperty()); final Thread thread = new Thread(task); thread.start(); } public HashMap<String, HashMap<Integer, Integer>> getTotalOccurrenceMaps() { return totalOccurrenceMaps; } }
package edu.mit.cci.simulation.model; import edu.mit.cci.simulation.jaxb.JaxbReference; import edu.mit.cci.simulation.util.SimulationValidationException; import edu.mit.cci.simulation.util.U; import edu.mit.cci.simulation.util.Validation; import org.apache.log4j.Logger; import org.aspectj.weaver.ast.Var; import org.springframework.roo.addon.entity.RooEntity; import org.springframework.roo.addon.javabean.RooJavaBean; import org.springframework.roo.addon.tostring.RooToString; import javax.persistence.Column; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.validation.constraints.NotNull; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.util.HashMap; import java.util.Map; @RooJavaBean @RooToString @RooEntity @XmlRootElement(name = "Tuple") @XmlAccessorType(XmlAccessType.NONE) public class Tuple { private static Logger log = Logger.getLogger(Tuple.class); public Tuple(Variable v) { setVar(v); } @NotNull @ManyToOne(targetEntity = DefaultVariable.class, fetch = FetchType.EAGER) @XmlJavaTypeAdapter(JaxbReference.Adapter.class) private Variable var; @Column(columnDefinition = "LONGTEXT") @XmlElement(name = "Value") private String value_; private transient String[] values; private transient final Map<Integer, TupleStatus> statuses = new HashMap<Integer, TupleStatus>(); public Tuple() { } public String[] getValues() { if (values == null) { if (value_ == null) return null; else { this.statuses.clear(); values = U.unescape(value_, this.statuses, var.getDataType() == DataType.NUM ? var.getPrecision_() : null); } } return values; } public void setValues(String[] values) throws SimulationValidationException { this.statuses.clear(); _setValues(values); } private void _setValues(String[] values) throws SimulationValidationException { Validation.isComplete(var); Validation.atMostArity(var, values.length); for (int i = 0; i < values.length; i++) { Validation.checkDataType(var, values[i], true); if (values[i] == null) continue; TupleStatus status = statuses.get(i); if (status != null) continue; U.process(var, i, values, statuses); } this.values = values; this.value_ = (U.escape(values, statuses)); } public void setValue_(String val) throws SimulationValidationException { this.statuses.clear(); _setValues(U.unescape(val, this.statuses, null)); } public TupleStatus getStatus(int i) { return statuses.get(i); } public void setStatus(int i, TupleStatus status) { TupleStatus current = getStatus(i); if (current != status) { statuses.put(i, status); value_ = U.updateEscapedArray(i, value_, status); values[i] = null; } } public static void main(String[] args) { String[] vals = new String[]{"hi;;", "ad%%253Bd;;", "nothing;;;"}; String encoded = U.escape(vals, null); System.err.println(encoded); vals = U.unescape(encoded, null, null); for (String val : vals) { System.err.println(val); } } public String getId_() { return "" + getId(); } public static Tuple copy(Tuple t) { Tuple result = new Tuple(); result.setVar(t.getVar()); try { result.setValue_(t.getValue_()); } catch (SimulationValidationException e) { throw new RuntimeException("Encountered an invalid tuple on copy", e); } result.persist(); return result; } @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private Long id; @XmlAttribute public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } }
package com.myou.appback.modules.util; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * Description: 控制spring的bean<br> * @version 1.0 */ public class SpringContext implements ApplicationContextAware { /** * context */ @Autowired private static ApplicationContext context; public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { context = applicationContext; } /** * 获取bean * @param name * @return */ public static Object getBean(String name) { return context.getBean(name); } /** * 是否包含bean * @param name * @return */ public static Boolean containsBean(String name){ return context.containsBean(name); } public static ApplicationContext getContext() { return context; } public static void setContext(ApplicationContext context) { SpringContext.context = context; } }
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.testfixture.servlet; import jakarta.servlet.http.HttpServletMapping; import jakarta.servlet.http.MappingMatch; import org.springframework.lang.Nullable; /** * Mock implementation of {@link HttpServletMapping}. * * @author Rossen Stoyanchev * @since 5.3.4 */ public class MockHttpServletMapping implements HttpServletMapping { private final String matchValue; private final String pattern; private final String servletName; @Nullable private final MappingMatch mappingMatch; public MockHttpServletMapping( String matchValue, String pattern, String servletName, @Nullable MappingMatch match) { this.matchValue = matchValue; this.pattern = pattern; this.servletName = servletName; this.mappingMatch = match; } @Override public String getMatchValue() { return this.matchValue; } @Override public String getPattern() { return this.pattern; } @Override public String getServletName() { return this.servletName; } @Override @Nullable public MappingMatch getMappingMatch() { return this.mappingMatch; } @Override public String toString() { return "MockHttpServletMapping [matchValue=\"" + this.matchValue + "\", " + "pattern=\"" + this.pattern + "\", servletName=\"" + this.servletName + "\", " + "mappingMatch=" + this.mappingMatch + "]"; } }
/* * Copyright (c) 2013-2014, Neuro4j.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.neuro4j.studio.core.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.neuro4j.studio.core.ActionNode; import org.neuro4j.studio.core.FollowByRelationNode; import org.neuro4j.studio.core.Network; import org.neuro4j.studio.core.Neuro4jPackage; import org.neuro4j.studio.core.NodeType; import org.neuro4j.studio.core.OperatorInput; import org.neuro4j.studio.core.format.f4j.NodeXML; import org.neuro4j.studio.core.util.UUIDMgr; import org.neuro4j.workflow.common.SWFParametersConstants; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Follow By Relation Node</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link org.neuro4j.studio.core.impl.FollowByRelationNodeImpl#getRelationName <em>Relation Name</em>}</li> * <li>{@link org.neuro4j.studio.core.impl.FollowByRelationNodeImpl#getMainInput <em>Main Input</em>}</li> * </ul> * </p> * * @generated */ public class FollowByRelationNodeImpl extends ActionNodeImpl implements FollowByRelationNode { protected static final String NAME_EDEFAULT = "Switch"; /** * The default value of the '{@link #getRelationName() <em>Relation Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getRelationName() * @generated * @ordered */ protected static final String RELATION_NAME_EDEFAULT = null; protected static final String FORK_DEFAULT = ""; /** * The cached value of the '{@link #getRelationName() <em>Relation Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getRelationName() * @generated * @ordered */ protected String relationName = RELATION_NAME_EDEFAULT; protected String fork = FORK_DEFAULT; /** * The cached value of the '{@link #getMainInput() <em>Main Input</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getMainInput() * @generated * @ordered */ protected OperatorInput mainInput; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ protected FollowByRelationNodeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override protected EClass eStaticClass() { return Neuro4jPackage.Literals.FOLLOW_BY_RELATION_NODE; } /** * 3<!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public String getRelationName() { return relationName; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public void setRelationName(String newRelationName) { String oldRelationName = relationName; relationName = newRelationName; setName(getDefaultName() + " : " + relationName); if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Neuro4jPackage.FOLLOW_BY_RELATION_NODE__RELATION_NAME, oldRelationName, relationName)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public OperatorInput getMainInput() { if (mainInput != null && mainInput.eIsProxy()) { InternalEObject oldMainInput = (InternalEObject) mainInput; mainInput = (OperatorInput) eResolveProxy(oldMainInput); if (mainInput != oldMainInput) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, Neuro4jPackage.FOLLOW_BY_RELATION_NODE__MAIN_INPUT, oldMainInput, mainInput)); } } return mainInput; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public OperatorInput basicGetMainInput() { return mainInput; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public void setMainInput(OperatorInput newMainInput) { OperatorInput oldMainInput = mainInput; mainInput = newMainInput; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Neuro4jPackage.FOLLOW_BY_RELATION_NODE__MAIN_INPUT, oldMainInput, mainInput)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Neuro4jPackage.FOLLOW_BY_RELATION_NODE__RELATION_NAME: return getRelationName(); case Neuro4jPackage.FOLLOW_BY_RELATION_NODE_FEATURE_FORK: return getFork(); case Neuro4jPackage.FOLLOW_BY_RELATION_NODE__MAIN_INPUT: if (resolve) return getMainInput(); return basicGetMainInput(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Neuro4jPackage.FOLLOW_BY_RELATION_NODE__RELATION_NAME: setRelationName((String) newValue); return; case Neuro4jPackage.FOLLOW_BY_RELATION_NODE__MAIN_INPUT: setMainInput((OperatorInput) newValue); return; case Neuro4jPackage.FOLLOW_BY_RELATION_NODE_FEATURE_FORK: setFork((String) newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Neuro4jPackage.FOLLOW_BY_RELATION_NODE__RELATION_NAME: setRelationName(RELATION_NAME_EDEFAULT); return; case Neuro4jPackage.FOLLOW_BY_RELATION_NODE__MAIN_INPUT: setMainInput((OperatorInput) null); return; case Neuro4jPackage.FOLLOW_BY_RELATION_NODE_FEATURE_FORK: setFork(FORK_DEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Neuro4jPackage.FOLLOW_BY_RELATION_NODE__RELATION_NAME: return RELATION_NAME_EDEFAULT == null ? relationName != null : !RELATION_NAME_EDEFAULT.equals(relationName); case Neuro4jPackage.FOLLOW_BY_RELATION_NODE_FEATURE_FORK: return FORK_DEFAULT == null ? fork != null : !FORK_DEFAULT.equals(fork); case Neuro4jPackage.FOLLOW_BY_RELATION_NODE__MAIN_INPUT: return mainInput != null; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (relationName: "); result.append(relationName); result.append(')'); return result.toString(); } @Override public String getDefaultName() { return NAME_EDEFAULT; } @Override public void setNodeSpecificProperties(NodeXML entity) { setNotNullConfig(entity, SWF_PARAM_DEFAULT, getRelationName()); setNotNullConfig(entity, FORK, getFork()); } @Override public void getNodeSpecificProperties(NodeXML entity) { setRelationName(entity.getConfig(SWF_PARAM_DEFAULT)); setFork(entity.getConfig(FORK)); } public static final String SWF_PARAM_DEFAULT = SWFParametersConstants.SWITCH_NODE_ACTION_NAME; public static final String FORK = "FORK"; @Override public String getLogicImplementationClassName() { return IMPL_CLASS; } public static final String IMPL_CLASS = "org.neuro4j.workflow.node.SwitchNode"; @Override public String getDefaultName(int count) { return getDefaultName(); } @Override public ActionNode createPasteClone(Network net) { FollowByRelationNodeImpl node = new FollowByRelationNodeImpl(); node.setId(UUIDMgr.getInstance().createUUIDString()); node.setName(this.getName()); node.setRelationName(this.getRelationName()); node.setX(this.getX() + 100); node.setY(this.getY() + 100); return node; } @Override public NodeType getNodeType() { return NodeType.SWITCH; } @Override public String getFork() { return fork; } @Override public void setFork(String newValue) { String oldValue = fork; fork = newValue; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Neuro4jPackage.FOLLOW_BY_RELATION_NODE_FEATURE_FORK, oldValue, fork)); } } // FollowByRelationNodeImpl
public class tutorial4 { public static void main(String[] args) { double i = 3; double pi = 4; while(i <= 1000) { pi = pi - (4/i) + (4/(i+2)); i += 4; } System.out.println("This is my calculated value of PI: " + pi); } }
package com.share.dao; import com.share.template.HibernateTemplate; public class StudentHeaderDao extends HibernateTemplate { }
package com.runingsong.qiubai.adapters; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.runingsong.qiubai.fragments.BlankFragment; import java.util.List; /** * Created by Administrator on 15-12-28. */ public class MyAdapter extends FragmentPagerAdapter{ private List<Fragment> fragments; private List<String> titles; public MyAdapter(FragmentManager fm, List<Fragment> fragments,List<String> title) { super(fm); this.fragments = fragments; this.titles = title; } @Override public Fragment getItem(int position) { Fragment fragment = fragments.get(position); return fragment; } @Override public int getCount() { return fragments.size(); } @Override public CharSequence getPageTitle(int position) { return titles.get(position); } }
package tk.jimmywang.attendance.app.model; /** * <i>Created by WangJin on 2014-08-30 23:38. * * @author WangJin * @version 1.0 */ public class Worker extends BaseModel{ private String name; private String phoneNumber; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } }
package com.cs240.server.java.dao; import model.Authtoken; import model.Person; import model.User; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import javax.xml.crypto.Data; import java.sql.Connection; import static org.junit.jupiter.api.Assertions.*; /*** * Tests all public UserDAO functions for a pass and a fail, other than * clear and delete table. */ class UserDAOTest { private Database db; private UserDAO uDAO; /*** * Load Test data for User tests * * @throws DataAccessException - If this fails, they all fail * @throws ClassNotFoundException - If this fails, they all fail */ @BeforeAll public static void load() throws DataAccessException, ClassNotFoundException { final String driver = "org.sqlite.JDBC"; Class.forName(driver); //Create Database. And get the connection. Database db = new Database(); Connection c = db.getConnection(); UserDAO uDAO = new UserDAO(c); //Set up blank tables uDAO.createTable(); uDAO.clear(); //Test data User user1 = new User("Bob","Bob","Bob","Bob", "Bob","Bob","M"); User user2 = new User("username","username","password","username", "me","you","M"); User user3 = new User("Katie","Katie","I<3Me","Katie", "Katie","Smiths","F"); //Insert test data uDAO.insertUser(user1); uDAO.insertUser(user2); uDAO.insertUser(user3); //Close connection - Commit db.closeConnection(true); } /*** * Creates a new connection to the database and initializes uDAO * * @throws DataAccessException - If this fails, they all fail * @throws ClassNotFoundException - If this fails, they all fail */ @BeforeEach public void setUp() throws DataAccessException, ClassNotFoundException { db = new Database(); Connection c = db.getConnection(); uDAO = new UserDAO(c); } /*** * Closes connection and does not commit changes * * @throws DataAccessException - If this fails, they all fail */ @AfterEach public void tearDown() throws DataAccessException { db.closeConnection(false); } /*** * Test that a new table has been created. * Nate should have been loaded into the new table. * * @throws DataAccessException - Tried to find Nate and did */ @Test void createTablePass() throws DataAccessException { uDAO.dropTable(); uDAO.createTable(); User user1 = new User("Nate","Nate","coolbro","Nate", "Nate","Thomas","M"); uDAO.insertUser(user1); assertEquals(uDAO.fetchUser("Nate","coolbro").getLastName(), "Thomas"); } /*** * Test that a new table has been created. * Nate should not be in the new table. * * @throws DataAccessException - Tried to find Nate and didnt */ @Test void createTablefail() throws DataAccessException { uDAO.dropTable(); uDAO.createTable(); assertNull(uDAO.fetchUser("Nate","coolbro")); } /*** * Test that the database fetched Katie * * @throws DataAccessException - Ignore */ @Test void fetchUserPass() throws DataAccessException { User user = uDAO.fetchUser("Katie","I<3Me"); assertEquals("Smiths",user.getLastName()); } /*** * Test that the database did not fetch BrighamYoung * * @throws DataAccessException - Ignore */ @Test void fetchUserFail() throws DataAccessException { User user = uDAO.fetchUser("BrighamYoung","BYU"); assertNull(user); } /*** * Test that the database inserted Tim Jones * * @throws DataAccessException - Ignore */ @Test void insertUserPass() throws DataAccessException { User user = new User("person","Robot","IROBOT","google", "Tim","Jones","M"); uDAO.insertUser(user); User actual = uDAO.fetchUser("Robot","IROBOT"); assertEquals("Jones",actual.getLastName()); } /*** * Test that database rejects null users. * * @throws DataAccessException - Ignore */ @Test void insertUserFail() throws DataAccessException { User actual = new User("Darth",null,"Im your father","Skywalker", "Darth","Vader","M"); assertThrows(DataAccessException.class, () ->{uDAO.insertUser(actual);}); } /*** * Tried to find username, but table was cleared. * * @throws DataAccessException - Ignore */ @Test void clear() throws DataAccessException { uDAO.clear(); assertNull(uDAO.fetchUser("username","password")); } }
package com.gsccs.sme.center.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.subject.Subject; 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.ResponseBody; import com.alibaba.fastjson.JSONObject; import com.gsccs.sme.api.domain.Account; import com.gsccs.sme.api.domain.base.JsonMsg; import com.gsccs.sme.api.domain.corp.Corp; import com.gsccs.sme.api.exception.ApiException; import com.gsccs.sme.api.service.AccountServiceI; import com.gsccs.sme.api.service.CorpServiceI; import com.gsccs.sme.shiro.client.UserPwdSiteToken; import com.gsccs.sme.web.api.service.RedisService; /** * 会员登录管理 * * @author x.d zhang * */ @Controller public class LoginController { @Autowired private CorpServiceI corpAPI; @Autowired private AccountServiceI accountAPI; @Autowired private RedisService redisService; @RequestMapping(value = "/login.html", method = RequestMethod.GET) public String doGet(Model model, HttpServletResponse response) { String tempPath = "html/login.html"; Corp corp = null; try { Subject subject = SecurityUtils.getSubject(); String username = (String) subject.getPrincipal(); Account user = accountAPI.getAccount(username); corp = corpAPI.getCorp(user.getId()); if (null == corp) { tempPath = "shop/shop404.html"; } } catch (Exception e) { e.printStackTrace(); } return null; } @RequestMapping(value = "/login", method = RequestMethod.POST) @ResponseBody public JsonMsg showLoginForm(HttpServletRequest req, Model model) { JsonMsg json = new JsonMsg(); String error = null; String username = req.getParameter("username"); String password = req.getParameter("password"); Subject subject = SecurityUtils.getSubject(); UserPwdSiteToken token = new UserPwdSiteToken(); token.setUsername(username); token.setPassword(password.toCharArray()); token.setRememberMe(true); try { subject.login(token); json.setSuccess(true); return json; } catch (UnknownAccountException e) { error = "用户名不存在"; } catch (IncorrectCredentialsException e) { error = "用户名/密码错误"; } catch (AuthenticationException e) { e.printStackTrace(); error = "其他错误:" + e.getMessage(); } json.setSuccess(false); json.setMsg(error); return json; } @RequestMapping(value = "/checkSession", method = RequestMethod.POST) @ResponseBody public JsonMsg checkSession(HttpServletRequest req, Model model) { JsonMsg json = new JsonMsg(); Subject subject = SecurityUtils.getSubject(); String account = (String) subject.getPrincipal(); if (StringUtils.isEmpty(account)) { json.setSuccess(false); } else { try { Account user = accountAPI.getAccount(account); if (null != user) { json.setSuccess(true); json.setData(user); } } catch (ApiException e) { json.setSuccess(false); } } return json; } @RequestMapping(value = "/updatepwd", method = RequestMethod.GET) public String updatepwd(Model model, HttpServletResponse response) { try { Subject subject = SecurityUtils.getSubject(); String username = (String) subject.getPrincipal(); Account user = accountAPI.getAccount(username); model.addAttribute("user", user); } catch (Exception e) { e.printStackTrace(); } return "corp/updatepwd"; } @ResponseBody @RequestMapping(value = "/updatepwd", method = RequestMethod.POST) public JsonMsg updatepwdPost(Long userid, String pwd, Model model, HttpServletResponse response) { JsonMsg jsonMsg = new JsonMsg(); try { Subject subject = SecurityUtils.getSubject(); String username = (String) subject.getPrincipal(); Account account = accountAPI.getAccount(username); if (account.getId() == userid && StringUtils.isNotEmpty(pwd)) { account.setPassword(pwd); accountAPI.updateAccount(account); jsonMsg.setSuccess(true); jsonMsg.setMsg("密码更新成功!"); } else { jsonMsg.setSuccess(false); jsonMsg.setMsg("密码更新失败!"); } } catch (Exception e) { e.printStackTrace(); } return jsonMsg; } /** * 用户注销 * * @return */ @RequestMapping("/logout") @ResponseBody public JSONObject logout() { // 清除用户session Subject subject = SecurityUtils.getSubject(); subject.logout(); return null; } }
package net.lantrack.project.base.controller; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.socket.TextMessage; import net.lantrack.framework.core.entity.ReturnEntity; import net.lantrack.framework.socket.MySocketHandle; @RestController @RequestMapping("socketpush") public class SocketPushController { @Autowired private MySocketHandle mySocketHandler; // socketpush/login @RequestMapping("login") public ReturnEntity login(HttpSession session, ReturnEntity info,String name) { session.setAttribute("user", name); info.success(name + "登录了"); return info; } // socketpush/sendMessage @RequestMapping("sendMessage") public ReturnEntity sendMessage(HttpSession session, ReturnEntity info,String message) { String name = (String) session.getAttribute("user"); mySocketHandler.sendMessageToUsers(name, new TextMessage(name + " : " + message)); return info; } }
package com.company; public class Device { private String brand; private String deviceModel; private OS os; private String osVersion; public Device(String brand, String deviceModel, OS os, String osVersion) { this.brand = brand; this.deviceModel = deviceModel; this.os = os; this.osVersion = osVersion; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getDeviceModel() { return deviceModel; } public void setDeviceModel(String deviceModel) { this.deviceModel = deviceModel; } public OS getOs() { return os; } public void setOs(OS os) { this.os = os; } public String getOsVersion() { return osVersion; } public void setOsVersion(String osVersion) { this.osVersion = osVersion; } }
/* * Welcome to use the TableGo Tools. * * http://vipbooks.iteye.com * http://blog.csdn.net/vipbooks * http://www.cnblogs.com/vipbooks * * Author:bianj * Email:edinsker@163.com * Version:5.8.0 */ package com.lenovohit.hcp.outpatient.model; import java.util.Date; import javax.persistence.Entity; import javax.persistence.Table; /** * TREAT_MEDICAL_RECORD * * @author zyus * @version 1.0.0 2017-12-16 */ public class IMedicalRecord implements java.io.Serializable { private String hosNo; private String hosName; private String proNo; private String proName; private String cardNo; private String cardType; private String actNo; private String appointNo; private String chiefComplaint; private String presentIllness; private String pastHistory; private String allergicHistory; private String physicalExam; private String otherExam; private String moOrder; private String weight; private String height; private Date seeTime; private String seeDept; private String seeDoc; private String medicalRecordsType; private String bloodPressureprMin; private String bloodPressureprMax; private String temperature; private String pulseRate; private String breath; private Date startDate; private Date endDate; public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public String getHosNo() { return hosNo; } public void setHosNo(String hosNo) { this.hosNo = hosNo; } public String getHosName() { return hosName; } public void setHosName(String hosName) { this.hosName = hosName; } public String getProNo() { return proNo; } public void setProNo(String proNo) { this.proNo = proNo; } public String getProName() { return proName; } public void setProName(String proName) { this.proName = proName; } public String getCardNo() { return cardNo; } public void setCardNo(String cardNo) { this.cardNo = cardNo; } public String getCardType() { return cardType; } public void setCardType(String cardType) { this.cardType = cardType; } public String getActNo() { return actNo; } public void setActNo(String actNo) { this.actNo = actNo; } public String getAppointNo() { return appointNo; } public void setAppointNo(String appointNo) { this.appointNo = appointNo; } public String getChiefComplaint() { return chiefComplaint; } public void setChiefComplaint(String chiefComplaint) { this.chiefComplaint = chiefComplaint; } public String getPresentIllness() { return presentIllness; } public void setPresentIllness(String presentIllness) { this.presentIllness = presentIllness; } public String getPastHistory() { return pastHistory; } public void setPastHistory(String pastHistory) { this.pastHistory = pastHistory; } public String getAllergicHistory() { return allergicHistory; } public void setAllergicHistory(String allergicHistory) { this.allergicHistory = allergicHistory; } public String getPhysicalExam() { return physicalExam; } public void setPhysicalExam(String physicalExam) { this.physicalExam = physicalExam; } public String getOtherExam() { return otherExam; } public void setOtherExam(String otherExam) { this.otherExam = otherExam; } public String getMoOrder() { return moOrder; } public void setMoOrder(String moOrder) { this.moOrder = moOrder; } public String getWeight() { return weight; } public void setWeight(String weight) { this.weight = weight; } public String getHeight() { return height; } public void setHeight(String height) { this.height = height; } public Date getSeeTime() { return seeTime; } public void setSeeTime(Date seeTime) { this.seeTime = seeTime; } public String getSeeDept() { return seeDept; } public void setSeeDept(String seeDept) { this.seeDept = seeDept; } public String getSeeDoc() { return seeDoc; } public void setSeeDoc(String seeDoc) { this.seeDoc = seeDoc; } public String getMedicalRecordsType() { return medicalRecordsType; } public void setMedicalRecordsType(String medicalRecordsType) { this.medicalRecordsType = medicalRecordsType; } public String getBloodPressureprMin() { return bloodPressureprMin; } public void setBloodPressureprMin(String bloodPressureprMin) { this.bloodPressureprMin = bloodPressureprMin; } public String getBloodPressureprMax() { return bloodPressureprMax; } public void setBloodPressureprMax(String bloodPressureprMax) { this.bloodPressureprMax = bloodPressureprMax; } public String getTemperature() { return temperature; } public void setTemperature(String temperature) { this.temperature = temperature; } public String getPulseRate() { return pulseRate; } public void setPulseRate(String pulseRate) { this.pulseRate = pulseRate; } public String getBreath() { return breath; } public void setBreath(String breath) { this.breath = breath; } /** 版本号 */ }
package com.appunite.ffmpeg; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Cap; import android.graphics.Paint.Join; import android.graphics.Paint.Style; import android.graphics.Rect; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; public class SeekerView extends View { private int mBarColor; private int mBarMinHeight; private int mBarMinWidth; private Paint mBarPaint; private Rect mBarRect; private int mBorderColor; private int mBorderPadding; private Paint mBorderPaint; private Rect mBorderRect; private int mBorderWidth; private int mCurrentValue; private int mMaxValue; private OnProgressChangeListener mOnProgressChangeListener; public interface OnProgressChangeListener { void onProgressChange(boolean z, int i, int i2); } public void setOnProgressChangeListener(OnProgressChangeListener onProgressChangeListener) { this.mOnProgressChangeListener = onProgressChangeListener; } public SeekerView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); this.mBorderPaint = new Paint(); this.mBarPaint = new Paint(); this.mBorderRect = new Rect(); this.mBarRect = new Rect(); this.mOnProgressChangeListener = null; this.mMaxValue = 100; this.mCurrentValue = 10; TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.SeekerView, defStyle, 0); float scale = getResources().getDisplayMetrics().density; this.mBorderWidth = a.getDimensionPixelSize(R.styleable.SeekerView_borderWidth, (int) ((1.0f * scale) + 0.5f)); this.mBorderColor = a.getColor(R.styleable.SeekerView_barColor, -16711681); this.mBorderPadding = a.getColor(R.styleable.SeekerView_borderPadding, (int) ((1.0f * scale) + 0.5f)); this.mBarMinHeight = a.getDimensionPixelSize(R.styleable.SeekerView_barMinHeight, (int) ((10.0f * scale) + 0.5f)); this.mBarMinWidth = a.getDimensionPixelSize(R.styleable.SeekerView_barMinWidth, (int) ((50.0f * scale) + 0.5f)); this.mBarColor = a.getColor(R.styleable.SeekerView_barColor, -16776961); this.mBorderPaint.setDither(true); this.mBorderPaint.setColor(this.mBorderColor); this.mBorderPaint.setStyle(Style.STROKE); this.mBorderPaint.setStrokeJoin(Join.ROUND); this.mBorderPaint.setStrokeCap(Cap.ROUND); this.mBorderPaint.setStrokeWidth((float) this.mBorderWidth); this.mBarPaint.setDither(true); this.mBarPaint.setColor(this.mBarColor); this.mBarPaint.setStyle(Style.FILL); this.mBarPaint.setStrokeJoin(Join.ROUND); this.mBarPaint.setStrokeCap(Cap.ROUND); this.mMaxValue = a.getInt(R.styleable.SeekerView_maxValue, this.mMaxValue); this.mCurrentValue = a.getInt(R.styleable.SeekerView_currentValue, this.mCurrentValue); } public SeekerView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public SeekerView(Context context) { this(context, null); } public void setMaxValue(int maxValue) { this.mMaxValue = maxValue; invalidate(); } public int maxValue() { return this.mMaxValue; } public void setCurrentValue(int currentValue) { this.mCurrentValue = currentValue; invalidate(); } public int currentValue() { return this.mCurrentValue; } protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawRect(this.mBorderRect, this.mBorderPaint); canvas.drawRect(this.mBarRect, this.mBarPaint); } public boolean onTouchEvent(MotionEvent event) { int action = event.getActionMasked(); boolean superResult = super.onTouchEvent(event); boolean grab = false; boolean finished = false; if (action == 0) { grab = true; } else if (action == 2) { grab = true; } else if (action == 1) { grab = true; finished = true; } if (!grab) { return superResult; } int padding = this.mBorderWidth + this.mBorderPadding; int barWidth = getWidth() - (padding * 2); float x = event.getX() - ((float) padding); if (x < 0.0f) { x = 0.0f; } if (x > ((float) barWidth)) { x = (float) barWidth; } this.mCurrentValue = (int) (((float) this.mMaxValue) * (x / ((float) barWidth))); if (this.mOnProgressChangeListener != null) { this.mOnProgressChangeListener.onProgressChange(finished, this.mCurrentValue, this.mMaxValue); } calculateBarRect(); invalidate(); return true; } protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(ViewCompat.resolveSizeAndState(((this.mBorderWidth + this.mBorderPadding) * 2) + this.mBarMinWidth, widthMeasureSpec, 0), ViewCompat.resolveSizeAndState(((this.mBorderWidth + this.mBorderPadding) * 2) + this.mBarMinHeight, heightMeasureSpec, 0)); } private void calculateBarRect() { int width = getWidth(); int barPadding = this.mBorderWidth + this.mBorderPadding; float pos = ((float) this.mCurrentValue) / ((float) this.mMaxValue); int barWidth = (int) (((float) (width - barPadding)) * pos); this.mBarRect.set(barPadding, barPadding, barWidth, getHeight() - barPadding); } protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (changed) { this.mBorderRect.set(0, 0, right - left, bottom - top); calculateBarRect(); } } }
package com.heihei.adapter; import java.util.List; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageView; import com.base.host.AppLogic; import com.facebook.fresco.FrescoImageHelper; import com.facebook.fresco.FrescoImageView; import com.heihei.dialog.UserDialog; import com.heihei.fragment.live.widget.AvatarImageView; import com.heihei.logic.UserMgr; import com.heihei.model.PlayActivityInfo; import com.heihei.model.User; import com.wmlives.heihei.R; public class AudienceAdapter extends RecyclerView.Adapter<AudienceAdapter.ViewHolder> { List<User> data; private String liveId = ""; private boolean isCreator = false; private PlayActivityInfo info = null; private Context context; public AudienceAdapter(List<User> data, Context context) { this.data = data; this.context = context; } public void setLiveIdAndIsCreator(String liveId, boolean isCreator) { this.liveId = liveId; this.isCreator = isCreator; } public void setReplayInfo(PlayActivityInfo info) { this.info = info; } public class ViewHolder extends RecyclerView.ViewHolder { private AvatarImageView iv_avatar; private ImageView iv_followed; public ViewHolder(View arg0) { super(arg0); iv_avatar = (AvatarImageView) arg0.findViewById(R.id.iv_avatar); iv_followed = (ImageView) arg0.findViewById(R.id.iv_followed); } } @Override public int getItemCount() { if (data == null) return 0; return data.size(); } @Override public void onBindViewHolder(ViewHolder vh, int position) { final User itemuser = data.get(position); if (itemuser.isFollowed) { vh.iv_followed.setVisibility(View.VISIBLE); if (itemuser.gender == User.FEMALE) { vh.iv_followed.setImageResource(R.drawable.hh_live_following_female); } else { vh.iv_followed.setImageResource(R.drawable.hh_live_following_male); } } else { vh.iv_followed.setVisibility(View.GONE); } vh.iv_avatar.setUser(data.get(position)); vh.iv_avatar.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (UserMgr.getInstance().getUid().equals(itemuser.uid)) { return; } if (!clickOlder()) { return; } UserDialog ud = new UserDialog(context, itemuser, liveId, isCreator, UserDialog.USERDIALOG_OPENTYPE_AUDIENCE); // if (isCreator) { // ud.setChatable(false); // } ud.setReplayInfo(info); ud.show(); } }); } private long lastClickTime = 0; private boolean clickOlder() { long currentTime = System.currentTimeMillis(); if (!(currentTime - lastClickTime > AppLogic.MIN_CLICK_DELAY_TIME)) return false; lastClickTime = System.currentTimeMillis(); return true; } @Override public ViewHolder onCreateViewHolder(ViewGroup arg0, int arg1) { View view = LayoutInflater.from(arg0.getContext()).inflate(R.layout.cell_audience, arg0, false); ViewHolder vh = new ViewHolder(view); return vh; } }
package com.itheima.drawimg; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Paint.Cap; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.Toast; import android.widget.SeekBar.OnSeekBarChangeListener; public class MainActivity extends Activity implements OnClickListener, OnSeekBarChangeListener, OnTouchListener { private ImageView ivResult; private SeekBar seekBar; private Bitmap bitmap; private Canvas canvas; private Paint paint; private Matrix matrix; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.iv_red).setOnClickListener(MainActivity.this); findViewById(R.id.iv_green).setOnClickListener(MainActivity.this); findViewById(R.id.iv_blue).setOnClickListener(MainActivity.this); findViewById(R.id.iv_yellow).setOnClickListener(MainActivity.this); findViewById(R.id.iv_purple).setOnClickListener(MainActivity.this); ivResult = (ImageView) findViewById(R.id.iv_result); seekBar = (SeekBar) findViewById(R.id.seekBar); // 设置监听进度 seekBar.setOnSeekBarChangeListener(MainActivity.this); // 设置屏幕触摸 ivResult.setOnTouchListener(MainActivity.this); bitmap = Bitmap.createBitmap(300, 300, Bitmap.Config.ARGB_4444); canvas = new Canvas(bitmap); //默认画板背景都是黑色的 canvas.drawColor(Color.WHITE); paint = new Paint(); paint.setStrokeCap(Cap.ROUND);//设置画笔形状 matrix = new Matrix(); } //初始化菜单 @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } //点击菜单item时调用 @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_save: File file = new File("/mnt/sdcard/"+System.currentTimeMillis()+".jpg"); OutputStream stream; try { stream = new FileOutputStream(file); //保存图片 /** * 参数1:图片格式(jpg、png) * 参数2:图片质量0-100 * 参数3:输出流 */ bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(); // intent.setAction(Intent.ACTION_MEDIA_MOUNTED);//android4.4以上,谷歌不允许发送该广播 // intent.setData(Uri.parse("file://"));//刷新所有文件,耗性能 intent.setAction(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);//刷新单个文件 //intent.setData(Uri.parse("/mnt/sdcar/xxx.jpg"));//刷新所有文件,耗性能 intent.setData(Uri.fromFile(file));//刷新所有文件,耗性能 // //通知相册刷新 sendBroadcast(intent); } catch (FileNotFoundException e) { e.printStackTrace(); } break; case R.id.action_clear: Toast.makeText(this, "清空", Toast.LENGTH_SHORT).show(); break; default: break; } return super.onOptionsItemSelected(item); } @Override public void onClick(View v) { // 如何判断点击那个id switch (v.getId()) { case R.id.iv_red: paint.setColor(Color.RED); break; case R.id.iv_green: paint.setColor(Color.GREEN); break; case R.id.iv_blue: paint.setColor(Color.BLUE); break; case R.id.iv_yellow: paint.setColor(Color.YELLOW); break; case R.id.iv_purple: paint.setColor(0xFFFF00FF); break; } } /** * 状态改变调用 */ @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { showLog("onProgressChanged"); } /** * 触摸时调用 */ @Override public void onStartTrackingTouch(SeekBar seekBar) { showLog("onStartTrackingTouch"); } /** * 触摸结束调用 */ @Override public void onStopTrackingTouch(SeekBar seekBar) { showLog("onStopTrackingTouch"); int progress = seekBar.getProgress();// 获取当前进度 Toast.makeText(this, "progress=" + progress, Toast.LENGTH_SHORT).show(); paint.setStrokeWidth(progress);//设置画笔粗细 } private void showLog(String msg) { Log.d("MainActivity", msg); } /** * 参数1:当前触摸的控件 * 参数2:触摸事件(坐标) */ private float downX, downY; @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN://按下 showLog("ACTION_DOWN"); //获取x、y轴按下坐标 downX = event.getX(); downY = event.getY(); break; case MotionEvent.ACTION_MOVE://移动 showLog("ACTION_MOVE"); float moveX = event.getX(); float moveY = event.getY(); //画线 // 5.开始作画 /** * 参数1:x轴开始坐标 参数2:y轴开始坐标 参数3:x轴结束坐标 参数4:y轴结束坐标 */ canvas.drawLine(downX, downY, moveX, moveY, paint); // 6.显示图像 ivResult.setImageBitmap(bitmap); //重置起点坐标 downX = moveX; downY = moveY; break; case MotionEvent.ACTION_UP://抬起 showLog("ACTION_UP"); break; } //true-当前控件消耗该事件,不往上传递,false-往上传递事件,后面有《自定义控件》 return true; } }
package com.gonzajf.spring.masteringSpring; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import com.gonzajf.spring.masteringSpring.controller.HomeController; @RunWith(SpringRunner.class) @WebMvcTest(HomeController.class) @WebAppConfiguration public class HomeControllerTest { @Autowired private WebApplicationContext wac; private MockMvc mockMvc; @Before public void setUp() { mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); } @Test public void should_redirect_to_profile() throws Exception { this.mockMvc.perform(get("/")) .andDo(print()) .andExpect(status().isFound()) .andExpect(redirectedUrl("/profile")); } }
package com.moh.departments.dialog; import android.app.Dialog; import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.util.Log; import android.view.Window; import android.widget.TextView; import com.moh.departments.R; public class DialogLoding { private static Dialog pDialog; TextView msg; public DialogLoding(Context act) { pDialog = new Dialog(act); pDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); pDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); pDialog.setContentView(R.layout.custom_dialog2); msg = pDialog.findViewById(R.id.loading_message); // img = (ImageView)pDialog.findViewById(R.id.loading_img); //animation = AnimationUtils.loadAnimation(act, R.anim.fade_in); //msg.startAnimation(animation); Log.e("dialog", "created"); pDialog.setCancelable(false); } public void showDialog(String my_msg) { msg.setText(my_msg); Log.e("dialog", my_msg); pDialog.show(); } public void hideDialog() { if (pDialog != null && pDialog.isShowing()) { pDialog.dismiss(); } /*android.os.Handler mHandler=new android.os.Handler(); mHandler.postDelayed(new Runnable() { @Override public void run() { if (pDialog != null && pDialog.isShowing()) { pDialog.dismiss(); } } },3000);*/ } }
package org.uva.forcepushql.interpreter.TypeChecker; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Collection; import java.util.Map.Entry; public class Messages { private final Collection<Entry<MessageTypes, String>> messagesCollection = new ArrayList<>(); public boolean isEmpty(){ return messagesCollection.isEmpty(); } public void addMessage(String message, MessageTypes messageType) { this.messagesCollection.add(new SimpleEntry<>(messageType, message)); } public boolean allWarning(){ boolean allWarning = true; for (Entry<MessageTypes, String> s: messagesCollection) { allWarning = allWarning && s.getKey().equals(MessageTypes.WARNING); } return allWarning; } @Override public String toString() { return this.messagesCollection.toString(); } public enum MessageTypes { WARNING, ERROR } }
/* * 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 icaresystem.Model; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Joseph Hackett */ public class HistoryTest { public HistoryTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } /** * Test of generateHistory method, of class History. */ @Test public void testGenerateHistory() { System.out.println("generateHistory"); History instance = null; instance.generateHistory(); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getId method, of class History. */ @Test public void testGetId() { System.out.println("getId"); History instance = null; int expResult = 0; int result = instance.getId(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of setId method, of class History. */ @Test public void testSetId() { System.out.println("setId"); int id = 0; History instance = null; instance.setId(id); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getHistoryType method, of class History. */ @Test public void testGetHistoryType() { System.out.println("getHistoryType"); History instance = null; String expResult = ""; String result = instance.getHistoryType(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of setHistoryType method, of class History. */ @Test public void testSetHistoryType() { System.out.println("setHistoryType"); String historyType = ""; History instance = null; instance.setHistoryType(historyType); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } }
package lka.wine.jdbc; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.List; import com.google.common.base.Strings; import lka.wine.dao.Brand; public class BrandsTable extends AbstractData<Brand> { private final static String tableName = "Brands"; private final static List<String> columnNames = Arrays.asList("BrandID", "BrandName"); @Override public Brand getObject(ResultSet rs) throws SQLException { Brand brand = new Brand(); brand.setBrandId(rs.getInt("BrandID")); brand.setBrandName(Strings.nullToEmpty(rs.getString("BrandName"))); return brand; } @Override public String getTableName() { return tableName; } @Override public String getIdColumnName() { return columnNames.get(0); } @Override public List<String> getColumnNames() { return columnNames; } @Override public int setParameters(PreparedStatement pstmt, Brand obj) throws SQLException { int index = 1; pstmt.setString(index++, obj.getBrandName()); return index; } }
package bis.project.services; import java.util.HashSet; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import bis.project.model.DailyAccountBalance; import bis.project.model.InterbankTransfer; import bis.project.model.LegalPersonDetails; import bis.project.repositories.DailyAccountBalanceRepository; import bis.project.repositories.InterbankTransferRepository; @Service public class InterbankTransferServicesImpl implements InterbankTransferServices { @Autowired private InterbankTransferRepository repository; @Override public Set<InterbankTransfer> getAllInterbankTrasfers() { Set<InterbankTransfer> clients = new HashSet<InterbankTransfer>(); for(InterbankTransfer client : repository.findAll()) { clients.add(client); } return clients; } @Override public InterbankTransfer getInterbankTransfer(Integer id) { return repository.findOne(id); } @Override public InterbankTransfer addInterbankTransfer(InterbankTransfer interbankTransfer) { return repository.save(interbankTransfer); } @Override public InterbankTransfer updateInterbankTransfer(InterbankTransfer interbankTransfer) { return repository.save(interbankTransfer); } @Override public void deleteInterbankTrasfer(Integer id) { InterbankTransfer client = repository.findOne(id); if(client != null) { repository.delete(id); } } }
// Decompiled by Jad v1.5.7d. Copyright 2000 Pavel Kouznetsov. // Jad home page: http:// www.geocities.com/SiliconValley/Bridge/8617/jad.html // Decompiler options: packimports(3) // Source File Name: Base64Decoder.java package com.ziaan.scorm.multi; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; public class Base64Decoder extends FilterInputStream { public Base64Decoder(InputStream inputstream) { super(inputstream); } public int read() throws IOException { int i; do { i = in.read(); if ( i == -1) return -1; } while ( Character.isWhitespace((char)i)); charCount++; if ( i == 61) return -1; i = ints[i]; int j = (charCount - 1) % 4; if ( j == 0) { carryOver = i & 0x3f; return read(); } if ( j == 1) { int k = (carryOver << 2) + (i >> 4) & 0xff; carryOver = i & 0xf; return k; } if ( j == 2) { int l = (carryOver << 4) + (i >> 2) & 0xff; carryOver = i & 0x3; return l; } if ( j == 3) { int i1 = (carryOver << 6) + i & 0xff; return i1; } else { return -1; } } public int read(byte abyte0[], int i, int j) throws IOException { int k; for ( k = 0; k < j; k++ ) { int l = read(); if ( l == -1 && k == 0) return -1; if ( l == -1) break; abyte0[i + k] = (byte)l; } return k; } public static String decode(String s) { byte abyte0[] = null; try { abyte0 = s.getBytes("8859_1"); } catch(UnsupportedEncodingException unsupportedencodingexception) { } Base64Decoder base64decoder = new Base64Decoder(new ByteArrayInputStream(abyte0)); ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream((int)((double)abyte0.length * 0.67000000000000004D)); try { byte abyte1[] = new byte[4096]; int i; while ( (i = base64decoder.read(abyte1)) != -1) bytearrayoutputstream.write(abyte1, 0, i); bytearrayoutputstream.close(); return bytearrayoutputstream.toString("8859_1"); } catch(IOException ioexception) { return null; } } public static void main(String args[]) throws Exception { if ( args.length != 1) System.err.println("Usage: java Base64Decoder fileToDecode"); Base64Decoder base64decoder = null; try { base64decoder = new Base64Decoder(new BufferedInputStream(new FileInputStream(args[0]))); byte abyte0[] = new byte[4096]; int i; while ( (i = base64decoder.read(abyte0)) != -1) System.out.write(abyte0, 0, i); } finally { if ( base64decoder != null ) base64decoder.close(); } } private static final char chars[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; private static final int ints[]; private int charCount; private int carryOver; static { ints = new int[128]; for ( int i = 0; i < 64; i++ ) ints[chars[i]] = i; } }
package com.lesports.airjordanplayer.ui; import android.content.Context; import android.support.annotation.NonNull; import com.lesports.airjordanplayer.VideoPlayerDisplaySurfaceView; import com.lesports.airjordanplayer.conf.VideoPlayerConfiguration; import com.lesports.airjordanplayer.ui.strategy.LastSelectedQualityStrategy; import com.lesports.airjordanplayer.ui.strategy.MoreHighResolutionQualityStrategy; import com.lesports.airjordanplayer.ui.strategy.StreamQualitySelectionStrategy; /** * Created by tianzhenhai on 2015/6/25. */ public class VideoPlayerSetting { // 接口API请求时的caller,由后台定义 public static final String API_CALLER = "1003"; //播放器默认宽高比 private VideoPlayerDisplaySurfaceView.VideoDisplaySurfaceResizeMode resizeMode; //播放器初始方向竖屏还是横屏 private ScreenOrientation screenOrientation = ScreenOrientation.PORTRAIT; //播放器是否支持转屏 private boolean enableRotateAutomatically = true; //是否显示打印log private boolean enableDebugMode = false; //是否缓存本地 private boolean supportDownloading = false; private StreamQualitySelectionStrategy qualitySelectionStrategy; private Context mContext; private VideoPlayerConfiguration mConfiguration; public VideoPlayerSetting(@NonNull final Context context) { this.mContext = context; } public StreamQualitySelectionStrategy getQualitySelectionStrategy() { if (qualitySelectionStrategy == null) return new LastSelectedQualityStrategy(mContext); // return new LastSelectedQualityStrategy(mContext); return qualitySelectionStrategy; } public void setQualitySelectionStrategy(StreamQualitySelectionStrategy mQualitySelectionStrategy) { this.qualitySelectionStrategy = mQualitySelectionStrategy; } public VideoPlayerDisplaySurfaceView.VideoDisplaySurfaceResizeMode getResizeMode() { return resizeMode; } public void setResizeMode(VideoPlayerDisplaySurfaceView.VideoDisplaySurfaceResizeMode resizeMode) { this.resizeMode = resizeMode; } public ScreenOrientation getScreenOrientation() { return screenOrientation; } public void setScreenOrientation(ScreenOrientation screenOrientation) { this.screenOrientation = screenOrientation; } public boolean isEnableRotateAutomatically() { return enableRotateAutomatically; } public void setEnableRotateAutomatically(boolean enableRotateAutomatically) { this.enableRotateAutomatically = enableRotateAutomatically; } public boolean isEnableDebugMode() { return enableDebugMode; } public void setEnableDebugMode(boolean enableDebugMode) { this.enableDebugMode = enableDebugMode; } public boolean isSupportDownloading() { return supportDownloading; } public void setSupportDownloading(boolean supportDownloading) { this.supportDownloading = supportDownloading; } public boolean isCanChangeScreenOrientation() { // TODO: 设置是否转屏策略 return true; } public enum ScreenOrientation { LANDSCAPE_LEFT, LANDSCAPE_RIGHT, PORTRAIT, PORTRAIT_UPSIDEDOWN } }
package com.ifeng.recom.mixrecall.core.service; import com.ifeng.recom.mixrecall.common.model.RecordInfo; import java.util.List; import java.util.Map; /** * Created by geyl on 2017/11/9. */ public class RecallNumberControl { private int recallNumber = 500; private double sumWeight; private List<RecordInfo> list; private Map<String, Double> tagWithWeightMap; public RecallNumberControl(List<RecordInfo> list, Map<String, Double> tagWithWeightMap, int recallNumber) { this.list = list; this.tagWithWeightMap = tagWithWeightMap; this.recallNumber = recallNumber; init(); } private void init() { for (RecordInfo recordInfo : list) { sumWeight += (recordInfo.getWeight() - 0.5); } } public int getRecallNumber(String tagName) { try { double s = (tagWithWeightMap.get(tagName) - 0.5) / sumWeight; //归一化后的tag权重 return (int) (Math.ceil(Math.log1p(s) * recallNumber)); } catch (Exception e) { return 5; } } }
package f.star.iota.milk.ui.bcy.ranking; import android.os.Bundle; import java.util.Date; import f.star.iota.milk.util.DateUtils; public class BCYRankingFragment extends BCYScrollImageFragment<BCYRankingPresenter, BCYRankingAdapter> { public static BCYRankingFragment newInstance(String url){ BCYRankingFragment fragment = new BCYRankingFragment(); Bundle bundle = new Bundle(); bundle.putString("base_url", url); bundle.putString("page_suffix","&date="+ DateUtils.dateFormat(new Date(), DateUtils.DATE_PATTERN_YYYYMMDD)); fragment.setArguments(bundle); return fragment; } @Override protected BCYRankingPresenter getPresenter() { return new BCYRankingPresenter(this); } @Override protected BCYRankingAdapter getAdapter() { return new BCYRankingAdapter(); } }
/** * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.thinkgem.jeesite.modules.sys.web; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.shiro.authz.annotation.RequiresRoles; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.google.common.collect.Maps; import com.thinkgem.jeesite.common.utils.CacheUtils; import com.thinkgem.jeesite.common.utils.StringUtils; import com.thinkgem.jeesite.common.web.BaseController; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; /** * 管理系统中的缓存 * * @author lsp * */ @Controller @RequestMapping(value = "${adminPath}/sys/cache") public class CacheController extends BaseController { @RequiresRoles("administrator") @RequestMapping(value = { "list", "" }) public String list(String cacheName, String key, HttpServletRequest request, HttpServletResponse response, Model model) { Map<String, Cache> cacheMap = Maps.newHashMap(); CacheManager cacheManager = CacheUtils.getCacheManager(); if (cacheManager != null) { String[] cacheNames = cacheManager.getCacheNames(); for (String name : cacheNames) { Cache cache = cacheManager.getCache(name); cacheMap.put(name, cache); } } model.addAttribute("cacheMap", cacheMap); model.addAttribute("ename", "cache"); return "modules/sys/cache/cacheList"; } @RequiresRoles("administrator") @RequestMapping(value = "delete") public String delete(String cacheName, String key, RedirectAttributes redirectAttributes) { logger.debug("delete cacheName : {} , key : {}", cacheName, key); try { if (StringUtils.isNotBlank(cacheName)) { if (StringUtils.isNotBlank(key)) { CacheUtils.remove(cacheName, key); } else { Cache cache = CacheUtils.getCacheManager().getCache(cacheName); if (cache != null) { cache.removeAll(); } CacheUtils.getCacheManager().removeCache(cacheName); } } addMessage(redirectAttributes, "删除缓存成功"); } catch (Exception e) { e.printStackTrace(); addMessage(redirectAttributes, "删除缓存失败"); } return "redirect:" + adminPath + "/sys/cache/"; } }
/* * Copyright (C) 2015 Adrien Guille <adrien.guille@univ-lyon2.fr> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package main.java.fr.ericlab.sondy.core.structures; import java.util.HashSet; import java.util.LinkedList; import javafx.collections.FXCollections; import javafx.collections.ObservableList; /** * * @author Adrien GUILLE, Laboratoire ERIC, Université Lumière Lyon 2 */ public class Events { public LinkedList<Event> list = new LinkedList<>(); public ObservableList<Event> observableList; public Events(ObservableList<Event> ol){ observableList = ol; for(Event e : observableList){ list.add(e); } } public Events() { observableList = FXCollections.observableArrayList(); } public void setFullList(){ observableList.addAll(list); } public void filterList(String term){ if(term.length() > 0){ HashSet<Integer> indexes = new HashSet<>(); for(int i = 0; i < observableList.size(); i++){ if(!observableList.get(i).getTextualDescription().contains(term)){ indexes.add(i); } } for(int j : indexes){ observableList.remove(j); } }else{ setFullList(); } } }
package com.lwl.yikao.base; import android.support.v4.view.GravityCompat; import android.support.v7.widget.PopupMenu; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import com.lwl.yikao.R; import me.yokeyword.fragmentation.SupportFragment; /** * Created by lwl on 16/11/19. */ public class BaseFragment extends SupportFragment { protected void initToolbarMenu(final Toolbar toolbar) { toolbar.inflateMenu(R.menu.home); toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.tb_more: final PopupMenu popupMenu = new PopupMenu(_mActivity, toolbar, GravityCompat.END); popupMenu.inflate(R.menu.home_pop); popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.tb_more_setting: //TODO 跳转到设置页面 break; } popupMenu.dismiss(); return true; } }); popupMenu.show(); break; } return true; } }); } }
package dao.product.impl; import dao.product.ProductDao; import entity.Product; import lombok.AccessLevel; import lombok.RequiredArgsConstructor; import lombok.experimental.FieldDefaults; import java.sql.*; import java.util.ArrayList; import java.util.List; @RequiredArgsConstructor @FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true) public class ProductDaoImpl implements ProductDao { Connection connection; static String CREATING_QUERY = "INSERT INTO product (id, name, code, quantity, price) VALUES(?,?,?,?,?);"; static String FIND_ALL_QUERY = "SELECT * FROM product;"; static String FIND_BY_CODE_QUERY = "SELECT * FROM product WHERE code =?;"; @Override public void save(Product product) { try (PreparedStatement preparedStatement = connection.prepareStatement(CREATING_QUERY)) { preparedStatement.setLong(1, product.getId()); preparedStatement.setString(2, product.getName()); preparedStatement.setString(3, product.getCode()); preparedStatement.setInt(4, product.getQuantity()); preparedStatement.setInt(5, product.getPrice()); preparedStatement.execute(); } catch (SQLException e) { e.printStackTrace(); } } @Override public List<Product> findAll() { List<Product> productsList = new ArrayList<>(); try (Statement statement = connection.createStatement()) { ResultSet resultSet = statement.executeQuery(FIND_ALL_QUERY); while (resultSet.next()) { Product product = new Product( resultSet.getLong("id"), resultSet.getString("name"), resultSet.getString("code"), resultSet.getInt("quantity"), resultSet.getInt("price") ); productsList.add(product); } } catch (SQLException e) { e.printStackTrace(); } return productsList; } public Product findByCode(String code) { try (PreparedStatement preparedStatement = connection.prepareStatement(FIND_BY_CODE_QUERY)) { preparedStatement.setString(1, code); ResultSet rs = preparedStatement.executeQuery(); if (rs.next()) { return new Product( rs.getLong("id"), rs.getString("name"), rs.getString("code"), rs.getInt("quantity"), rs.getInt("price") ); } return null; } catch (SQLException e) { e.printStackTrace(); return null; } } }
package io.gtrain.exception; import io.gtrain.domain.model.dto.message.AuthenticationFailedMessage; import org.springframework.http.HttpStatus; import reactor.core.publisher.Mono; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; /** * @author William Gentry */ public class InvalidAuthenticationFormatException extends GlmsException { @Override public HttpStatus getHttpStatus() { return HttpStatus.UNPROCESSABLE_ENTITY; } @Override public Mono<AuthenticationFailedMessage> getValidationMessages() { return Mono.just(new AuthenticationFailedMessage("Authentication attempt in illegal format")); } }
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2011 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): ActiveEon Team - http://www.activeeon.com * * ################################################################ * $$ACTIVEEON_CONTRIBUTOR$$ */ package functionaltests; import static junit.framework.Assert.assertTrue; import org.ow2.proactive.scheduler.common.Scheduler; import org.ow2.proactive.scheduler.common.SchedulerEvent; import org.ow2.proactive.scheduler.common.SchedulerStatus; import org.ow2.tests.FunctionalTest; /** * This class tests the different job events of the ProActive scheduler : * pauseJob, resumeJob, killjob, changePriority, etc... * * * @author The ProActive Team * @date 2 jun 08 * @since ProActive Scheduling 1.0 */ public class TestSchedulerMiscEvents extends FunctionalTest { /** * Tests starts here. * * @throws Throwable any exception that can be thrown during the test. */ @org.junit.Test public void run() throws Throwable { Scheduler schedAdminInterface = SchedulerTHelper.getSchedulerInterface(); SchedulerTHelper.log("Try many tests about scheduler state"); assertTrue(!schedAdminInterface.start()); assertTrue(!schedAdminInterface.resume()); assertTrue(schedAdminInterface.stop()); SchedulerTHelper.log("waiting scheduler stopped event"); SchedulerTHelper.waitForEventSchedulerState(SchedulerEvent.STOPPED); assertTrue(schedAdminInterface.getStatus().equals(SchedulerStatus.STOPPED)); assertTrue(!schedAdminInterface.pause()); assertTrue(!schedAdminInterface.freeze()); assertTrue(schedAdminInterface.start()); SchedulerTHelper.log("waiting scheduler started event"); SchedulerTHelper.waitForEventSchedulerState(SchedulerEvent.STARTED); assertTrue(schedAdminInterface.getStatus().equals(SchedulerStatus.STARTED)); assertTrue(schedAdminInterface.pause()); SchedulerTHelper.log("waiting scheduler paused event"); SchedulerTHelper.waitForEventSchedulerState(SchedulerEvent.PAUSED); assertTrue(schedAdminInterface.getStatus().equals(SchedulerStatus.PAUSED)); assertTrue(schedAdminInterface.freeze()); SchedulerTHelper.log("waiting scheduler frozen event"); SchedulerTHelper.waitForEventSchedulerState(SchedulerEvent.FROZEN); assertTrue(schedAdminInterface.getStatus().equals(SchedulerStatus.FROZEN)); assertTrue(schedAdminInterface.stop()); SchedulerTHelper.log("waiting scheduler stopped event"); SchedulerTHelper.waitForEventSchedulerState(SchedulerEvent.STOPPED); assertTrue(schedAdminInterface.getStatus().equals(SchedulerStatus.STOPPED)); assertTrue(!schedAdminInterface.resume()); //TODO resume from stopped doesn't throw any event ? assertTrue(schedAdminInterface.start()); SchedulerTHelper.log("waiting scheduler started event"); SchedulerTHelper.waitForEventSchedulerState(SchedulerEvent.STARTED); assertTrue(schedAdminInterface.getStatus().equals(SchedulerStatus.STARTED)); assertTrue(schedAdminInterface.freeze()); SchedulerTHelper.log("waiting scheduler frozen event"); SchedulerTHelper.waitForEventSchedulerState(SchedulerEvent.FROZEN); assertTrue(schedAdminInterface.getStatus().equals(SchedulerStatus.FROZEN)); assertTrue(schedAdminInterface.resume()); SchedulerTHelper.log("waiting scheduler resumed event"); SchedulerTHelper.waitForEventSchedulerState(SchedulerEvent.RESUMED); assertTrue(schedAdminInterface.pause()); SchedulerTHelper.log("waiting scheduler paused event"); SchedulerTHelper.waitForEventSchedulerState(SchedulerEvent.PAUSED); assertTrue(schedAdminInterface.getStatus().equals(SchedulerStatus.PAUSED)); assertTrue(schedAdminInterface.resume()); SchedulerTHelper.log("waiting scheduler resumed event"); SchedulerTHelper.waitForEventSchedulerState(SchedulerEvent.RESUMED); assertTrue(!schedAdminInterface.start()); SchedulerTHelper.log("waiting scheduler shutting down event"); assertTrue(schedAdminInterface.shutdown()); SchedulerTHelper.waitForEventSchedulerState(SchedulerEvent.SHUTTING_DOWN); SchedulerTHelper.log("waiting scheduler shutted down event"); SchedulerTHelper.waitForEventSchedulerState(SchedulerEvent.SHUTDOWN); } }
/* In a deck of cards, each card has an integer written on it. Return true if and only if you can choose X >= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where: Each group has exactly X cards. All the cards in each group have the same integer. Example 1: Input: deck = [1,2,3,4,4,3,2,1] Output: true Explanation: Possible partition [1,1],[2,2],[3,3],[4,4]. Example 2: Input: deck = [1,1,1,2,2,2,3,3] Output: false´ Explanation: No possible partition. Example 3: Input: deck = [1] Output: false Explanation: No possible partition. Example 4: Input: deck = [1,1] Output: true Explanation: Possible partition [1,1]. Example 5: Input: deck = [1,1,2,2,2,2] Output: true Explanation: Possible partition [1,1],[2,2],[2,2]. */ //Time O(Nlog ^2 N) each gcd operation is Log^2 N Space O(n) class Solution { public boolean hasGroupsSizeX(int[] deck) { int n = deck.length; HashMap<Integer, Integer> map = new HashMap<>(); for(int d : deck){ map.put(d, map.getOrDefault(d, 0) + 1); } int res = 0; for(int val : map.values()){ res = gcd(val, res); } return res > 1; } // find greatest common divisor public int gcd(int a, int b){ return b == 0 ? a : gcd(b, a % b); } }
package game.moves; import tiles.Tile; import tiles.inner.Edge; import tiles.inner.Road; import game.Game; import game.Move; import game.Player; public class Road_Move extends Move { private Tile tile; private Edge edge; private Road road; private Player owner; public Road_Move(){ super(Road.cost,true); } public Road_Move(Road_Move move){ super(move); tile= move.tile; edge= move.edge; road= move.road; owner= move.owner; } public void send(Tile t, Edge e, Road r, Player p) { tile=t; edge=e; road=r; owner=p; super.send(); } public Player apply(Player owner, Game game) { edge.addRoad(road, owner); return owner; } }
package network.nerve.swap.cache; import network.nerve.swap.model.NerveToken; import network.nerve.swap.model.dto.stable.StableSwapPairDTO; import java.util.Collection; /** * @author Niels */ public interface StableSwapPairCache { StableSwapPairDTO get(String address); StableSwapPairDTO put(String address, StableSwapPairDTO dto); StableSwapPairDTO reload(String address); StableSwapPairDTO remove(String address); Collection<StableSwapPairDTO> getList(); boolean isExist(String pairAddress); String getPairAddressByTokenLP(int chainId, NerveToken tokenLP); }
package com.kieferlam.battlelan.game.states; import com.kieferlam.battlelan.settings.InputHandler; import com.kieferlam.battlelan.settings.Settings; import java.util.ArrayList; /** * Created by Kiefer on 22/03/2015. */ public interface State { public void init(Settings settings, long parentWindowId); public void cursorPositionEvent(long windowID, double xpos, double ypos); public void cursorButtonEvent(long windowID, int button, int action, int mods); public void keyEvent(long windowID, int key, int scancode, int action, int mods); public void logic(double delta, double time, InputHandler input); public void render(double delta); public void delete(); }
package windlessstorm.galaxy.merchant; public class GalaxySpeak{ public static enum Type{ ASSIGNMENT, CREDITS, HOWMUCH, HOWMANY, NOMATCH } public class ParseLine { private GalaxySpeak.Type type; private String pattern; public ParseLine(GalaxySpeak.Type type, String pattern) { this.type = type; this.pattern = pattern; } public String getPattern() { return this.pattern; } public GalaxySpeak.Type getType() { return this.type; } } public static String patternAssigned = "^([A-Za-z]+) is ([I|V|X|L|C|D|M])$"; public static String patternCredits = "^([A-Za-z]+)([A-Za-z\\s]*) is ([0-9]+) ([c|C]redits)$"; public static String patternHowMuch = "^how much is (([A-Za-z\\s])+)\\?$"; public static String patternHowMany= "^how many [c|C]redits is (([A-Za-z\\s])+)\\?$"; private ParseLine[] lineparser; public GalaxySpeak() { this.lineparser = new ParseLine[4]; this.lineparser[0] = new ParseLine(GalaxySpeak.Type.ASSIGNMENT, patternAssigned); this.lineparser[1] = new ParseLine(GalaxySpeak.Type.CREDITS, patternCredits); this.lineparser[2] = new ParseLine(GalaxySpeak.Type.HOWMUCH, patternHowMuch); this.lineparser[3] = new ParseLine(GalaxySpeak.Type.HOWMANY, patternHowMany); } public GalaxySpeak.Type getLineType(String line) { line = line.trim(); GalaxySpeak.Type result = Type.NOMATCH; boolean matched = false; for(int i =0;i<lineparser.length && !matched ;i++) { if( line.matches(lineparser[i].getPattern()) ) { matched = true; result = lineparser[i].getType(); } } return result; } }
package com.training.rettiwt.model; import lombok.Getter; import lombok.Setter; import javax.persistence.*; @Getter @Setter @Entity public class Comment extends BaseEntity { @Id @Access(value = AccessType.PROPERTY) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "comment_generator") @SequenceGenerator(name = "comment_generator", sequenceName = "comment_id_seq", allocationSize = 1) private Long id; @Column(length = 350, nullable = false) private String message; @Column(nullable = false) private Integer likes; @Column(nullable = false) private Integer dislikes; @ManyToOne(cascade = CascadeType.ALL, optional = false) @JoinColumn(name = "profile_id") private Profile profile; @ManyToOne(fetch = FetchType.LAZY) private Post post; }
package com.ripple.price.util; /** * Created by Geert Weening (geert@ripple.com) on 2/6/14. */ public class Log { private final static String TAG = "ripple_price"; private static enum Level { DEBUG, INFO, ERROR }; private static void log(Log.Level level, String fmt, Object... args) { // SLOW! String formats are slow, use sparingly String message = String.format("[%s] %s", level, String.format(fmt, args)); switch (level) { case DEBUG: android.util.Log.d(TAG, message); break; case INFO: android.util.Log.i(TAG, message); break; case ERROR: android.util.Log.e(TAG, message); break; } } public static void debug(String fmt, Object... args) { log(Level.DEBUG, fmt, args); } public static void info(String fmt, Object... args) { log(Level.INFO, fmt, args); } public static void error(String fmt, Object... args) { log(Level.ERROR, fmt, args); } public static void debug(Object object) { log(Level.DEBUG, "%s", String.valueOf(object)); } public static void info(Object object) { log(Level.INFO, "%s", String.valueOf(object)); } public static void error(Object object) { log(Level.ERROR, "%s", String.valueOf(object)); } public static void debug(Throwable t) { android.util.Log.d(TAG, "exception", t); } public static void info(Throwable t) { android.util.Log.i(TAG, "exception", t); } public static void error(Throwable t) { android.util.Log.e(TAG, "exception", t); } }
package com.lyl.core.common.code; import lombok.AllArgsConstructor; import lombok.Getter; /** * Created by lyl * Date 2018/12/25 20:21 */ @AllArgsConstructor public final class ReturnCode { @Getter private Integer code; @Getter private String msg; public boolean isSuccess(){ return this.code>=10000 && this.code<20000; } public ReturnCode format(Object... params){ ReturnCode returnCode = new ReturnCode(this.code,this.msg); returnCode.msg=String.format(this.msg,params); return returnCode; } }
import java.time.*; public class Creation { static ZoneId zoneId = ZoneId.of("Pacific/Kiritimati"); public static void main(String[] args) { //LocalDate //Instantiation // LocalDate localDate = new LocalDate(); //The constructor LocalDate() is undefined //public static LocalDate now() LocalDate localDate = LocalDate.now(); System.out.println(localDate); //Prints: 2017-10-30 //public static LocalDate now(ZoneId zone) localDate = LocalDate.now(zoneId); System.out.println(localDate); //Prints: 2017-10-31 //public static LocalDate of(int year, int month, int dayOfMonth) localDate = LocalDate.of(2017, 10, 30); System.out.println(localDate); //Prints: 2017-10-30 // localDate = LocalDate.of(2017, 10, 0); //java.time.DateTimeException: Invalid value for DayOfMonth (valid values 1 - 28/31) // localDate = LocalDate.of(2017, 0, 1); //java.time.DateTimeException: Invalid value for MonthOfYear (valid values 1 - 12) localDate = LocalDate.of(0, 1, 1); System.out.println(localDate); //Prints: 0000-01-01 localDate = LocalDate.of(-1, 1, 1); System.out.println(localDate); //Prints: -0001-01-01 localDate = LocalDate.of(10000, 1, 1); System.out.println(localDate); //Prints: +10000-01-01 // localDate = LocalDate.of(2020, 2, 30); //Exception in thread "main" java.time.DateTimeException: Invalid date 'FEBRUARY 30' localDate = LocalDate.of(2020, 2, 29); System.out.println(localDate); //Prints: 2020-02-29 // localDate = LocalDate.of(2021, 2, 29); //Exception in thread "main" java.time.DateTimeException: Invalid date 'February 29' as '2021' is not a leap year localDate = LocalDate.of(2021, 2, 28); System.out.println(localDate); //Prints: 2020-02-28 //public static LocalDate of(int year, Month month, int dayOfMonth) localDate = LocalDate.of(2017, Month.OCTOBER, 30); System.out.println(localDate); //Prints: 2017-10-30 //LocalTime //Instantiation // LocalTime localTime = new LocalTime(); //2017-10-30T13:15:20.999999999 //public static LocalTime now() LocalTime localTime = LocalTime.now(); System.out.println(localTime); //Prints: 15:06:09.832 localTime = LocalTime.now(zoneId) ; System.out.println(localTime); //Prints: 01:06:09.832 //static LocalTime of(int hour, int minute) localTime = LocalTime.of(13, 15); System.out.println(localTime); //Prints: 13:15 // localTime = LocalTime.of(24, 15); //Exception in thread "main" java.time.DateTimeException: Invalid value for HourOfDay (valid values 0 - 23) // localTime = LocalTime.of(13, 60); //Exception in thread "main" java.time.DateTimeException: Invalid value for MinuteOfHour (valid values 0 - 59) //static LocalTime of(int hour, int minute, int second) localTime = LocalTime.of(13, 15, 20); System.out.println(localTime); //Prints: 13:15:20 //static LocalTime of(int hour, int minute, int second, int nanoOfSecond) localTime = LocalTime.of(13, 15, 20, 400000000); System.out.println(localTime); //Prints: 13:15:20.400 localTime = LocalTime.of(13, 15, 20, 400500000); System.out.println(localTime); //Prints: 13:15:20.400500 localTime = LocalTime.of(13, 15, 20, 400500600); System.out.println(localTime); //Prints: 13:15:20.400500600 // localTime = LocalTime.of(13, 15, 20, 1000000000); //Exception in thread "main" java.time.DateTimeException: Invalid value for NanoOfSecond (valid values 0 - 999999999) localTime = LocalTime.of(13, 15, 20, 999999999); System.out.println(localTime); //Prints: 13:15:20.999999999 //LocalDateTime //Instantiation // LocalDateTime localDateTime = new LocalDateTime(); //2017-10-30T13:15:20.999999999 //static LocalDateTime now() LocalDateTime localDateTime = LocalDateTime.now(); System.out.println(localDateTime); //Prints: 2017-10-30T15:17:40.296 //static LocalDateTime now(ZoneId zone) localDateTime = LocalDateTime.now(zoneId); System.out.println(localDateTime); //Prints: 2017-10-31T01:19:25.581 //static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute) localDateTime = LocalDateTime.of(2017, 10, 30, 16, 10); System.out.println(localDateTime); //Prints: 2017-10-30T16:10 //static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second) localDateTime = LocalDateTime.of(2017, 10, 30, 16, 10, 20); System.out.println(localDateTime); //2017-10-30T16:10:20 //static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond) localDateTime = LocalDateTime.of(2017, 10, 30, 16, 10, 20, 400000000); System.out.println(localDateTime); //2017-10-30T16:10:20.400 localDateTime = LocalDateTime.of(2017, 10, 30, 16, 10, 20, 999999999); System.out.println(localDateTime); //2017-10-30T16:10:20.999999999 //static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute) localDateTime = LocalDateTime.of(2017, Month.OCTOBER, 30, 16, 10); System.out.println(localDateTime); //Prints: 2017-10-30T16:10 //static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second) localDateTime = LocalDateTime.of(2017, Month.OCTOBER, 30, 16, 10, 20); System.out.println(localDateTime); //2017-10-30T16:10:20 //static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond) localDateTime = LocalDateTime.of(2017, Month.OCTOBER, 30, 16, 10, 20, 400000000); System.out.println(localDateTime); //2017-10-30T16:10:20.400 //static LocalDateTime of(LocalDate date, LocalTime time) System.out.println(localDate); //Prints: 2017-10-30 System.out.println(localTime); //Prints: 13:15:20.999999999 localDateTime = LocalDateTime.of(localDate, localTime); System.out.println(localDateTime); //Prints: 2017-10-30T13:15:20.999999999 //ZonedDateTime //Instantiation // ZonedDateTime zonedDateTime = new ZonedDateTime(); //2017-10-30T13:15:20.999999999 //static ZonedDateTime now() ZonedDateTime zonedDateTime = ZonedDateTime.now(); System.out.println(zonedDateTime); //2017-10-30T16:18:08.406+04:00[Asia/Muscat] //static ZonedDateTime now(ZoneId zone) zonedDateTime = ZonedDateTime.now(zoneId); System.out.println(zonedDateTime); //2017-10-31T02:19:49.455+14:00[Pacific/Kiritimati] //static ZonedDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond, ZoneId zone) zonedDateTime = ZonedDateTime.of(2017, 10, 30, 16, 22, 0, 0, zoneId); System.out.println(zonedDateTime); //Prints: 2017-10-30T16:22+14:00[Pacific/Kiritimati] zonedDateTime = ZonedDateTime.of(2017, 10, 30, 16, 22, 15, 0, zoneId); System.out.println(zonedDateTime); //Prints: 2017-10-30T16:22:15+14:00[Pacific/Kiritimati] zonedDateTime = ZonedDateTime.of(2017, 10, 30, 16, 22, 15, 400000000, zoneId); System.out.println(zonedDateTime); //Prints: 2017-10-30T16:22:15.400+14:00[Pacific/Kiritimati] zonedDateTime = ZonedDateTime.of(2017, 10, 30, 16, 22, 15, 999999999, zoneId); System.out.println(zonedDateTime); //Prints: 2017-10-30T16:22:15.999999999+14:00[Pacific/Kiritimati] //static ZonedDateTime of(LocalDate date, LocalTime time, ZoneId zone) System.out.println(localDate); //Prints: 2017-10-30 System.out.println(localTime); //Prints: 13:15:20.999999999 zonedDateTime = ZonedDateTime.of(localDate, localTime, zoneId); System.out.println(zonedDateTime); //Prints: 2017-10-30T13:15:20.999999999+14:00[Pacific/Kiritimati] //static ZonedDateTime of(LocalDateTime localDateTime, ZoneId zone) System.out.println(localDateTime); //Prints: 2017-10-30T13:15:20.999999999 zonedDateTime = ZonedDateTime.of(localDateTime, zoneId); System.out.println(zonedDateTime); //Prints: 2017-10-30T13:15:20.999999999+14:00[Pacific/Kiritimati] } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.jmx.export.naming; import java.util.Hashtable; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import org.springframework.aop.support.AopUtils; import org.springframework.beans.factory.InitializingBean; import org.springframework.jmx.export.metadata.JmxAttributeSource; import org.springframework.jmx.export.metadata.ManagedResource; import org.springframework.jmx.support.ObjectNameManager; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; /** * An implementation of the {@link ObjectNamingStrategy} interface * that reads the {@code ObjectName} from the source-level metadata. * Falls back to the bean key (bean name) if no {@code ObjectName} * can be found in source-level metadata. * * <p>Uses the {@link JmxAttributeSource} strategy interface, so that * metadata can be read using any supported implementation. Out of the box, * {@link org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource} * introspects a well-defined set of annotations that come with Spring. * * @author Rob Harrop * @author Juergen Hoeller * @since 1.2 * @see ObjectNamingStrategy * @see org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource */ public class MetadataNamingStrategy implements ObjectNamingStrategy, InitializingBean { /** * The {@code JmxAttributeSource} implementation to use for reading metadata. */ @Nullable private JmxAttributeSource attributeSource; @Nullable private String defaultDomain; /** * Create a new {@code MetadataNamingStrategy} which needs to be * configured through the {@link #setAttributeSource} method. */ public MetadataNamingStrategy() { } /** * Create a new {@code MetadataNamingStrategy} for the given * {@code JmxAttributeSource}. * @param attributeSource the JmxAttributeSource to use */ public MetadataNamingStrategy(JmxAttributeSource attributeSource) { Assert.notNull(attributeSource, "JmxAttributeSource must not be null"); this.attributeSource = attributeSource; } /** * Set the implementation of the {@code JmxAttributeSource} interface to use * when reading the source-level metadata. */ public void setAttributeSource(JmxAttributeSource attributeSource) { Assert.notNull(attributeSource, "JmxAttributeSource must not be null"); this.attributeSource = attributeSource; } /** * Specify the default domain to be used for generating ObjectNames * when no source-level metadata has been specified. * <p>The default is to use the domain specified in the bean name * (if the bean name follows the JMX ObjectName syntax); else, * the package name of the managed bean class. */ public void setDefaultDomain(String defaultDomain) { this.defaultDomain = defaultDomain; } @Override public void afterPropertiesSet() { if (this.attributeSource == null) { throw new IllegalArgumentException("Property 'attributeSource' is required"); } } /** * Reads the {@code ObjectName} from the source-level metadata associated * with the managed resource's {@code Class}. */ @Override public ObjectName getObjectName(Object managedBean, @Nullable String beanKey) throws MalformedObjectNameException { Assert.state(this.attributeSource != null, "No JmxAttributeSource set"); Class<?> managedClass = AopUtils.getTargetClass(managedBean); ManagedResource mr = this.attributeSource.getManagedResource(managedClass); // Check that an object name has been specified. if (mr != null && StringUtils.hasText(mr.getObjectName())) { return ObjectNameManager.getInstance(mr.getObjectName()); } else { Assert.state(beanKey != null, "No ManagedResource attribute and no bean key specified"); try { return ObjectNameManager.getInstance(beanKey); } catch (MalformedObjectNameException ex) { String domain = this.defaultDomain; if (domain == null) { domain = ClassUtils.getPackageName(managedClass); } Hashtable<String, String> properties = new Hashtable<>(); properties.put("type", ClassUtils.getShortName(managedClass)); properties.put("name", beanKey); return ObjectNameManager.getInstance(domain, properties); } } } }
package com.wenyuankeji.spring.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.wenyuankeji.spring.dao.IBaseSuggestionDao; import com.wenyuankeji.spring.model.BaseSuggestionModel; import com.wenyuankeji.spring.service.IBaseSuggestionService; import com.wenyuankeji.spring.util.BaseException; @Service public class BaseSuggestionServiceImpl implements IBaseSuggestionService{ @Autowired private IBaseSuggestionDao baseSuggestionDao; @Override public BaseSuggestionModel searchBaseSuggestion(int sid) throws BaseException { return baseSuggestionDao.searchBaseSuggestion(sid); } @Override public List<BaseSuggestionModel> searchBaseSuggestion(String startTime, String endTime, int page, int rows) throws BaseException { return baseSuggestionDao.searchBaseSuggestion(startTime, endTime, page, rows); } @Override public int searchBaseSuggestionCount(String startTime, String endTime) throws BaseException { return baseSuggestionDao.searchBaseSuggestionCount(startTime, endTime); } }
package com.dbs.db.dao; import java.sql.SQLException; import java.util.List; import com.dbs.db.filter.Criteria; public interface IGenericDao<T> { public List<T> getAll(); public boolean create(T bean); public boolean update(T bean) throws Exception; public boolean delete(T bean) throws Exception; public boolean deleteAll(); public List<T> findByCriteria(Criteria criteria); public void commit() throws SQLException; public void rollback() throws SQLException; }
package com.vividare.HelperClasses; import android.util.Log; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ConstantFunctions { public static String getratingRandomId() { String assignmentId = ""; int max = 999999999; int min = 1; int random = (int )(Math.random() * max + min); String timeStemp = String.valueOf(System.currentTimeMillis()); return assignmentId = timeStemp+"_"+String.valueOf(random); //return assignmentId = String.valueOf(random); } public static String getratingRandom2Digit() { String assignmentId = ""; int max = 99; int min = 1; int random = (int )(Math.random() * max + min); return assignmentId = String.valueOf(random); //return assignmentId = String.valueOf(random); } public static boolean emailValidator(final String mailAddress) { Pattern pattern; Matcher matcher; final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; pattern = Pattern.compile(EMAIL_PATTERN); matcher = pattern.matcher(mailAddress); return matcher.matches(); } public static String verficationRandom() { String rnadom = ""; int max = 9999; int min = 1; int random = (int )(Math.random() * max + min); return rnadom = String.valueOf(random); } public static long daysBetween(String startDate, String endDate) { final SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy"); final Date date1; final Date date2; Calendar calendar1 = Calendar.getInstance(); Calendar calendar2 = Calendar.getInstance(); try { date1 = format.parse(startDate); calendar1.setTime(date1); calendar1.add(Calendar.DAY_OF_YEAR, 1); date2 = format.parse(endDate); calendar2.setTime(date2); calendar2.add(Calendar.DAY_OF_YEAR, 1); } catch (ParseException e) { e.printStackTrace(); } long end = calendar1.getTimeInMillis(); long start = calendar2.getTimeInMillis(); return TimeUnit.MILLISECONDS.toDays(Math.abs(end - start)); } public static String currentDate() { Date currentDate = Calendar.getInstance().getTime(); String myFormat = "dd-MMM-yyyy"; //In which you need put here SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.ENGLISH); String mCurrentDate = sdf.format(currentDate); return mCurrentDate; } public static String currentTime() { long timeStemp = System.currentTimeMillis(); String currentTime = android.text.format.DateFormat.format("hh:mm a", new Date(timeStemp)).toString(); return currentTime; } public static String currenttimeStemp() { long timeStemp = System.currentTimeMillis(); return String.valueOf(timeStemp); } public static String dateTimeToTimeStemp(String sDate, String sTime) { String resultTimeStemp = ""; Date date = null; try { String dateAndTime = sDate+" "+sTime; java.text.DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy hh:mm a"); date = (Date)formatter.parse(dateAndTime); Log.e("TAg", "the time Stemp is here " + date.getTime()); } catch (ParseException e) { e.printStackTrace(); } return String.valueOf(date.getTime()); } public static String formatCurrency(String amount) { DecimalFormat formatter = new DecimalFormat("###,###,##0.0"); return formatter.format(Double.parseDouble(amount)); } public static double round(double value, int places) { if (places < 0) throw new IllegalArgumentException(); long factor = (long) Math.pow(10, places); value = value * factor; long tmp = Math.round(value); return (double) tmp / factor; } }
package com.example.vmac.myrobot.oog; import android.util.Log; import com.ibm.watson.developer_cloud.android.library.audio.AudioConsumer; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; /** * Created by Administrator on 2017/12/9. */ public class InputStreamToFileOgg implements AudioConsumer { public final static String TAG=InputStreamToFileOgg.class.getSimpleName(); File toFile; FileOutputStream fileOutputStream; public InputStreamToFileOgg(InputStream inputStream,int lenth,int bufferSize,File parent){ byte[] buffer=new byte[bufferSize]; int r=0; int seek=0; try { toFile=new File(parent,System.currentTimeMillis()+".ogg"); toFile.createNewFile(); fileOutputStream=new FileOutputStream(toFile); while((r = inputStream.read(buffer,0,bufferSize))>0&&(seek<lenth)){ seek+=r;//记录读取的长度 } } catch (Exception e) { e.printStackTrace(); Log.i(TAG,"****读取报错"+e.getMessage()); } } @Override public void consume(byte[] data, double amplitude, double volume) { } @Override public void consume(byte[] data) { } }
public class Platinum implements Membership { private static Platinum instance = new Platinum(); public static Platinum getInstance() { return instance; } @Override public double getDiscount() { return 0.85; } public String toString() { return "Platinum"; } }
package com.example.instilingo; import java.util.Hashtable; import java.util.Map; import android.app.SearchManager; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.widget.TextView; public class SearchActivity extends BaseActivity { TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.search_view); textView = (TextView) findViewById(R.id.tv1); Intent intent = getIntent(); handleIntent(intent); } @Override protected void onNewIntent(Intent intent) { // TODO Auto-generated method stub super.onNewIntent(intent); setIntent(intent); handleIntent(intent); } private void handleIntent(Intent intent){ Map<String,String> map = new Hashtable<String,String>(); map.put("alak","Alakananda hostel"); map.put("alakite","Resident of Alakananda hostel"); map.put("app","to apply"); map.put("arb","arbitray ,random"); map.put("bog","bathroom"); String result = "no such word \nif you are using voice search try typing it"; if (Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.QUERY); Log.i("search","query="+query); String str = map.get(query.toLowerCase()); if(str!=null) { result = ""+str; } } else { String query2 = intent.getExtras().getString("word"); Log.i("search","query="+query2); String str = map.get(query2); if(str!=null) { result = ""+str; } } textView.setText(result); } }
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; gaiclass lab2 { private void print(String orgStr, String cmpStr, int toffset, int ooffset, int len) { String toShow = ""; if (toffset < 0) toShow+="toffset < 0 \n"; else toShow+="toffset >= 0 \n"; if (ooffset < 0) toShow+="oofset < 0 \n"; else toShow+="offset >= 0 \n"; if ((toffset <= (long) orgStr.length()-len)) toShow+="toffset <= (long)value.length - len\n"; else toShow+="toffset > (long)value.length - len\n"; if((ooffset <= (long)cmpStr.length() - len)) toShow+="offset <= (long)other.value.length - len\n"; else toShow+="offset > (long)other.value.length - len\n"; System.out.println(toShow); } @Test public void case11() { String s = "Welcome to Java"; StringBuffer cs = new StringBuffer(("Welcome to Java")); assertEquals(true, s.contentEquals(cs)); } @Test public void case12() { String s = "Welcome to Java"; StringBuilder cs = new StringBuilder("Welcome to Java"); assertEquals(true,s.contentEquals(cs)); } @Test public void case13() { String s = "Welcome to Java"; String cs = new String("Welcome to Java"); assertEquals (true, s.contentEquals(cs)); } @Test public void case14() { String s = "Welcome to Java"; CharSequence cs = new myCharSequence("Welcome to Java"); assertEquals(true, s.contentEquals(cs)); } @Test public void case15() { String s = "Welcome to Java"; CharSequence cs = new myCharSequence("Welcome"); assertEquals(false, s.contentEquals(cs)); } @Test public void case16() { String s = "Welcome to Java"; CharSequence cs = new myCharSequence("Welcome to Jjaa"); assertEquals(false, s.contentEquals(cs)); } @Test public void case21() { String orgStr = "Welcome to Java"; String cmpStr = "Welcome to Java"; int toffset = -1; int ooffse = -1; int len = 20; this.print(orgStr, cmpStr, toffset, ooffse, len); assertFalse(orgStr.regionMatches(-1,"Welcome to Java", -1, 5)); } @Test public void case22() { String orgStr = "Welcome to Java"; String cmpStr = "Welcome"; int toffset = -1; int ooffse = -1; int len = 15; this.print(orgStr, cmpStr, toffset, ooffse, len); assertFalse(orgStr.regionMatches(toffset, cmpStr, ooffse, len)); } @Test public void case23() { String orgStr = "Welcome"; String cmpStr = "Welcome to Java"; int toffset = -1; int ooffse = -1; int len = 15; this.print(orgStr, cmpStr, toffset, ooffse, len); assertFalse(orgStr.regionMatches(toffset, cmpStr, ooffse, len)); } @Test public void case24() { String orgStr = "Welcome to Java"; String cmpStr = "Welcome to Java"; int toffset = -10; int ooffse = -10; int len = 15; this.print(orgStr, cmpStr, toffset, ooffse, len); assertFalse(orgStr.regionMatches(toffset, cmpStr, ooffse, len)); } @Test public void case25() { String orgStr = "Welcome to Java"; String cmpStr = "Welcome"; int toffset = 0; int ooffse = -1; int len = 15; this.print(orgStr, cmpStr, toffset, ooffse, len); assertFalse(orgStr.regionMatches(toffset, cmpStr, ooffse, len)); } @Test public void case26() { String orgStr = "Welcome to Java"; String cmpStr = "Welcome"; int toffset = 0; int ooffse = 20; int len = 15; this.print(orgStr, cmpStr, toffset, ooffse, len); assertFalse(orgStr.regionMatches(toffset, cmpStr, ooffse, len)); } @Test public void case27() { String orgStr = "Welcome to Java"; String cmpStr = "Welcome"; int toffset = 0; int ooffse = 1; int len = 8; this.print(orgStr, cmpStr, toffset, ooffse, len); assertFalse(orgStr.regionMatches(toffset, cmpStr, ooffse, len)); } @Test public void case28() { String orgStr = "Welcome to Java"; String cmpStr = "Welcome"; int toffset = 0; int ooffse = 1; int len = 8; this.print(orgStr, cmpStr, toffset, ooffse, len); assertFalse(orgStr.regionMatches(toffset, cmpStr, ooffse, len)); } @Test public void case29() { String orgStr = "Welcome to Java"; String cmpStr = "Welcome"; int toffset = -1; int ooffse = 10; int len = 8; this.print(orgStr, cmpStr, toffset, ooffse, len); assertFalse(orgStr.regionMatches(toffset, cmpStr, ooffse, len)); } @Test public void case30() { String orgStr = "Welcome to Java"; String cmpStr = "Welcome to Java Java"; int toffset = -1; int ooffse = 0; int len = 13; this.print(orgStr, cmpStr, toffset, ooffse, len); assertFalse(orgStr.regionMatches(toffset, cmpStr, ooffse, len)); } @Test public void case31() { String orgStr = "Welcome to Java"; String cmpStr = "Welcome"; int toffset = -20; int ooffse = 0; int len = 13; this.print(orgStr, cmpStr, toffset, ooffse, len); assertFalse(orgStr.regionMatches(toffset, cmpStr, ooffse, len)); } @Test public void case32() { String orgStr = "Welcome to Java"; String cmpStr = "Welcome"; int toffset = -1; int ooffse = 0; int len = 1; this.print(orgStr, cmpStr, toffset, ooffse, len); assertFalse(orgStr.regionMatches(toffset, cmpStr, ooffse, len)); } @Test public void case34() { String orgStr = "Welcome to Java"; String cmpStr = "Welcome"; int toffset = 8; int ooffse = 0; int len = 4; this.print(orgStr, cmpStr, toffset, ooffse, len); assertFalse(orgStr.regionMatches(toffset, cmpStr, ooffse, len)); } @Test public void case33() { String orgStr = "Welcome to Java"; String cmpStr = "Welcome"; int toffset = 8; int ooffse = 0; int len = 20; this.print(orgStr, cmpStr, toffset, ooffse, len); assertFalse(orgStr.regionMatches(toffset, cmpStr, ooffse, len)); } @Test public void case35() { String orgStr = "Welcome to Java"; String cmpStr = "Welcome"; int toffset = 0; int ooffse = 0; int len = 8; this.print(orgStr, cmpStr, toffset, ooffse, len); assertFalse(orgStr.regionMatches(toffset, cmpStr, ooffse, len)); } @Test public void case36() { String orgStr = "Welcome to Java"; String cmpStr = "Welcome to Java"; int toffset = 0; int ooffse = 0; int len = 8; this.print(orgStr, cmpStr, toffset, ooffse, len); assertTrue(orgStr.regionMatches(toffset, cmpStr, ooffse, len)); } @Test public void case3_1() { assertFalse("Welcome".startsWith("Welcome to Java", -1)); } @Test public void case3_2() { assertFalse("Welcome to Java".startsWith("Welcome", -1)); } @Test public void case3_3() { assertFalse("Welcome to Java".startsWith("Welcome", 8)); } @Test public void case3_4() { assertFalse("Welcome to Java".startsWith("Welcome to C++", 0)); } @Test public void case3_5() { assertTrue("Welcome to Java".startsWith("Welcome", 0)); } @Test // H public void case4_1() { StringBuilder s = new StringBuilder("Welcome to Java"); System.out.println(s.indexOf("",30)); assertEquals(15, s.indexOf("",30)); } @Test // I public void case4_2() { StringBuilder s = new StringBuilder("Welcome to Java"); assertEquals(0, s.indexOf("",-1)); System.out.println(s.indexOf("",-1)); } @Test // G public void case4_3() { StringBuilder s = new StringBuilder("Welcome to Java"); assertEquals(11, s.indexOf("Java",-1)); System.out.println(s.indexOf("Java",-1)); } @Test // A public void case4_4() { StringBuilder s = new StringBuilder("Welcome to Java"); assertEquals(-1, s.indexOf("Welcome to Java",5)); } @Test // B public void case4_5() { StringBuilder s = new StringBuilder("Welcome to Java"); assertEquals(-1, s.indexOf("Welcome to Java and Python",5)); } @Test // F public void case4_6() { StringBuilder s = new StringBuilder("欢迎 to Java"); System.out.println(s.indexOf("Welcome to Java",0)); assertEquals(-1, s.indexOf("Welcome to Java",0)); } @Test // E public void case4_7() { StringBuilder s = new StringBuilder("Welcome to Java"); System.out.println(s.indexOf("欢迎",0)); assertEquals(0, s.indexOf("Welcome to Java",0)); } @Test // D public void case4_8() { StringBuilder s = new StringBuilder("欢迎 to Java"); System.out.println(s.indexOf("欢迎",0)); assertEquals(0, s.indexOf("欢迎",0)); } @Test // C public void case4_9() { StringBuilder s = new StringBuilder("Welcome to Java"); System.out.println(s.indexOf("Java",0)); assertEquals(11, s.indexOf("Java",0)); } @Test public void case5_1() { final String[] strs = "aaaobbboccc".split("o", 2); //assertAll(()->assertTrue("aaa".equals(strs[0]))); assertAll(()->assertTrue("aaa".equals(strs[0])), ()->assertTrue("bbboccc".equals(strs[1]))); } @Test public void case5_2() { String[] strs = "aaaobbboccc".split("o",3); assertAll(()->assertTrue("aaa".equals(strs[0])), ()->assertTrue("bbb".equals(strs[1])), ()->assertTrue("ccc".equals(strs[2]))); } @Test public void case5_3() { String[] strs = "aaaobbboccc".split("k", 0); assertAll(()->assertTrue("aaaobbboccc".equals(strs[0]))); } @Test public void case5_4() { String[] strs = "aaaobbboccco".split("o", 0); assertAll(()->assertTrue(3==strs.length), ()->assertTrue("aaa".equals(strs[0])), ()->assertTrue("bbb".equals(strs[1])), ()->assertTrue("ccc".equals(strs[2])) ); } @Test public void case5_5() { String[] strs = "aaaoobbbooccc".split("oo", 0); assertAll(()->assertTrue(3==strs.length), ()->assertTrue("aaa".equals(strs[0])), ()->assertTrue("bbb".equals(strs[1])), ()->assertTrue("ccc".equals(strs[2])) ); } } class myCharSequence implements CharSequence { public myCharSequence(String str) { this.value = str.toCharArray(); } private char[] value; public int length() { return value.length; } public char charAt(int index) { return this.value[index]; } public CharSequence subSequence(int start, int end) { return new myCharSequence(new String(value).substring(start, end + 1)); } }
package io.jrevolt.sysmon.jms; import javax.jms.JMSException; import javax.jms.Message; import java.net.InetAddress; import java.net.UnknownHostException; /** * @author <a href="mailto:patrikbeno@gmail.com">Patrik Beno</a> */ public class JmsContext { static private ThreadLocal<JmsContext> tlJmsContext = new ThreadLocal<>(); static public JmsContext jmsContext() { return tlJmsContext.get(); } static public void withJmsContext(Message message, Runnable runnable) { try { tlJmsContext.set(new JmsContext(message)); runnable.run(); } finally { tlJmsContext.remove(); } } Message message; InetAddress server; public JmsContext(Message message) { try { this.message = message; this.server = InetAddress.getByName(message.getStringProperty("server")); } catch (Exception e) { throw new UnsupportedOperationException(e); } } public Message getMessage() { return message; } public InetAddress getServer() { return server; } }
package kr.ac.kopo.day07.homework; public class IcecreamMain { public static void main(String[] args) { IcecreamMarket m = new IcecreamMarket(); m.info(); } }
package ortigiaenterprises.platerecognizer; import android.graphics.Bitmap; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import ortigiaenterprises.platerecognizer.sqlDb.MyDBHandler; /** * Created by Iolanda on 25/07/2016. */ public class ModificaDbActivity extends AppCompatActivity { //resultdb dovrebbe essere passato come parametro al click del bottone Modifica private MyDBHandler dbHandler; private EditText Operatoretext; private EditText Surveytext; private EditText LunghezzaMaxtext; private EditText LunghezzaMintext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mod_db); dbHandler = MyDBHandler.getInstance(getBaseContext()); Object[] parameters = dbHandler.getParameters(); Operatoretext=(EditText) findViewById(R.id.operatoreId); Surveytext=(EditText) findViewById(R.id.surveyId); LunghezzaMaxtext=(EditText) findViewById(R.id.maxTarga); LunghezzaMintext=(EditText) findViewById(R.id.minTarga); String Operatore=(String) parameters[0]; Operatoretext.setText(Operatore); String Survey=(String) parameters[1]; Surveytext.setText(Survey); int LunghezzaMin= (int) parameters[2]; LunghezzaMintext.setText(Integer.toString(LunghezzaMin)); int LunghezzaMax= (int) parameters[3]; LunghezzaMaxtext.setText(Integer.toString(LunghezzaMax)); Button b2 = (Button) findViewById(R.id.button); b2.setOnClickListener(new View.OnClickListener(){ @Override //On click function public void onClick(View view) { String newOperatore=Operatoretext.getText().toString(); String newSurvey=Surveytext.getText().toString(); int newmax=Integer.parseInt(LunghezzaMaxtext.getText().toString()); int newmin=Integer.parseInt(LunghezzaMintext.getText().toString()); dbHandler.updateParametri(newOperatore,newSurvey,newmin,newmax); Toast.makeText(getBaseContext(),"Modifiche effettuate con successo!", Toast.LENGTH_SHORT).show(); } }); } }
package com.manoharacademy.corejava.fundamentals.scope; public class ScopeOfVariable { public static void main(String[] args) { int i1 = 2; //we can not use the value of un-initialized variable //we can not create duplicate variable in same scope //method parameters are in scope inside method body { int i2; //you can nest blocks inside blocks } //a vairable declared inside a inner block is not visible outside in outer block { //we can not create duplicate variable inside inner block } //Just like method input parameters, for loop initialized parameters are visible //inside for loop, but not outside for block //parameters defined inside do block are not visible in while expression //paramters defined inside try block are not visible in catch and finally blocks } //editbox plugin for eclipse //BlueJ editor }
package proghf.model; import org.junit.Test; import static org.junit.Assert.*; public class LabelTest { @Test public void getName() { var label = new Label("test"); assertEquals("test", label.getName()); } @Test public void setName() { var label = new Label("invalid"); label.setName("test"); assertEquals("test", label.getName()); } @Test public void nameProperty() { var label = new Label("test"); var property = label.nameProperty(); assertEquals("test", property.get()); } @Test public void labelEquals() { var label1 = new Label("test"); var label2 = new Label("test"); var label3 = new Label("other"); assertEquals(label1, label2); assertEquals(label2, label1); assertNotEquals(label1, label3); assertNotEquals(null, label1); assertNotEquals(new Object(), label1); } @Test public void labelHashCode() { var label1 = new Label("test"); var label2 = new Label("test"); var label3 = new Label("other"); assertEquals(label1.hashCode(), label2.hashCode()); assertEquals(label2.hashCode(), label1.hashCode()); assertNotEquals(label1.hashCode(), label3.hashCode()); } }
package oops; public class Absatraction { static int a=12; void Absatraction() { System.out.println(a); } public static void main(String[] args) { Absatraction obj=new Absatraction(); //vijay v=new vijay(); //vishal vi=new vishal(); // Ramesh r=new Suresh(); // r.age(); //s r.gender(); // r.name(); } }
package com.barclaycard.currency.exception; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.ModelAndView; @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public ModelAndView handleException(Exception ex){ ModelAndView modelAndView = new ModelAndView("errorPage"); modelAndView.addObject("errorMessage", "Something went wrong, please try after some time"); return modelAndView; } }
package edu.zhoutt.mall.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.math.BigDecimal; import java.util.Date; @Data @NoArgsConstructor @AllArgsConstructor public class Product { private Long id; private String name; private String image; private BigDecimal price; private String description; // 是否已下架 0:未下架, 1:已下架 private Integer isDown; // 总数量 private Long total; private Long sell; // 分类Id private Long categoryId; private Date createTime; private Date updateTime; }
package com.gaoshin.appbooster.dao; import java.util.List; import com.gaoshin.appbooster.bean.ApplicationDetailsList; import com.gaoshin.appbooster.bean.RewardDetails; import com.gaoshin.appbooster.bean.RewardDetailsList; import com.gaoshin.appbooster.bean.UserDetails; import com.gaoshin.appbooster.entity.Application; import com.gaoshin.appbooster.entity.ApplicationType; public interface PublisherDao extends GenericDao { Application getApplication(ApplicationType type, String marketId); List<Application> listUserApplications(String userId); UserDetails getUserDetails(String userId); ApplicationDetailsList latestApplications(int size); RewardDetailsList latestRewards(int size); RewardDetails getRewardDetails(String rewardId); }
package common.elements.interfaces; import common.elements.interfaces.base.IBaseWebElement; public interface IButton extends IBaseWebElement<IButton> { void click() throws Exception; }
package ma.adria.banque.entities; import java.io.Serializable; import java.util.Collection; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import org.codehaus.jackson.annotate.JsonIgnore; /** * cette classe représente un béneficiaire prise en charge par un abonné de la banque * @author ouakrim * @since 02/2016 * @version 1.0.0 */ @Entity @Table (name="Benificiaire") public class Beneficiaire implements Serializable{ private static final long serialVersionUID = 1L; /*=====================================================================================*/ /* ATTRIBUES DE LA CLASSE */ /*=====================================================================================*/ @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id_beneficiaire") private long id; private String prenom; private String nom; private String numeroCompte; @JsonIgnore @ManyToOne(fetch = FetchType.LAZY) private Abonne abonne ; @JsonIgnore @OneToMany(mappedBy = "beneficiaire") private Collection<VirementMultipleBeneficiaire> virementMultipleBeneficiaires; /*=====================================================================================*/ /* CONSTRUCTEURS */ /*=====================================================================================*/ public Beneficiaire() { super(); } public Beneficiaire( String prenom, String nom, String numeroCompte, Abonne abonne, Collection<VirementMultipleBeneficiaire> virementMultipleBeneficiaires) { super(); this.prenom = prenom; this.nom = nom; this.numeroCompte = numeroCompte; this.abonne = abonne; this.virementMultipleBeneficiaires = virementMultipleBeneficiaires; } /*=====================================================================================*/ /* GETTERS & SETTERS */ /*=====================================================================================*/ public long getId() { return id; } public void setId(long id) { this.id = id; } public String getPrenom() { return prenom; } public void setPrenom(String prenom) { this.prenom = prenom; } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } public String getNumeroCompte() { return numeroCompte; } public void setNumeroCompte(String numeroCompte) { this.numeroCompte = numeroCompte; } public Abonne getAbonne() { return abonne; } public void setAbonne(Abonne abonne) { this.abonne = abonne; } public Collection<VirementMultipleBeneficiaire> getVirementMultipleBeneficiaires() { return virementMultipleBeneficiaires; } public void setVirementMultipleBeneficiaires( Collection<VirementMultipleBeneficiaire> virementMultipleBeneficiaires) { this.virementMultipleBeneficiaires = virementMultipleBeneficiaires; } }
package br.mpac.controller; import java.io.IOException; import java.util.List; import javax.enterprise.context.RequestScoped; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.Query; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import br.mpac.entidade.Usuario; import br.mpac.util.MensagemUtil; @Named @RequestScoped public class LoginController { @Inject private EntityManager em; private String login; private String senha; public void efetuarLogin() throws IOException{ HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest(); HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse(); String login = request.getParameter("login"); String senha = request.getParameter("senha"); Query q = em.createQuery("SELECT u FROM Usuario u WHERE login = '" + login + "'"); List<Usuario> encontrados = q.getResultList(); if (encontrados.size() > 0) { Usuario user = encontrados.get(0); if(validacao(user, senha)){ HttpSession session = request.getSession(); session.setAttribute("authUser", user); response.sendRedirect("index.xhtml"); }else{ MensagemUtil.mensagemError("A senha está incorreta"); } } else { MensagemUtil.mensagemError("O usuário não está cadastrado!"); } } private boolean validacao(Usuario user1, String senha){ return user1.getSenha().equals(senha); } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } }
package network.nerve.swap.model.dto; import io.nuls.core.rpc.model.ApiModel; /** * @author Niels */ @ApiModel(name = "Farm信息详情") public class FarmInfoVO { private String farmHash; private int stakeTokenChainId; private int stakeTokenAssetId; private int syrupTokenChainId; private int syrupTokenAssetId; private String syrupPerBlock;//每个区块奖励的糖果数量 private long startBlockHeight;//开始计算奖励的高度 private long lockedTime;//锁定时间,在此时间之前不解锁 private String creatorAddress; private String accSyrupPerShare;//累计每股可分到的奖励数量 private String syrupTokenBalance; private String stakeTokenBalance; private String totalSyrupAmount; private boolean modifiable; //0不可以修改,1可以修改 private long withdrawLockTime; private long stopHeight; public long getStopHeight() { return stopHeight; } public void setStopHeight(long stopHeight) { this.stopHeight = stopHeight; } public String getFarmHash() { return farmHash; } public void setFarmHash(String farmHash) { this.farmHash = farmHash; } public int getStakeTokenChainId() { return stakeTokenChainId; } public void setStakeTokenChainId(int stakeTokenChainId) { this.stakeTokenChainId = stakeTokenChainId; } public int getStakeTokenAssetId() { return stakeTokenAssetId; } public void setStakeTokenAssetId(int stakeTokenAssetId) { this.stakeTokenAssetId = stakeTokenAssetId; } public int getSyrupTokenChainId() { return syrupTokenChainId; } public void setSyrupTokenChainId(int syrupTokenChainId) { this.syrupTokenChainId = syrupTokenChainId; } public int getSyrupTokenAssetId() { return syrupTokenAssetId; } public void setSyrupTokenAssetId(int syrupTokenAssetId) { this.syrupTokenAssetId = syrupTokenAssetId; } public String getSyrupPerBlock() { return syrupPerBlock; } public void setSyrupPerBlock(String syrupPerBlock) { this.syrupPerBlock = syrupPerBlock; } public long getStartBlockHeight() { return startBlockHeight; } public void setStartBlockHeight(long startBlockHeight) { this.startBlockHeight = startBlockHeight; } public long getLockedTime() { return lockedTime; } public void setLockedTime(long lockedTime) { this.lockedTime = lockedTime; } public String getCreatorAddress() { return creatorAddress; } public void setCreatorAddress(String creatorAddress) { this.creatorAddress = creatorAddress; } public String getAccSyrupPerShare() { return accSyrupPerShare; } public void setAccSyrupPerShare(String accSyrupPerShare) { this.accSyrupPerShare = accSyrupPerShare; } public String getSyrupTokenBalance() { return syrupTokenBalance; } public void setSyrupTokenBalance(String syrupTokenBalance) { this.syrupTokenBalance = syrupTokenBalance; } public String getStakeTokenBalance() { return stakeTokenBalance; } public void setStakeTokenBalance(String stakeTokenBalance) { this.stakeTokenBalance = stakeTokenBalance; } public String getTotalSyrupAmount() { return totalSyrupAmount; } public void setTotalSyrupAmount(String totalSyrupAmount) { this.totalSyrupAmount = totalSyrupAmount; } public boolean isModifiable() { return modifiable; } public void setModifiable(boolean modifiable) { this.modifiable = modifiable; } public long getWithdrawLockTime() { return withdrawLockTime; } public void setWithdrawLockTime(long withdrawLockTime) { this.withdrawLockTime = withdrawLockTime; } }
package com.neu.spring; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import com.neu.spring.pojo.StockInfo; import com.neu.spring.pojo.TradeOrder; public class BuyValidator implements Validator { public boolean supports(Class aClass) { return aClass.equals(TradeOrder.class); } public void validate(Object obj, Errors errors) { TradeOrder tradeOrder = (TradeOrder) obj; ValidationUtils.rejectIfEmptyOrWhitespace(errors, "stockId", "error.invalid.stockId", "stockId Required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "traderId", "error.invalid.traderId", "traderId Required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "buyDate", "error.invalid.buyDate", "buyDate Required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "buyPrice", "error.invalid.buyPrice", "buyPrice Required"); // ValidationUtils.rejectIfEmptyOrWhitespace(errors, "status", "error.status", "status Required"); // ValidationUtils.rejectIfEmptyOrWhitespace(errors, "type", "error.type", "type Required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "qty", "error.qty", "qty Required"); // ValidationUtils.rejectIfEmptyOrWhitespace(errors, "instrument", "error.instrument", "instrument Required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "triggerPrice", "error.triggerPrice", "triggerPrice Required"); } }
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(); System.out.println((((input.nextLong()-12345+2147483648l)%2147483648l)*1857678181)%2147483648l); } }
package com.xiv.gearplanner.controllers; import com.xiv.gearplanner.models.inventory.Gear; import com.xiv.gearplanner.models.inventory.GearStatType; import com.xiv.gearplanner.models.inventory.GearType; import com.xiv.gearplanner.models.inventory.ItemStat; import com.xiv.gearplanner.services.GearService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PageableDefault; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.validation.Valid; @Controller public class GearController { private GearService gear; @Autowired public GearController(GearService gear) { this.gear = gear; } @GetMapping("/gear") public String addMain(Model model) { model.addAttribute("gear", new Gear()); model.addAttribute("stat", new ItemStat()); model.addAttribute("statTypes", gear.getGears().getStatTypes()); model.addAttribute("types", gear.getGears().getGearTypes()); return "gear/index"; } @PostMapping("/gear") public String addGearSubmit(@RequestParam("stat-type") String type, @RequestParam("value") String value, @Valid Gear newGear, Model model) { newGear.addGearStat(gear.convertStatList(type,value)); gear.save(newGear); return "redirect:/gear"; } @GetMapping("/gear/view") public String viewGear(Model model, @PageableDefault(value=25) Pageable pageable ) { model.addAttribute("gear", gear.getGears().findAll(pageable)); return "gear/view"; } @GetMapping("/gear/add") public String addGear(Model model) { model.addAttribute("gear", new Gear()); return "gear/add"; } @GetMapping("/gear/add/stat-type") public String addStatType(Model model) { model.addAttribute("statTypes",new GearStatType()); return "gear/addStatType"; } @GetMapping("/gear/add/type") public String addType(Model model) { model.addAttribute("type",new GearType()); return "gear/addType"; } @PostMapping("/gear/add/type") public String addTypeSubmit(@Valid GearType type, Model model) { return "redirect:/gear"; } @GetMapping("/api/gear") public String jsonGear() { return ""; } }
package net.sf.throughglass.timeline.ui; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; /** * Created by guang_hik on 14-8-10. */ public class LazyBitmapDrawable extends BitmapDrawable { public LazyBitmapDrawable(Bitmap bitmap) { super(bitmap); } }
package com.asterixcode.asterixfoodapi.domain.repository; import com.asterixcode.asterixfoodapi.domain.model.Restaurant; import java.util.List; public interface RestaurantRepository { List<Restaurant> listAll(); Restaurant getBy(Long id); Restaurant add(Restaurant restaurant); void remove(Restaurant restaurant); }
package com.miao.demo.agent; import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import java.io.ByteArrayInputStream; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.lang.instrument.Instrumentation; import java.security.ProtectionDomain; public class ClassTransform implements ClassFileTransformer { private Instrumentation inst; protected ClassTransform(Instrumentation inst) { this.inst = inst; } /** * 此方法在redefineClasses时或者初次加载时会调用,也就是说在class被再次加载时会被调用, * 并且我们通过此方法可以动态修改class字节码,实现类似代理之类的功能,具体方法可使用ASM或者javasist, * 如果对字节码很熟悉的话可以直接修改字节码。 */ @Override public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { byte[] transformed = null; HotAgent.clsnames.add(className); return null; } // @Override // public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer){ // System.out.println("正在加载类:"+ className); // if (!"com/miao/demo/entity/Bean1".equals(className)){ // return classfileBuffer; // } // // CtClass cl = null; // try { // ClassPool classPool = ClassPool.getDefault(); // cl = classPool.getOrNull("Bean1"); // System.out.println("cl=====>"+cl); // if(cl!=null){ // cl.detach(); // } // cl = classPool.makeClass(new ByteArrayInputStream(classfileBuffer)); // CtMethod ctMethod = cl.getDeclaredMethod("test1"); // System.out.println("获取方法名称:"+ ctMethod.getName()); // // ctMethod.insertBefore("System.out.println(\" 动态插入的打印语句 \");"); // ctMethod.insertAfter("System.out.println($_);"); // byte[] transformed = cl.toBytecode(); // return transformed; // }catch (Exception e){ // e.printStackTrace(); // // } // return classfileBuffer; // } }
import org.openqa.selenium.By; import static com.codeborne.selenide.Selenide.$; public class Come3Branch { private By btnBranches1 = By.xpath("//a[@id='btnBranches']"); private By btnBranchesSl = By.xpath("//div[@id='treeview']//ul[@class = 'k-group']//span[@class='k-icon k-plus']"); private By btnBranches2 = By.xpath("//*[@id='treeview_tv_active']/ul/li[1]/div/span[1]"); private By btnBranches3 = By.xpath("//*[@id='treeview_tv_active']/ul/li/div/span/span[1]"); public Come3Branch сome3Branch() { $(btnBranches1).click(); $(btnBranchesSl).click(); $(btnBranches2).click(); $(btnBranches3).click(); return new Come3Branch(); } }
package com.worldchip.bbp.ect.util; import com.worldchip.bbp.ect.R; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.animation.Animation.AnimationListener; import android.view.animation.RotateAnimation; import android.view.animation.TranslateAnimation; /** * 杞洏鍔ㄧ敾 * @author Administrator * */ public class PangxieAnimationUtils { private static boolean isRunning = false; public static void startInRotateAnimation(final View view,long startOffset) { TranslateAnimation ta = new TranslateAnimation(0, 70, 0, 0); ta.setStartOffset(startOffset); ta.setFillAfter(true); ta.setDuration(2000); ta.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation arg0) { // TODO Auto-generated method stub isRunning = true; } @Override public void onAnimationRepeat(Animation arg0) { // TODO Auto-generated method stub } @Override public void onAnimationEnd(Animation arg0) { // TODO Auto-generated method stub isRunning = false; startOutRotateAnimation(view, 1500); } }); view.startAnimation(ta); } public static void startOutRotateAnimation(final View view, long startOffset) { TranslateAnimation ta = new TranslateAnimation(70, 0, 0, 0); ta.setStartOffset(startOffset); ta.setFillAfter(true); ta.setDuration(2000); ta.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation arg0) { // TODO Auto-generated method stub isRunning = true; } @Override public void onAnimationRepeat(Animation arg0) { // TODO Auto-generated method stub } @Override public void onAnimationEnd(Animation arg0) { // TODO Auto-generated method stub isRunning = false; } }); view.startAnimation(ta); } public static boolean isRunningAnimation() { // return isInRunning || isOutRunning; return isRunning; } }
package ru.job4j.bank; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.TreeMap; import java.util.stream.Collectors; /** * Класс Bank реализует сущность Банк. * * @author Gureyev Ilya (mailto:ill-jah@yandex.ru) * @version 2018-12-12 * @since 2017-05-15 */ public class Bank { /** * Список счетов пользователя. */ private TreeMap<User, List<Account>> accounts; /** * Конструктор. */ public Bank() { this.accounts = new TreeMap<>(); } /** * Добавляет счёт пользователя. * @param user пользователь. * @param account счёт пользователя. */ public void addAccountToUser(User user, Account account) { List<Account> userAccounts = this.accounts.get(user); if (userAccounts == null) { userAccounts = new LinkedList<>(); } userAccounts.add(account); this.accounts.put(user, userAccounts); } /** * Добавляет пользователя. * @param user пользователь. */ public void addUser(User user) { this.accounts.put(user, new LinkedList<>()); } /** * Удаляет счёт пользователя. * @param user пользователь. * @param account счёт пользователя. */ public void deleteAccountFromUser(User user, Account account) { List<Account> userAccounts = this.accounts.get(user); userAccounts.remove(account); } /** * Удаляет пользователя. * @param user пользователь. */ public void deleteUser(User user) { this.accounts.remove(user); } /** * Получает пользователей. * @return список пользователей. */ public List<User> getUsersAsList() { return this.accounts.keySet().stream().collect(Collectors.toList()); } /** * Получает пользователя. * @param passport паспорт пользователя. * @return пользователь. */ public User getUserByPassport(String passport) { Optional<User> oUser = this.accounts.keySet().stream().filter(x -> x.getPassport().equals(passport)).findFirst(); return oUser.isPresent() ? oUser.get() : null; } /** * Получает счёт по паспорту и реквизитам. * @param passport паспорт пользователя. * @param requisites реквизитам счёта. * @return счёт. */ public Account getAccountByRequisitesAndPassport(final String passport, final String requisites) { Account acc = null; if (passport != null && requisites != null) { User user = this.getUserByPassport(passport); if (user != null) { Optional<Account> oAcc = this.accounts.get(user).stream().filter(x -> x.getRequisites().equals(requisites)).findFirst(); acc = oAcc.isPresent() ? oAcc.get() : null; } } return acc; } /** * Получает список со счетами. * @return список со счетами. */ public List<Account> getAccounts() { List<Account> accounts = new LinkedList<>(); this.accounts.values().forEach(accounts::addAll); return accounts; } /** * Получает список со счетами пользователя. * @param user пользователь. * @return список со счетами пользователя. */ public List<Account> getUserAccounts(User user) { return this.accounts.get(user); } /** * Переводит деньги между счетами. * @param srcUser пользователь-источник. * @param srcAccount счёт списания. * @param dstUser пользователь-получатель. * @param dstAccount счёт получения. * @param amount сумма перевода. * @return true в случае успешного перевода денег, иначе false. */ public boolean transferMoney(User srcUser, Account srcAccount, User dstUser, Account dstAccount, double amount) { boolean success = false; Account srcAcc = this.getAccountByRequisitesAndPassport(srcUser.getPassport(), srcAccount.getRequisites()); Account dstAcc = this.getAccountByRequisitesAndPassport(dstUser.getPassport(), dstAccount.getRequisites()); if (srcAcc != null && dstAcc != null && srcAcc.getValue() >= amount) { srcAcc.setValue(srcAcc.getValue() - amount); dstAcc.setValue(dstAcc.getValue() - amount); success = true; } return success; } }
package com.alextroy.alextroynewsuda; public class News { private String webTitle; private String webPublicationDate; private String webSectionName; private String webUrl; private String webAuthor; public News(String webTitle, String webPublicationDate, String webSectionName, String webUrl, String webAuthor) { this.webTitle = webTitle; this.webPublicationDate = webPublicationDate; this.webSectionName = webSectionName; this.webUrl = webUrl; this.webAuthor = webAuthor; } public String getWebTitle() { return webTitle; } public String getWebPublicationDate() { return webPublicationDate; } public String getWebSectionName() { return webSectionName; } public String getWebUrl() { return webUrl; } public String getWebAuthor() { return webAuthor; } }
package com.scriptingsystems.tutorialjava.poo.interfaces; public interface Comparable { public int compareTo (Object other) throws ComparationException; }
package core.client.game.operations; import cards.Card; import cards.equipments.Equipment.EquipmentType; import ui.game.interfaces.Activatable; import ui.game.interfaces.CardUI; public abstract class AbstractCardInitiatedMultiTargetOperation extends AbstractMultiCardMultiTargetOperation { protected final CardUI activator; /** * @param card : the card that activated this Operation * @param maxTargets : max number of targets selectable */ public AbstractCardInitiatedMultiTargetOperation(Activatable card, int maxTargets) { super(0, maxTargets); this.activator = (CardUI) card; } @Override protected final boolean isCardActivatable(Card card) { return false; } @Override protected boolean isConfirmEnabled() { return this.targets.size() == this.maxTargets; } @Override protected final boolean isCancelEnabled() { return true; } @Override protected final boolean isEquipmentTypeActivatable(EquipmentType type) { return false; } @Override public void onLoadedCustom() { this.activator.setActivatable(true); this.activator.setActivated(true); } @Override public void onUnloadedCustom() { this.activator.setActivatable(false); this.activator.setActivated(false); } }
package travel.api; import com.alibaba.nacos.api.annotation.NacosInjected; import com.alibaba.nacos.api.annotation.NacosProperties; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource; import com.alibaba.nacos.spring.context.annotation.discovery.EnableNacosDiscovery; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; import javax.annotation.PostConstruct; import java.util.TimeZone; /** * @author Administrator */ @SpringBootApplication @ServletComponentScan(basePackages = {"travel.api.config"}) @MapperScan(basePackages = {"travel.api.table.mapper"}) @NacosPropertySource(dataId = "example", autoRefreshed = true) @EnableNacosDiscovery(globalProperties = @NacosProperties(serverAddr = "47.102.121.70:8848")) public class ApiApplication{ @PostConstruct void setDefaultTimezone() { TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai")); } @NacosInjected private NamingService namingService; public static void main(String[] args) { TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai")); SpringApplication.run(ApiApplication.class, args); } @PostConstruct public void registerInstance() throws NacosException { namingService.registerInstance("api", "47.102.121.70", 9999); } }
package elections; public interface Constituency { int votersCount(); void permanentlyUpdateVotersPreferences(int[] vector); void temporarilyUpdateVotersPreferences(int[] vector); int checkCumulativePartyScoreAfterApplyingAction(CampaignAction action, Party party); ConstituencyResults castVotes(); int mandatesCount(); String name(); }
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2011 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ActiveEon Team * http://www.activeeon.com/ * Contributor(s): * * ################################################################ * $$ACTIVEEON_INITIAL_DEV$$ */ package org.ow2.proactive.scheduler; import java.net.URI; import javax.security.auth.login.LoginException; import org.apache.log4j.Logger; import org.objectweb.proactive.ActiveObjectCreationException; import org.objectweb.proactive.annotation.PublicAPI; import org.objectweb.proactive.api.PAActiveObject; import org.objectweb.proactive.core.config.CentralPAPropertyRepository; import org.objectweb.proactive.core.util.log.ProActiveLogger; import org.ow2.proactive.authentication.crypto.Credentials; import org.ow2.proactive.resourcemanager.authentication.RMAuthentication; import org.ow2.proactive.resourcemanager.exception.RMException; import org.ow2.proactive.resourcemanager.frontend.RMConnection; import org.ow2.proactive.scheduler.authentication.SchedulerAuthentication; import org.ow2.proactive.scheduler.common.Scheduler; import org.ow2.proactive.scheduler.common.SchedulerAuthenticationInterface; import org.ow2.proactive.scheduler.common.SchedulerConnection; import org.ow2.proactive.scheduler.common.exception.InternalSchedulerException; import org.ow2.proactive.scheduler.common.exception.SchedulerException; import org.ow2.proactive.scheduler.common.util.SchedulerLoggers; import org.ow2.proactive.scheduler.core.SchedulerFrontend; import org.ow2.proactive.scheduler.core.properties.PASchedulerProperties; import org.ow2.proactive.scheduler.exception.AdminSchedulerException; import org.ow2.proactive.scheduler.util.SchedulerDevLoggers; /** * <b>Start here</b>, it provides method to create a new ProActive Scheduler and manage it.<br> * With this Class, you will be able to create a new scheduler with or without connecting yourself, * or create it with your administrator properties.<br> * A resources manager may have been launched before creating a new scheduler. * * Object which performs the Scheduler (RM)creation, * and provides Scheduler's front-end active objects.<BR> * {@link SchedulerAuthentication}.<BR> * * @author The ProActive Team * @since ProActive Scheduling 2.0 */ @PublicAPI public class SchedulerFactory { /** Logger to be used for all messages related to the scheduler */ public static final Logger logger = ProActiveLogger.getLogger(SchedulerLoggers.SCHEDULER); public static final Logger logger_dev = ProActiveLogger.getLogger(SchedulerDevLoggers.SCHEDULER); private static boolean allowNullInit = false; private static boolean schedulerStarted = false; /** * Try to join Resource Manager at given URI. * * @param uriRM the resource manager URL * @return a Resource Manager authentication interface if success. * @throws RMException if no RM could be joined at this URI. */ public static RMAuthentication tryJoinRM(URI uriRM) throws RMException { return RMConnection.join(uriRM.toString()); } /** * Creates and starts a Scheduler on the local host using the given initializer to configure it. * Only one Scheduler can be started by JVM. * * @param rmURL the URL of a started Resource Manager * @param initializer Use to configure the Scheduler before starting it. * This parameter cannot be null, if you want to start the Scheduler using JVM properties * use the {@link #} to start the Scheduler without configuration * * @return a Scheduler authentication that allow you to administer it or get its connection URL. * * @throws ActiveObjectCreationException If Scheduler cannot be created */ public static synchronized SchedulerAuthenticationInterface startLocal(URI rmURL, SchedulerInitializer initializer) throws InternalSchedulerException { if (!schedulerStarted) { if (!allowNullInit) { if (initializer != null) { //configure application configure(initializer); } else { throw new IllegalArgumentException("Initializer cannot be null !"); } } if (rmURL == null) { throw new IllegalArgumentException("RM url is null !"); } try { tryJoinRM(rmURL); String policy = initializer.getPolicyFullClassName(); //start scheduler createScheduler(rmURL, policy); SchedulerAuthenticationInterface sai = SchedulerConnection.waitAndJoin(null); schedulerStarted = true; return sai; } catch (Exception e) { throw new InternalSchedulerException(e); } } else { throw new InternalSchedulerException("Scheduler already localy running"); } } /** * Configure the VM to be ready to start the new Scheduler. * * @param initializer the initializer used to configured the VM. */ private static void configure(SchedulerInitializer initializer) { //security manager if (System.getProperty("java.security.manager") == null) { System.setProperty("java.security.manager", ""); } //check policy String s = initializer.getPolicyFullClassName(); if (s == null) { throw new IllegalArgumentException("Scheduler policy is not set, cannot start Scheduler !"); } //scheduler properties s = initializer.getSchedulerPropertiesConfiguration(); if (s == null) { throw new IllegalArgumentException( "Scheduler properties file is not set, cannot start Scheduler !"); } System.setProperty(PASchedulerProperties.PA_SCHEDULER_PROPERTIES_FILEPATH, s); //pa conf s = initializer.getProActiveConfiguration(); if (s != null) { System.setProperty(CentralPAPropertyRepository.PA_CONFIGURATION_FILE.getName(), s); } //Scheduler home s = initializer.getSchedulerHomePath(); if (s != null) { System.setProperty(PASchedulerProperties.SCHEDULER_HOME.getKey(), s); } } /** * Creates and starts a Scheduler on the local host. * This call considered that the JVM is correctly configured for starting Scheduler. * The "pa.scheduler.home" and required JVM properties MUST be set. * * @param rmURL the URL of a started Resource Manager * @param policy the full class name of the Scheduling policy to use. * * @return a Scheduler authentication that allow you to administer the Scheduler or get its connection URL. * * @throws ActiveObjectCreationException If Scheduler cannot be created */ public static SchedulerAuthenticationInterface startLocal(URI rmURL, String policy) throws Exception { SchedulerInitializer init = new SchedulerInitializer(); init.setPolicyFullClassName(policy); allowNullInit = true; SchedulerAuthenticationInterface sai = startLocal(rmURL, init); allowNullInit = false; return sai; } /** * Create a new scheduler on the local host plugged on the given resource manager.<br> * This will provide a connection interface to allow the access to a restricted number of user.<br> * Use {@link SchedulerConnection} class to join the Scheduler. * * @param rmURL the resource manager URL on which the scheduler will connect * @param policyFullClassName the full policy class name for the scheduler. * @throws AdminSchedulerException If an error occurred during creation process */ public static void createScheduler(URI rmURL, String policyFullClassName) throws AdminSchedulerException { logger.info("Starting new Scheduler"); //check arguments... if (rmURL == null) { String msg = "The Resource Manager URL must not be null"; logger_dev.error(msg); throw new AdminSchedulerException(msg); } try { // creating the scheduler // if this fails then it will not continue. logger.info("Creating scheduler frontend..."); PAActiveObject.newActive(SchedulerFrontend.class.getName(), new Object[] { rmURL, policyFullClassName }); //ready logger.info("Scheduler is now ready to be started !"); } catch (Exception e) { logger_dev.error(e); throw new AdminSchedulerException(e.getMessage()); } } /** * Create a new scheduler on the local host plugged on the given resource manager.<br> * This constructor also requires the credentials of the client to connect.<br><br> * It will return a client scheduler able to managed the scheduler.<br><br> * <font color="red">WARNING :</font> this method provides a way to connect to the scheduler after its creation, * BUT if the scheduler is restarting after failure, this method will create the scheduler * but will throw a SchedulerException due to the failure of client connection.<br> * In fact, while the scheduler is restarting after a crash, no one can connect it during the whole restore process.<br><br> * In any other case, the method will block until connection is allowed or error occurred. * * @param rmURL the resource manager URL on which the scheduler will connect * @param policyFullClassName the full policy class name for the scheduler. * @return a scheduler interface to manage the scheduler. * @throws SchedulerException if the scheduler cannot be created. * @throws AdminSchedulerException if a client connection exception occurs. * @throws LoginException if a user login/password exception occurs. */ public static Scheduler createScheduler(Credentials creds, URI rmURL, String policyFullClassName) throws AdminSchedulerException, SchedulerException, LoginException { createScheduler(rmURL, policyFullClassName); SchedulerAuthenticationInterface auth = SchedulerConnection.waitAndJoin(null); return auth.login(creds); } }
package action; import java.util.ArrayList; import com.opensymphony.xwork2.ActionSupport; import mantenimiento.GestionTurismo; import models.Categoria; import models.Paquete; public class TurismoAction extends ActionSupport{ /** * */ private static final long serialVersionUID = 1L; // DATOS private ArrayList<Categoria> listaCategorias; private ArrayList<Paquete> listaPaquetes; private Paquete p; private String mensaje; public String registrarPaquete() { int i= new GestionTurismo().registrarPaquete(p); if (i == 0) { mensaje = "No se pudo registrar"; addActionError("No se registro correctamente"); return "error"; } else { mensaje = "Registro exitoso"; addActionMessage(mensaje); return "ok"; } } public String listadoCategoria() { listaCategorias = new GestionTurismo().listaCategorias(); return "ok"; } public String listadoPaquetes() { return "ok"; } public ArrayList<Categoria> getListaCategorias() { return listaCategorias; } public void setListaCategorias(ArrayList<Categoria> listaCategorias) { this.listaCategorias = listaCategorias; } public ArrayList<Paquete> getListaPaquetes() { return listaPaquetes; } public void setListaPaquetes(ArrayList<Paquete> listaPaquetes) { this.listaPaquetes = listaPaquetes; } public Paquete getP() { return p; } public void setP(Paquete p) { this.p = p; } public String getMensaje() { return mensaje; } public void setMensaje(String mensaje) { this.mensaje = mensaje; } }
package com.bistel.distributed; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; public class MessagePublishLookup { private static Set<String> set = new HashSet<String>(); public static void savePref(String pref) { set.add(pref); } public static void removeAll() { set.clear(); } public static void removePref(String pref) { set.remove(pref); } public static boolean isAvailable(String pref) { return set.contains(pref); } public static List<String> getKey(String prefix) { List<String> list = new ArrayList<String>(); Iterator<String> it = set.iterator(); while(it.hasNext()) { String key = it.next(); if(key.startsWith(prefix)) { list.add(key); } } return list; } public static Set<String> getSet() { return set; } }
/** * Class for the Manager of the Software Project Day project. Manager answers * team leader questions, holds meetings, goes to meetings, and goes to lunch, * and when not doing those things, does whatever managers do. * * @author Jonathon Shippling <jjs5471@rit.edu> */ public class Manager extends Employee{ // The manager's own office private final Office office; //The conference room for the morning meeting private final ConferenceRoom conferenceRoom; private final AfternoonConferenceRoom afternoonConferenceRoom; //how long, in ms, it takes to complete various tasks private long manLunchTime = 600L; private long manExecMeetTime = 600L; // The earliest time a manager can begin a task, in ns private long manDevMeetStart = 0L; //8:00 am, waits in office for //all leaders to arrive by 8:30 private long manExecMeet1Start = 1200000000L; //10:00 am, unless a question is in his queue private long manLunchStart = 2400000000L; //12:00 pm, unless a question is in his queue private long manExecMeet2Start = 3600000000L; //2:00 pm, unless a question is in his queue private long manStatusMeetStart = 4800000000L; //4:00 pm, waits in conference room for //all team members to arrive by 4:15 private long manEndDayStart = 5400000000L; //5:00 pm, unless a question in in his queue // The runnables scheduled protected Runnable goToDevMeeting; protected Runnable goToExecMeeting; protected Runnable goToLunch; protected Runnable goToStatusUpdateMeeting; protected Runnable endOfDayLeave; /** * Constructor for the Manager * * @param scheduler the lone event scheduler * @param numTeamLeads the number of team leaders */ public Manager(Scheduler scheduler, int numTeamLeads, ConferenceRoom conferenceRoom, AfternoonConferenceRoom afternoonConferenceRoom){ super(scheduler, null); this.setName("Manager"); this.office = new Office(numTeamLeads + 1, this); this.conferenceRoom = conferenceRoom; this.afternoonConferenceRoom = afternoonConferenceRoom; initRunnables(); registerDaysEvents(scheduler); } /** * Initialization of the Manager's runnables for scheduling */ @Override protected void initRunnables() { /** * Runnable for the developer meeting starting as early as 8am */ goToDevMeeting = new Runnable() { @Override public void run(){ System.out.println("Manager goes to morning developer meeting"); office.enterRoom(); } }; /** * Runnable for the scheduled meetings from 10-11 and 2-3 */ goToExecMeeting = new Runnable() { @Override public void run(){ System.out.println("Manager goes to an Executive Meeting"); try { Thread.sleep(manExecMeetTime); } catch (InterruptedException e) { } System.out.println("Manager left an Executive Meeting"); } }; /** * Runnable for the Manager's lunch time */ goToLunch = new Runnable(){ @Override public void run() { System.out.println("Manager goes to lunch"); try { Thread.sleep(manLunchTime); } catch (InterruptedException e) { } System.out.println("Manager returns from lunch"); } }; /** * Runnable for the status update meeting taking place as early as 4 pm */ goToStatusUpdateMeeting = new Runnable(){ @Override public void run() { System.out.println("Manager goes to the project status update"+ " meeting"); afternoonConferenceRoom.enterRoom(); // TODO enter the afternoon conference meeting room } }; /** * Runnable for the manager leaving at the end of the day */ endOfDayLeave = new Runnable() { public void run() { System.out.println("Manager leaves work."); //Throw an interrupt which states that this developer thread can now be terminated //as the developer has now left. interrupt(); } }; } /** * Manager registering his runnables with the scheduler */ @Override protected void registerDaysEvents(Scheduler scheduler) { scheduler.registerEvent(goToDevMeeting, this, manDevMeetStart, false); scheduler.registerEvent(goToExecMeeting, this, manExecMeet1Start, false); scheduler.registerEvent(goToLunch, this, manLunchStart, false); scheduler.registerEvent(goToExecMeeting, this, manExecMeet2Start, false); scheduler.registerEvent(goToStatusUpdateMeeting, this, manStatusMeetStart, false); scheduler.registerEvent(endOfDayLeave, this, manEndDayStart, true); } /** * Returns the Manager's office * * @return */ public Office getOffice(){ return office; } /** * The manager is able to answer questions always */ @Override protected boolean canAnswerQuestion() { return true; } /** * Manager receives the question and then sleeps for the appropriate * amount of time */ @Override protected void onQuestionAsked(Employee askedTo) { System.out.println("Manager received a question."); try { Thread.sleep(100L); } catch (InterruptedException e) { } System.out.println("Manager answered a question."); } /** * Managers never receive answers, only ask questions */ @Override protected void onAnswerReceived(Employee receivedFrom) { return; } /** * Should never be called as a manager as he doesn't ask questions */ @Override protected void onQuestionCancelled(Employee notAvailable) { return; } }
package com.icia.example03.editor; import java.beans.*; import java.time.*; import org.springframework.stereotype.*; @Component public class CustomLocalDateEditor extends PropertyEditorSupport { // text : 2020-11-20 @Override public void setAsText(String text) throws IllegalArgumentException { String[] str = text.split("-"); int year = Integer.parseInt(str[0]); int month = Integer.parseInt(str[1]); int day = Integer.parseInt(str[2]); LocalDate date = LocalDate.of(year, month, day); setValue(date); } }