text stringlengths 10 2.72M |
|---|
package com.grability.test.dlmontano.grabilitytest.interfaces;
import com.grability.test.dlmontano.grabilitytest.model.ContentType;
import java.util.Map;
/**
* Created by Diego Montano on 05/06/2016.
*/
public interface ContentTypeDataSource extends DataSource {
boolean defaultSourceContentHasContentTypes();
boolean sourceContentHasContentTypes(String sourceContentName, boolean open);
int getContentTypesCount();
Map<Long, ContentType> getAllContentTypes();
ContentType getContentTypeByAppId(long appId);
boolean addContentType(ContentType contentType);
boolean updateContentType(ContentType contentType);
boolean deleteContentType(ContentType contentType);
}
|
package com.nearsoft.upiita.api.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication
@ComponentScan("com.nearsoft.upiita.api")
@EntityScan("com.nearsoft.upiita.api.model")
@EnableJpaRepositories("com.nearsoft.upiita.api.repository")
public class UpiitaApiApplication {
public static void main(String [] args) {
SpringApplication.run(UpiitaApiApplication.class, args);
}
}
|
package com.paleimitations.schoolsofmagic.common.spells.modifiers;
public interface IHasArea {
}
|
package com.tencent.mm.protocal.c;
import f.a.a.b;
import f.a.a.c.a;
import java.util.LinkedList;
public final class bmo extends bhp {
public bhy rKi;
public bhy rKj;
public bhy rKk;
public float rYk;
public int rgC;
public int skL;
public bhy skM;
public bhy skN;
public bhy skO;
public bhy skP;
public bhy skQ;
public int skR;
public int skS;
public String skT;
protected final int a(int i, Object... objArr) {
int fS;
if (i == 0) {
a aVar = (a) objArr[0];
if (this.six == null) {
throw new b("Not all required fields were included: BaseResponse");
} else if (this.skM == null) {
throw new b("Not all required fields were included: SongName");
} else if (this.skN == null) {
throw new b("Not all required fields were included: SongSinger");
} else if (this.rKj == null) {
throw new b("Not all required fields were included: SongAlbum");
} else if (this.rKk == null) {
throw new b("Not all required fields were included: SongAlbumUrl");
} else if (this.skO == null) {
throw new b("Not all required fields were included: SongWifiUrl");
} else if (this.skP == null) {
throw new b("Not all required fields were included: SongWapLinkUrl");
} else if (this.skQ == null) {
throw new b("Not all required fields were included: SongWebUrl");
} else if (this.rKi == null) {
throw new b("Not all required fields were included: SongLyric");
} else {
if (this.six != null) {
aVar.fV(1, this.six.boi());
this.six.a(aVar);
}
aVar.fT(2, this.rgC);
aVar.fT(3, this.skL);
aVar.l(4, this.rYk);
if (this.skM != null) {
aVar.fV(5, this.skM.boi());
this.skM.a(aVar);
}
if (this.skN != null) {
aVar.fV(6, this.skN.boi());
this.skN.a(aVar);
}
if (this.rKj != null) {
aVar.fV(7, this.rKj.boi());
this.rKj.a(aVar);
}
if (this.rKk != null) {
aVar.fV(8, this.rKk.boi());
this.rKk.a(aVar);
}
if (this.skO != null) {
aVar.fV(9, this.skO.boi());
this.skO.a(aVar);
}
if (this.skP != null) {
aVar.fV(10, this.skP.boi());
this.skP.a(aVar);
}
if (this.skQ != null) {
aVar.fV(11, this.skQ.boi());
this.skQ.a(aVar);
}
if (this.rKi != null) {
aVar.fV(12, this.rKi.boi());
this.rKi.a(aVar);
}
aVar.fT(13, this.skR);
aVar.fT(14, this.skS);
if (this.skT == null) {
return 0;
}
aVar.g(15, this.skT);
return 0;
}
} else if (i == 1) {
if (this.six != null) {
fS = f.a.a.a.fS(1, this.six.boi()) + 0;
} else {
fS = 0;
}
fS = ((fS + f.a.a.a.fQ(2, this.rgC)) + f.a.a.a.fQ(3, this.skL)) + (f.a.a.b.b.a.ec(4) + 4);
if (this.skM != null) {
fS += f.a.a.a.fS(5, this.skM.boi());
}
if (this.skN != null) {
fS += f.a.a.a.fS(6, this.skN.boi());
}
if (this.rKj != null) {
fS += f.a.a.a.fS(7, this.rKj.boi());
}
if (this.rKk != null) {
fS += f.a.a.a.fS(8, this.rKk.boi());
}
if (this.skO != null) {
fS += f.a.a.a.fS(9, this.skO.boi());
}
if (this.skP != null) {
fS += f.a.a.a.fS(10, this.skP.boi());
}
if (this.skQ != null) {
fS += f.a.a.a.fS(11, this.skQ.boi());
}
if (this.rKi != null) {
fS += f.a.a.a.fS(12, this.rKi.boi());
}
fS = (fS + f.a.a.a.fQ(13, this.skR)) + f.a.a.a.fQ(14, this.skS);
if (this.skT != null) {
fS += f.a.a.b.b.a.h(15, this.skT);
}
return fS;
} else if (i == 2) {
f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler);
for (fS = bhp.a(aVar2); fS > 0; fS = bhp.a(aVar2)) {
if (!super.a(aVar2, this, fS)) {
aVar2.cJS();
}
}
if (this.six == null) {
throw new b("Not all required fields were included: BaseResponse");
} else if (this.skM == null) {
throw new b("Not all required fields were included: SongName");
} else if (this.skN == null) {
throw new b("Not all required fields were included: SongSinger");
} else if (this.rKj == null) {
throw new b("Not all required fields were included: SongAlbum");
} else if (this.rKk == null) {
throw new b("Not all required fields were included: SongAlbumUrl");
} else if (this.skO == null) {
throw new b("Not all required fields were included: SongWifiUrl");
} else if (this.skP == null) {
throw new b("Not all required fields were included: SongWapLinkUrl");
} else if (this.skQ == null) {
throw new b("Not all required fields were included: SongWebUrl");
} else if (this.rKi != null) {
return 0;
} else {
throw new b("Not all required fields were included: SongLyric");
}
} else if (i != 3) {
return -1;
} else {
f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0];
bmo bmo = (bmo) objArr[1];
int intValue = ((Integer) objArr[2]).intValue();
LinkedList IC;
int size;
byte[] bArr;
f.a.a.a.a aVar4;
boolean z;
bhy bhy;
switch (intValue) {
case 1:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
fl flVar = new fl();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = flVar.a(aVar4, flVar, bhp.a(aVar4))) {
}
bmo.six = flVar;
}
return 0;
case 2:
bmo.rgC = aVar3.vHC.rY();
return 0;
case 3:
bmo.skL = aVar3.vHC.rY();
return 0;
case 4:
bmo.rYk = aVar3.vHC.readFloat();
return 0;
case 5:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
bhy = new bhy();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = bhy.a(aVar4, bhy, bhp.a(aVar4))) {
}
bmo.skM = bhy;
}
return 0;
case 6:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
bhy = new bhy();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = bhy.a(aVar4, bhy, bhp.a(aVar4))) {
}
bmo.skN = bhy;
}
return 0;
case 7:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
bhy = new bhy();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = bhy.a(aVar4, bhy, bhp.a(aVar4))) {
}
bmo.rKj = bhy;
}
return 0;
case 8:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
bhy = new bhy();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = bhy.a(aVar4, bhy, bhp.a(aVar4))) {
}
bmo.rKk = bhy;
}
return 0;
case 9:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
bhy = new bhy();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = bhy.a(aVar4, bhy, bhp.a(aVar4))) {
}
bmo.skO = bhy;
}
return 0;
case 10:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
bhy = new bhy();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = bhy.a(aVar4, bhy, bhp.a(aVar4))) {
}
bmo.skP = bhy;
}
return 0;
case 11:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
bhy = new bhy();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = bhy.a(aVar4, bhy, bhp.a(aVar4))) {
}
bmo.skQ = bhy;
}
return 0;
case 12:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
bhy = new bhy();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = bhy.a(aVar4, bhy, bhp.a(aVar4))) {
}
bmo.rKi = bhy;
}
return 0;
case 13:
bmo.skR = aVar3.vHC.rY();
return 0;
case 14:
bmo.skS = aVar3.vHC.rY();
return 0;
case 15:
bmo.skT = aVar3.vHC.readString();
return 0;
default:
return -1;
}
}
}
}
|
/**
*
*/
package com.atanu.java.spring.offersvc.bo;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.atanu.java.spring.offersvc.client.DataSvcClient;
import com.atanu.java.spring.offersvc.converter.AncillaryConverter;
import com.atanu.java.spring.offersvc.exception.OfferSvcException;
import com.atanu.java.spring.offersvc.logger.ApplicationLogger;
import com.atanu.java.spring.offersvc.model.client.AncillaryDetails;
import com.atanu.java.spring.offersvc.model.client.PreferredAncillaryResponse;
import com.atanu.java.spring.offersvc.model.service.Ancillary;
import com.atanu.java.spring.offersvc.model.service.AncillarySvcResponse;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
/**
* @author Atanu Bhowmick
*
*/
@Service
public class AncillaryMgmtBO {
@Autowired
private DataSvcClient dataSvcClient;
@Autowired
private AncillaryConverter converter;
@Autowired
private HazelcastInstance hazelcastInstance;
private static final ApplicationLogger logger = new ApplicationLogger(AncillaryMgmtBO.class);
/**
* @param ancillaryId
* @return Ancillary
* @throws OfferSvcException
*/
public Ancillary getAncillaryById(String ancillaryId) throws OfferSvcException {
logger.debug("Inside getAncillaryDetailsById()");
return converter.convertToAncllary(dataSvcClient.getAncillaryById(ancillaryId));
}
/**
* @return List<Ancillary>
* @throws OfferSvcException
*/
public List<Ancillary> getAllAncillaries() throws OfferSvcException {
logger.debug("Inside getAncillaryDetailsById()");
List<AncillaryDetails> ancillaryDetails = dataSvcClient.getAllAncillaries();
List<Ancillary> ancillaries = null;
if (!CollectionUtils.isEmpty(ancillaryDetails)) {
ancillaries = ancillaryDetails.stream().map(details -> converter.convertToAncllary(details))
.collect(Collectors.toList());
}
return ancillaries;
}
/**
* @param ancillarySvcRequest
* @return AncillarySvcResponse
* @throws OfferSvcException
*/
public AncillarySvcResponse getAncillariesByAirorts(String originAirportCode, String destAirporCode)
throws OfferSvcException {
logger.debug("Inside getAllAncillariesByAirortCode()");
PreferredAncillaryResponse ancillaryResponse = dataSvcClient
.getPreferredAncillaryResponseByAirports(originAirportCode, destAirporCode);
return converter.covertToAncillarySvcResponse(ancillaryResponse);
}
public String putInHazelastMap() {
IMap<String, String> iMap = hazelcastInstance.getMap("TEST_MAP");
iMap.lock("TEST_KEY");
iMap.put("TEST_KEY", "This is hazelcast cache testing..cache", 2L, TimeUnit.MINUTES);
iMap.unlock("TEST_KEY");
return "Success";
}
public String getFromHazelcastMap() {
IMap<String, String> iMap = hazelcastInstance.getMap("TEST_MAP");
return iMap.get("TEST_KEY");
}
} |
package ruletas;
import imports.GQueue;
import imports.RadixSortQueue;
import javax.swing.JOptionPane;
public class RadixSortQueue_ruleta {
public static void main(String[] args) {
GQueue<Integer> mainqueue = new GQueue<Integer>();
int numcompras = Integer.parseInt(JOptionPane.showInputDialog(null, "Dame cuantos gastos hiciste hoy:"));
for(int i=0; i<numcompras; i++){
mainqueue.enqueue(Integer.parseInt(JOptionPane.showInputDialog(null, "Dame los gastos que hiciste el dia de hoy:")));
}
RadixSortQueue sorter = new RadixSortQueue(mainqueue);
JOptionPane.showMessageDialog(null, ("Tus compras organizadas del dia de hoy son:\n")+ sorter.sort());
}
}
|
package com.ds.algo.matters.bfs;
import java.util.*;
public class IterativeBfsTraversal {
public static void main(String[] args){
List<Edge> edges = Arrays.asList(
new Edge(1, 2), new Edge(1, 3), new Edge(1, 4),
new Edge(2, 5), new Edge(2, 6), new Edge(5, 9),
new Edge(5, 10), new Edge(4, 7), new Edge(4, 8),
new Edge(7, 11), new Edge(7, 12)
// vertex 0, 13 and 14 are single nodes
);
final int N = 15;
Graph graph = new Graph(edges, N);
boolean[] discovered = new boolean[N];
for (int i = 0; i < N; i++){
if (!discovered[i]){
BFS(graph, i, discovered);
}
}
}
private static void BFS(Graph graph, int v, boolean[] discovered){
Queue<Integer> q = new ArrayDeque<>();
// mark source vertex as discovered
discovered[v] = true;
q.add(v);
while (!q.isEmpty()){
v = q.poll();
System.out.print(v + " ");
for (int u : graph.adjList.get(v)){
if (!discovered[u]){
discovered[u] = true;
q.add(u);
}
}
}
}
}
class Edge {
int source, destination;
public Edge(int source, int destination) {
this.source = source;
this.destination = destination;
}
}
class Graph {
List<List<Integer>> adjList = null;
Graph(List<Edge> edges, int N){
adjList = new ArrayList<>();
for (int i = 0; i < N; i++){
adjList.add(new ArrayList<>());
}
for (Edge edge : edges){
int src = edge.source;
int dest = edge.destination;
adjList.get(src).add(dest);
adjList.get(dest).add(src);
}
}
}
|
package median;
import java.util.Collections;
import java.util.PriorityQueue;
public class Solution {
public Solution() {
// add new fields and complete the constructor if necessary.
largehalf = new PriorityQueue<Integer>();
smallhalf = new PriorityQueue<Integer>(11, Collections.reverseOrder());
}
private PriorityQueue<Integer> largehalf;
private PriorityQueue<Integer> smallhalf;
public void read(int value) {
// write your implementation here.
if(smallhalf.isEmpty() || value <= smallhalf.peek()){
smallhalf.offer(value);
}
else{
largehalf.offer(value);
}
if(smallhalf.size() - largehalf.size() >= 2){
largehalf.offer(smallhalf.poll());
}
else if(largehalf.size() > smallhalf.size()){
smallhalf.offer(largehalf.poll());
}
}
public Double median() {
// write your implementation here.
int size = largehalf.size() + smallhalf.size();
if(size == 0){
return null;
}
else if(size % 2 != 0){
return (double) (smallhalf.peek());
}
else{
return (smallhalf.peek() + largehalf.peek())/2.0;
}
}
public static void main (String [] args){
Solution s = new Solution();
System.out.println();
}
}
|
package br.com.becommerce.infrastructure.persistence;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
@Configuration
public class MongoConfiguration {
private enum DateToZonedDateTimeConverter implements Converter<Date, ZonedDateTime> {
INSTANCE;
@Override
public ZonedDateTime convert(Date source) {
return ZonedDateTime.ofInstant(source.toInstant(), ZoneId.systemDefault());
}
}
private enum ZonedDateTimeToDateConverter implements Converter<ZonedDateTime, Date> {
INSTANCE;
@Override
public Date convert(ZonedDateTime source) {
return Date.from(source.toInstant());
}
}
@Bean
public MongoCustomConversions customConversions() {
List<Converter<?, ?>> converters = Arrays.asList(
DateToZonedDateTimeConverter.INSTANCE,
ZonedDateTimeToDateConverter.INSTANCE);
return new MongoCustomConversions(converters);
}
}
|
package com.company.domain;
import java.math.BigDecimal;
public class Business {
private Integer id;
private String password;
public Business(String password, String name, String addr, String ex, BigDecimal starPrice, BigDecimal sendPrice) {
this.password = password;
this.name = name;
this.addr = addr;
Ex = ex;
this.starPrice = starPrice;
this.sendPrice = sendPrice;
}
private String name;
private String addr;
private String Ex;
private BigDecimal starPrice;
private BigDecimal sendPrice;
public Business() {
}
public Business(Integer id,String password, String name, String addr, String ex, BigDecimal starPrice, BigDecimal sendPrice) {
this.id = id;
this.password = password;
this.name = name;
this.addr = addr;
Ex = ex;
this.starPrice = starPrice;
this.sendPrice = sendPrice;
}
public String getPassword() {
return password;
}
public Integer getId() {
return id;
}
@Override
public String toString() {
return "店名叫" + name +
", 地址在" + addr +
", 简介:" + Ex +
",订饭 " + starPrice +
"元起送, 配送费统一为" + sendPrice +
"元,欢迎订餐";
}
public void setId(Integer id) {
this.id = id;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public String getEx() {
return Ex;
}
public void setEx(String ex) {
Ex = ex;
}
public BigDecimal getStarPrice() {
return starPrice;
}
public void setStarPrice(BigDecimal starPrice) {
this.starPrice = starPrice;
}
public BigDecimal getSendPrice() {
return sendPrice;
}
public void setSendPrice(BigDecimal sendPrice) {
this.sendPrice = sendPrice;
}
}
|
package com.jjw.sparkCore.others.partitioner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.apache.spark.Partitioner;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function2;
import scala.Tuple2;
/**
* 自定义分区器
* @author root
*
*/
public class PartitionerTest {
public static void main(String[] args) {
SparkConf conf = new SparkConf();
conf.setMaster("local").setAppName("partitioner");
JavaSparkContext sc = new JavaSparkContext(conf);
JavaPairRDD<Integer, String> nameRDD = sc.parallelizePairs(Arrays.asList(
new Tuple2<Integer, String>(1,"zhangsan"),
new Tuple2<Integer, String>(2,"lisi"),
new Tuple2<Integer, String>(3,"wangwu"),
new Tuple2<Integer, String>(4,"zhaoliu"),
new Tuple2<Integer, String>(5,"shunqi"),
new Tuple2<Integer, String>(6,"zhouba")
), 2);
nameRDD.mapPartitionsWithIndex(new Function2<Integer, Iterator<Tuple2<Integer,String>>, Iterator<String>>() {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public Iterator<String> call(Integer index, Iterator<Tuple2<Integer, String>> iter) throws Exception {
List<String> list = new ArrayList<String>();
while(iter.hasNext()){
System.out.println("nameRDD partitionID = "+index+" , value = "+iter.next());
}
return list.iterator();
}
}, true).collect();
System.out.println("******************************");
JavaPairRDD<Integer, String> partitionRDD = nameRDD.partitionBy(new Partitioner() {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
/**
* 返回你想要创建分区的个数
*/
public int numPartitions() {
return 2;
}
@Override
/**
* 对输入的key做计算,然后返回该key的分区ID,范围一定是0到numPartitions-1
*/
public int getPartition(Object key) {
int i = (int)key;
if(i%2==0){
return 0;
}
return 1;
}
});
partitionRDD.mapPartitionsWithIndex(new Function2<Integer, Iterator<Tuple2<Integer,String>>, Iterator<String>>() {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public Iterator<String> call(Integer index, Iterator<Tuple2<Integer, String>> iter) throws Exception {
List<String> list = new ArrayList<String>();
while(iter.hasNext()){
System.out.println("partitionRDD partitionID = "+index+" , value = "+iter.next());
}
return list.iterator();
}
}, true).collect();
sc.stop();
}
}
|
package com.tencent.mm.blink;
import com.tencent.mm.kernel.j;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.x;
import java.util.ArrayList;
public final class a {
public static final int[] cVN = new int[]{0, 1, 2};
public static final int[] cVO = new int[]{3, 13, 23};
public static final int[] cVP = new int[]{4, 14, 24};
public static final int[] cVQ = new int[]{5, 15, 25};
public static final int[] cVR = new int[]{6, 16, 26};
public static final int[] cVS = new int[]{7, 17, 27};
public static final int[] cVT = new int[]{8, 18, 28};
public static final int[] cVU = new int[]{9, 19, 29};
public static final int[] cVV = new int[]{63, 69, 75};
public static final int[] cVW = new int[]{64, 70, 76};
public static final int[] cVX = new int[]{65, 71, 77};
public static final int[] cVY = new int[]{66, 72, 78};
private static final ArrayList<long[]> cVZ = new ArrayList();
private static long cWa = 0;
private static boolean cWb = false;
private static long cWc = 0;
private static long cWd = 0;
private static byte cWe = (byte) 0;
public static void aB(long j) {
j.aB(j);
}
public static void i(String str, long j) {
j.i(str, j);
}
public static void ey(String str) {
j.ey(str);
}
public static void i(long j, long j2) {
cVZ.add(new long[]{709, j, j2});
}
public static void j(long j, long j2) {
cVZ.add(new long[]{783, j, j2});
}
public static void xc() {
cWa = System.currentTimeMillis();
}
public static void xd() {
if (fl(1024)) {
j(1, System.currentTimeMillis() - cWa);
j(2, 1);
}
}
public static void cR(String str) {
if (fl(512) && ad.chW().equals(str)) {
cWb = true;
x.i("MicroMsg.BlinkStartup", "report this time");
}
}
public static void vh() {
fl(512);
}
public static void aC(long j) {
if (System.currentTimeMillis() - j > 200) {
fl(512);
cWb = false;
}
}
public static void xe() {
fl(512);
cWb = false;
}
public static void aD(long j) {
cWc = j;
cWd = j;
}
private static void a(int[] iArr, long j) {
x.i("MicroMsg.BlinkStartup", "%s %s", Integer.valueOf(iArr[0]), Long.valueOf(j));
i((long) iArr[0], j);
if (com.tencent.mm.f.a.lY) {
i((long) iArr[1], j);
} else {
i((long) iArr[2], j);
}
}
public static boolean xf() {
if (cWb) {
return fl(256);
}
return false;
}
private static boolean fl(int i) {
if ((cWe & i) != 0) {
return false;
}
cWe = (byte) (cWe | i);
x.i("MicroMsg.BlinkStartup", "checkAndMark bit 0x%x", Integer.valueOf(i));
return true;
}
private static void aE(long j) {
if (j > 10000) {
xe();
}
}
public static void fm(int i) {
if (cWd == 0) {
x.e("MicroMsg.BlinkStartup", "sLastPhaseTimestamp is 0");
return;
}
long currentTimeMillis = System.currentTimeMillis() - cWd;
switch (i) {
case 1:
if (fl(1)) {
a(cVO, currentTimeMillis);
cWd = System.currentTimeMillis();
return;
}
return;
case 2:
if (fl(2)) {
a(cVP, currentTimeMillis);
cWd = System.currentTimeMillis();
return;
}
return;
case 3:
if (fl(4)) {
a(cVQ, currentTimeMillis);
cWd = System.currentTimeMillis();
return;
}
return;
case 4:
if (fl(8)) {
a(cVR, currentTimeMillis);
cWd = System.currentTimeMillis();
return;
}
return;
case 5:
if (fl(16)) {
aE(currentTimeMillis);
a(cVS, currentTimeMillis);
cWd = System.currentTimeMillis();
return;
}
return;
case 6:
if (fl(32)) {
aE(currentTimeMillis);
a(cVT, currentTimeMillis);
cWd = System.currentTimeMillis();
return;
}
return;
default:
return;
}
}
public static void xg() {
long currentTimeMillis = System.currentTimeMillis() - cWc;
a(cVU, currentTimeMillis);
if (currentTimeMillis <= 3000) {
a(cVV, 1);
} else if (currentTimeMillis > 3000 && currentTimeMillis <= 6000) {
a(cVW, 1);
} else if (currentTimeMillis <= 6000 || currentTimeMillis > 10000) {
a(cVY, 1);
} else {
a(cVX, 1);
}
a(cVN, 1);
}
public static ArrayList<long[]> xh() {
return cVZ;
}
}
|
/*
Java Power Info utility, (C)2021 IC Book Labs
Table model for Tree Monitor (text table built), abstract class
*/
package powerinfo;
import javax.swing.table.AbstractTableModel;
import javax.swing.tree.TreePath;
public abstract class TreeMonitor
{
public abstract AbstractTableModel getTableModelByPath( TreePath x );
}
|
/*
* Copyright (c) 2015. ReviewBot by Jeremy Tidwell is licensed under a Creative Commons
* Attribution-NonCommercial-ShareAlike 4.0 International License.
* Based on a work at https://github.com/necanthrope/ReviewBot.
*/
package reviewbot.repository.metadata;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.stereotype.Repository;
import reviewbot.entity.Book;
import reviewbot.entity.GenreMap;
import reviewbot.entity.metadata.Subgenre;
import reviewbot.repository.AbstractRepository;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
/**
* Created by jtidwell on 4/8/2015.
*/
@Repository
@Transactional
public class SubgenreRepository extends AbstractRepository<Subgenre> {
@Override
public Subgenre create(Subgenre subgenre) {
getCurrentSession().save(subgenre);
return subgenre;
}
@Override
public List<Subgenre> readAll() {
return _entityManager.createQuery("from Subgenre").getResultList();
}
@Override
public List<Subgenre> readRange(Integer offset, Integer length) {
final Integer len = length;
final Integer offs = offset;
List<Subgenre> subgenreEntities = (List<Subgenre>) getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
Query q = getSessionFactory().getCurrentSession().createQuery("from Subgenre");
q.setFirstResult(offs);
q.setMaxResults(len);
return q.list();
}
});
List<Subgenre> subgenres = new ArrayList<Subgenre>();
for (Subgenre subgenre : subgenreEntities) {
subgenres.add(subgenre);
}
return subgenres;
}
@Override
public Subgenre readOne(Integer id) {
return readOneEntity(id);
}
public Subgenre readOneEntity(Integer id) {
if (id == null)
return new Subgenre();
return (Subgenre) getCurrentSession().get(Subgenre.class, id);
}
@SuppressWarnings("unchecked")
@Override
public List<Subgenre> readList(Integer[] idsIn) {
final Integer[] ids = idsIn;
List<Subgenre> subgenreEntities = (List<Subgenre>) getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
Criteria criteria = session.createCriteria(Subgenre.class);
criteria.add(Restrictions.in("subgenre", ids));
criteria.addOrder(Order.asc("name"));
return criteria.list();
}
});
List<Subgenre> subgenres = new ArrayList<Subgenre>();
for (Subgenre subgenre : subgenreEntities) {
subgenres.add(subgenre);
}
return subgenres;
}
@Override
public Subgenre update(Subgenre inSubgenre) {
Subgenre subgenre = (Subgenre) getCurrentSession().get(Subgenre.class, inSubgenre.getSubgenre());
subgenre.setName(inSubgenre.getName());
subgenre.setDescription(inSubgenre.getDescription());
getCurrentSession().merge(subgenre);
return subgenre;
}
@Override
public void delete(Integer id) {
Subgenre subgenre = (Subgenre) getCurrentSession().get(Subgenre.class, id);
if (subgenre != null) {
getCurrentSession().delete(subgenre);
getCurrentSession().flush();
}
}
}
|
package com.mysql.cj.protocol.a;
import com.mysql.cj.Messages;
import com.mysql.cj.protocol.Message;
import com.mysql.cj.protocol.MessageHeader;
import com.mysql.cj.protocol.MessageReader;
import java.io.IOException;
import java.util.Optional;
public class MultiPacketReader implements MessageReader<NativePacketHeader, NativePacketPayload> {
private MessageReader<NativePacketHeader, NativePacketPayload> packetReader;
public MultiPacketReader(MessageReader<NativePacketHeader, NativePacketPayload> packetReader) {
this.packetReader = packetReader;
}
public NativePacketHeader readHeader() throws IOException {
return (NativePacketHeader)this.packetReader.readHeader();
}
public NativePacketPayload readMessage(Optional<NativePacketPayload> reuse, NativePacketHeader header) throws IOException {
int packetLength = header.getMessageSize();
NativePacketPayload buf = (NativePacketPayload)this.packetReader.readMessage(reuse, header);
if (packetLength == 16777215) {
buf.setPosition(16777215);
NativePacketPayload multiPacket = null;
int multiPacketLength = -1;
byte multiPacketSeq = getMessageSequence();
do {
NativePacketHeader hdr = readHeader();
multiPacketLength = hdr.getMessageSize();
if (multiPacket == null)
multiPacket = new NativePacketPayload(multiPacketLength);
multiPacketSeq = (byte)(multiPacketSeq + 1);
if (multiPacketSeq != hdr.getMessageSequence())
throw new IOException(Messages.getString("PacketReader.10"));
this.packetReader.readMessage(Optional.of(multiPacket), hdr);
buf.writeBytes(NativeConstants.StringLengthDataType.STRING_FIXED, multiPacket.getByteBuffer(), 0, multiPacketLength);
} while (multiPacketLength == 16777215);
buf.setPosition(0);
}
return buf;
}
public byte getMessageSequence() {
return this.packetReader.getMessageSequence();
}
public void resetMessageSequence() {
this.packetReader.resetMessageSequence();
}
public MessageReader<NativePacketHeader, NativePacketPayload> undecorateAll() {
return this.packetReader.undecorateAll();
}
public MessageReader<NativePacketHeader, NativePacketPayload> undecorate() {
return this.packetReader;
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\cj\protocol\a\MultiPacketReader.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ |
package com.ysyt.bean;
import java.io.Serializable;
import java.math.BigInteger;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.hibernate.annotations.Filter;
import org.hibernate.annotations.FilterDef;
import org.hibernate.annotations.FilterDefs;
import com.Util.Util;
import com.constants.CommonConstants;
@Entity
@Table(name = "accomodation_subtypes", schema = CommonConstants.SCHEMA)
public class AccomodationSubTypes implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "id", columnDefinition = "serial")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "sharable_count" )
private Integer sharableCount ;
@Column(name = "sharable_type" )
private String sharableType ;
@Column(name = "accomodation_type_id" )
private Long accomodationTypeId ;
@Column(name = "is_deleted" ,nullable = false ,insertable=false, columnDefinition = "boolean default false")
private Boolean isDeleted ;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getSharableCount() {
return sharableCount;
}
public void setSharableCount(Integer sharableCount) {
this.sharableCount = sharableCount;
}
public String getSharableType() {
return sharableType;
}
public void setSharableType(String sharableType) {
this.sharableType = sharableType;
}
public Long getAccomodationTypeId() {
return accomodationTypeId;
}
public void setAccomodationTypeId(Long accomodationTypeId) {
this.accomodationTypeId = accomodationTypeId;
}
public Boolean getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(Boolean isDeleted) {
this.isDeleted = isDeleted;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
} |
package br.com.conspesca.filter;
import java.io.IOException;
import javax.inject.Inject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import br.com.conspesca.VO.UserSessionVO;
import br.com.conspesca.security.SessionSecurity;
@WebFilter
public class SecurityFilter implements Filter{
@Inject
private SessionSecurity sessionSecurity;
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
if(httpServletRequest.getRequestURI().contains("resource")){
chain.doFilter(request, response);
return;
}
UserSessionVO userAuthentication = this.sessionSecurity.getUserAuthentication();
String paginaAtual = httpServletRequest.getServletPath();
if(userAuthentication==null
&& !paginaAtual.equalsIgnoreCase("/pages/login.xhtml")
&& !paginaAtual.equalsIgnoreCase("/pages/pesquisaprincipal.xhtml")
&& !paginaAtual.equalsIgnoreCase("/pages/map.xhtml")){
String contextPath = httpServletRequest.getContextPath();
httpServletResponse.sendRedirect(contextPath+"/pages/login.xhtml");
return;
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
|
package org.spring.fom.support.task.pool;
import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spring.fom.support.task.parse.IoUtil;
/**
*
* @author shanhm1991@163.com
*
*/
public class JdbcHelper {
protected static final Logger LOG = LoggerFactory.getLogger(JdbcHelper.class);
private static final int MAXLEN = 30;
private static final int BUFFER = 1024;
private static final int COL_TYPE_12 = 12;
private static final int COL_TYPE_2005 = 2005;
private static final int INDEX_DEX = 46;
protected JdbcHelper(){
}
protected final void _startTransaction(String poolName) throws Exception {
JdbcPool pool = getPool(poolName);
JdbcPool.JdbcNode node = (JdbcPool.JdbcNode)pool.acquire();
if(node.isInTransaction){
LOG.warn("transaction started[Connection was already in Transaction]");
return;
}
node.isInTransaction = true;
Connection con = node.v;
try{
con.commit();
con.setAutoCommit(false);
if (LOG.isDebugEnabled()) {
LOG.debug("transaction started");
}
}catch(Exception e){
node.isInTransaction = false;
con.setAutoCommit(true);
pool.release();
LOG.error("transaction start failed", e);
}
}
protected final void _endTransaction(String poolName) throws Exception {
JdbcPool pool = getPool(poolName);
JdbcPool.JdbcNode node = (JdbcPool.JdbcNode)pool.acquire();
if(!node.isInTransaction){
pool.release();
LOG.warn("transaction commit failed[Connection is not in Transaction]");
return;
}
Connection con = node.v;
try{
con.commit();
if (LOG.isDebugEnabled()) {
LOG.debug("transaction commited");
}
}catch(Exception e){
LOG.error("transaction commit failed, rollback now", e);
con.rollback();
}finally{
node.isInTransaction = false;
con.setAutoCommit(true);
pool.release();
}
}
private boolean isInTransaction(JdbcPool pool) throws Exception{
JdbcPool.JdbcNode node = (JdbcPool.JdbcNode)pool.acquire();
return node.isInTransaction;
}
/**
* 取消事务,直接回滚,释放连接
* @param poolName
* @throws Exception
*/
private void cancelTransaction(String poolName) throws Exception {
if(!isInTransaction(getPool(poolName))){
return;
}
JdbcPool pool = getPool(poolName);
try{
JdbcPool.JdbcNode node = (JdbcPool.JdbcNode)pool.acquire();
if(!isInTransaction(getPool(poolName))){
LOG.warn("transaction canceled[Connection was not in Transaction]");
return;
}
Connection con = node.v;
if (LOG.isDebugEnabled()) {
LOG.debug("transaction canceled and rollback");
}
con.rollback();
con.setAutoCommit(true);
}finally{
pool.release();
}
}
protected final List<Map<String, Object>> _queryForList(String poolName, String sql, Map<String, Object> paramMap) throws Exception {
StringBuilder sqlBuilder = new StringBuilder(sql);
Map<String, Integer> indexMap = praseSQL(sqlBuilder);
sql = sqlBuilder.toString();
if(!isInTransaction(getPool(poolName))){
return queryForList(poolName, sql, paramMap, indexMap);
}else{
return queryForListTransaction(poolName, sql, paramMap, indexMap);
}
}
private List<Map<String, Object>> queryForList(String poolName, String sql, Map<String, Object> paramMap, Map<String, Integer> indexMap) throws Exception {
JdbcPool pool = getPool(poolName);
PreparedStatement ps = null;
ResultSet resultSet = null;
try{
Connection con = pool.acquire().v;
ps = con.prepareStatement(sql);
setParams(con, ps, paramMap, indexMap);
if (LOG.isDebugEnabled()) {
LOG.debug("[query]=" + sql);
LOG.debug("[param]=" + logParam(ps, paramMap, indexMap));
}
long eTime = System.currentTimeMillis();
List<Map<String, Object>> list = praseResultSet(ps.executeQuery());
if (LOG.isDebugEnabled()) {
LOG.debug("[affects=" + list.size() + ",cost=" + (System.currentTimeMillis() - eTime) + "ms]");
}
return list;
}finally{
pool.release();
IoUtil.close(resultSet);
IoUtil.close(ps);
}
}
private List<Map<String, Object>> queryForListTransaction(String poolName, String sql, Map<String, Object> paramMap, Map<String, Integer> indexMap) throws Exception {
JdbcPool pool = getPool(poolName);
PreparedStatement ps = null;
ResultSet resultSet = null;
try{
Connection con = pool.acquire().v;
ps = con.prepareStatement(sql);
setParams(con, ps, paramMap, indexMap);
if (LOG.isDebugEnabled()) {
LOG.debug("[query]=" + sql);
LOG.debug("[param]=" + logParam(ps, paramMap, indexMap));
}
long eTime = System.currentTimeMillis();
List<Map<String, Object>> list = praseResultSet(ps.executeQuery());
if (LOG.isDebugEnabled()) {
LOG.debug("[affects=" + list.size() + ",cost=" + (System.currentTimeMillis() - eTime) + "ms]");
}
return list;
}catch(Exception e){
cancelTransaction(poolName);
throw new Exception("transaction faile, data rollbacked", e);
}finally{
IoUtil.close(resultSet);
IoUtil.close(ps);
}
}
protected final int _execute(String poolName, String sql, Map<String, Object> paramMap) throws Exception {
StringBuilder sqlBuilder = new StringBuilder(sql);
Map<String, Integer> indexMap = praseSQL(sqlBuilder);
sql = sqlBuilder.toString();
if(isInTransaction(getPool(poolName))){
return executeTransaction(poolName, sql, paramMap, indexMap);
}else{
return execute(poolName, sql, paramMap, indexMap);
}
}
private int execute(String poolName, String sql, Map<String, Object> paramMap, Map<String, Integer> indexMap) throws Exception {
JdbcPool pool = getPool(poolName);
PreparedStatement ps = null;
try{
Connection con = pool.acquire().v;
ps = con.prepareStatement(sql);
setParams(con, ps, paramMap, indexMap);
if (LOG.isDebugEnabled()) {
LOG.debug("[execute]=" + sql);
LOG.debug("[param]=" + logParam(ps, paramMap, indexMap));
}
long eTime = System.currentTimeMillis();
int num = ps.executeUpdate();
if (LOG.isDebugEnabled()) {
LOG.debug("[affects=" + num + ",cost=" + (System.currentTimeMillis() - eTime) + "ms]");
}
return num;
}finally{
IoUtil.close(ps);
pool.release();
}
}
private int executeTransaction(String poolName, String sql, Map<String, Object> paramMap, Map<String, Integer> indexMap) throws Exception {
PreparedStatement ps = null;
try{
Connection con = getPool(poolName).acquire().v;
ps = con.prepareStatement(sql);
setParams(con, ps, paramMap, indexMap);
if (LOG.isDebugEnabled()) {
LOG.debug("[execute in transaction]=" + sql);
LOG.debug("[param] = " + logParam(ps, paramMap, indexMap));
}
long eTime = System.currentTimeMillis();
int num = ps.executeUpdate();
if (LOG.isDebugEnabled()) {
LOG.debug("[affects=" + num + ",cost=" + (System.currentTimeMillis() - eTime) + "ms]");
}
return num;
}catch(Exception e) {
cancelTransaction(poolName);
throw new Exception("transaction faile, data rollbacked", e);
}finally{
IoUtil.close(ps);
}
}
protected final int[] _batchExecute(String poolName, String sql, List<Map<String, Object>> paramMaps) throws Exception {
StringBuilder sqlBuilder = new StringBuilder(sql);
Map<String, Integer> indexMap = praseSQL(sqlBuilder);
sql = sqlBuilder.toString();
if(isInTransaction(getPool(poolName))){
return batchExecuteTransaction(poolName, sql, paramMaps, indexMap);
}else{
return batchExecute(poolName, sql, paramMaps, indexMap);
}
}
private int[] batchExecute(String poolName, String sql, List<Map<String, Object>> paramMaps, Map<String, Integer> indexMap) throws Exception {
JdbcPool pool = getPool(poolName);
PreparedStatement ps = null;
try{
Connection con = pool.acquire().v;
ps = con.prepareStatement(sql);
for(Map<String, Object> map : paramMaps){
setParams(con, ps, map, indexMap);
ps.addBatch();
}
if (LOG.isDebugEnabled()) {
LOG.debug("[batch execute]=" + sql);
}
long eTime = System.currentTimeMillis();
int[] nums = ps.executeBatch();
int num = 0;
for(int i : nums){
num += i;
}
if (LOG.isDebugEnabled()) {
LOG.debug("[affects=" + num + ",cost=" + (System.currentTimeMillis() - eTime) + "ms]");
}
return nums;
}finally{
IoUtil.close(ps);
pool.release();
}
}
private int[] batchExecuteTransaction(String poolName, String sql, List<Map<String, Object>> paramMaps, Map<String, Integer> indexMap) throws Exception {
PreparedStatement ps = null;
try{
Connection con = getPool(poolName).acquire().v;
ps = con.prepareStatement(sql);
for(Map<String, Object> map : paramMaps){
setParams(con, ps, map, indexMap);
ps.addBatch();
}
if (LOG.isDebugEnabled()) {
LOG.debug("[batch execute in transaction]=" + sql);
}
long eTime = System.currentTimeMillis();
int[] nums = ps.executeBatch();
int num = 0;
for(int i : nums){
num += i;
}
if (LOG.isDebugEnabled()) {
LOG.debug("[affects=" + num + ",cost=" + (System.currentTimeMillis() - eTime) + "ms]");
}
return nums;
}catch(Exception e){
cancelTransaction(poolName);
throw new Exception("transaction faile, data rollbacked", e);
}finally{
IoUtil.close(ps);
}
}
private JdbcPool getPool(String poolName) {
JdbcPool pool = (JdbcPool)PoolManager.get(poolName);
if(pool == null){
throw new RuntimeException("pool[" + poolName + "] not exist.");
}
return pool;
}
private Map<String,Integer> praseSQL(StringBuilder sqlBuilder){
Map<String,Integer> indexMap = new HashMap<String,Integer>();
String sql = sqlBuilder.toString();
if(sql.indexOf("#") == -1){
return indexMap;
}
int index = 0;
while(sql.indexOf("#") != -1){
int start = sql.indexOf("#");
int end = sql.indexOf("#", start + 1);
String key = sql.substring(start + 1, end);
index++;
indexMap.put(key, index);
sql = sql.substring(0, start) + "?" + sql.substring(end + 1);
}
sqlBuilder.delete(0, sqlBuilder.length()).append(sql);
return indexMap;
}
private void setParams(Connection con, PreparedStatement ps, Map<String, Object> paramMap, Map<String, Integer> indexMap) throws Exception{
for(Entry<String, Integer> entry : indexMap.entrySet()){
String key = entry.getKey();
Integer index = entry.getValue();
Object value = paramMap.get(key);
if(value == null){
throw new IllegalArgumentException("param[" + key + "] not valued.");
}
ps.setObject(index, value);
}
}
private String logParam(PreparedStatement ps, Map<String, Object> paramMap, Map<String, Integer> indexMap) {
StringBuilder builder = new StringBuilder("[");
if(indexMap == null || indexMap.isEmpty()){
return builder.append("]").toString();
}else{
int count = 0;
for(Entry<String, Integer> entry : indexMap.entrySet()){
String key = entry.getKey();
builder.append(key);
builder.append("=");
String value = String.valueOf(paramMap.get(key));
if(value.length() > MAXLEN){
value = value.substring(0, MAXLEN) + "...";
}
builder.append(value);
count++;
if(count < indexMap.size()){
builder.append(",");
}
}
}
// 暂时不用AbstractMethodError
// try {
// ParameterMetaData pdata = ps.getParameterMetaData();
// int count = pdata.getParameterCount();
// for(int i = 1; i <= count; i++){
// //String type = pdata.getParameterTypeName(i); 不支持的特性
// String value = getParamValue(i, paramMap, indexMap);
// if(i < count){
// builder.append(value).append(", ");
// continue;
// }
// builder.append(value);
// }
// } catch (SQLException e) {
// LOG.error(e);
// }
return builder.append("]").toString();
}
private List<Map<String, Object>> praseResultSet(ResultSet resultSet) throws SQLException{
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
while (resultSet.next()) {
list.add(praseResult(resultSet));
}
return list;
}
private Map<String, Object> praseResult(ResultSet resultSet) throws SQLException {
Map<String, Object> result = new HashMap<String, Object>();
ResultSetMetaData rsmd = resultSet.getMetaData();
int cols = rsmd.getColumnCount();
for (int i = 1; i <= cols; ++i) {
String colName = rsmd.getColumnLabel(i);
if ((colName == null) || (colName.length() == 0)) {
colName = rsmd.getColumnName(i);
}
Object colValue = resultSet.getObject(i);
int colType = rsmd.getColumnType(i);
if ((colValue == null) && ((1 == colType) || (COL_TYPE_12 == colType) || (-1 == colType))) {
colValue = "";
} else if ((COL_TYPE_2005 == colType) || (Clob.class.isInstance(colValue))) {
colValue = processClob(resultSet.getClob(i));
} else {
colValue = processBigDecimal(colValue, resultSet, i);
}
result.put(colName, colValue);
}
return result;
}
private Object processBigDecimal(Object obj, ResultSet rs, int columIndex) throws SQLException {
if (obj instanceof BigInteger) {
obj = Long.valueOf(((BigInteger) obj).longValue());
} else if (obj instanceof BigDecimal) {
BigDecimal bd = (BigDecimal) obj;
if ((bd.scale() == 0) || (bd.toString().indexOf(INDEX_DEX) == -1)) {
obj = Long.valueOf(bd.longValue());
} else
obj = Float.valueOf(bd.floatValue());
}
return obj;
}
private String processClob(Clob clob) throws SQLException {
if (clob == null) {
return "";
}
BufferedReader reader = new BufferedReader(clob.getCharacterStream());
StringBuilder sb = new StringBuilder("");
if (reader != null) {
try {
char[] buffer = new char[BUFFER];
int c = -1;
while ((c = reader.read(buffer)) != -1)
sb.append(buffer, 0, c);
} catch (IOException e) {
LOG.error("", e);
} finally {
IoUtil.close(reader);
}
}
return sb.toString();
}
}
|
package org.milvus.regex.syntax;
public abstract class Regex {
public final RegexType type;
public Regex(RegexType type) {
this.type = type;
}
}
|
/*
* UniTime 3.2 - 3.5 (University Timetabling Application)
* Copyright (C) 2008 - 2013, UniTime LLC, and individual contributors
* as indicated by the @authors tag.
*
* 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 org.unitime.timetable.form;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionMapping;
import org.unitime.timetable.security.SessionContext;
/**
* @author Tomas Muller
*/
public class ExamChangesForm extends ExamReportForm {
private static final long serialVersionUID = 4093360180461644275L;
private String iChage = sChangeInitial;
public static final String sChangeInitial = "Initial";
public static final String sChangeBest = "Best";
public static final String sChangeSaved = "Saved";
public static final String[] sChanges = new String[] { sChangeInitial, sChangeBest, sChangeSaved };
private boolean iReverse = false;
private boolean iNoSolver = false;
public boolean getReverse() { return iReverse; }
public void setReverse(boolean reverse) { iReverse = reverse; }
public String getChangeType() { return iChage; }
public void setChangeType(String changeType) { iChage = changeType; }
public String[] getChangeTypes() { return sChanges; }
public void reset(ActionMapping mapping, HttpServletRequest request) {
super.reset(mapping, request);
iChage = sChangeInitial; iReverse = false;
}
public void load(SessionContext session) {
super.load(session);
setReverse("1".equals(session.getUser().getProperty("ExamChanges.reverse", "0")));
setChangeType(session.getUser().getProperty("ExamChanges.changeType", sChangeInitial));
}
public void save(SessionContext session) {
super.save(session);
session.getUser().setProperty("ExamChanges.reverse", getReverse() ? "1" : "0");
session.getUser().setProperty("ExamChanges.changeType", getChangeType());
}
public boolean getNoSolver() { return iNoSolver;}
public void setNoSolver(boolean noSolver) { iNoSolver = noSolver;}
}
|
package stepDefinition;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import pageObjects.DynamicLoadingExample1Page;
import pageObjects.DynamicLoadingExample2Page;
import pageObjects.DynamicLoadingPage;
import utils.TestContext;
import static org.testng.Assert.*;
public class NavigationSteps
{
private TestContext testContext;
private DynamicLoadingPage dynamicLoadingPage;
private DynamicLoadingExample1Page example1Page;
private DynamicLoadingExample2Page example2Page;
public NavigationSteps(TestContext context)
{
testContext = context;
dynamicLoadingPage = testContext.getPageObjectManager().getDynamicLoadingPage();
example1Page = testContext.getPageObjectManager().getDynamicLoadingExample1Page();
example2Page = testContext.getPageObjectManager().getDynamicLoadingExample2Page();
}
@When("^the user opens the Example 2 link in a new tab$")
public void theUserOpensTheExample2LinkInANewTab()
{
dynamicLoadingPage.openExample2NewTab();
testContext.getWindowManager().switchToNewTab();
}
@When("the user visits the Example 1 page")
public void theUserVisitsTheExample1Page()
{
dynamicLoadingPage.clickExample1();
}
@Then("^the user sees the Example 1 page$")
public void theUserSeesTheExample1Page()
{
assertEquals(example1Page.getTitle(), "Example 1: Element on page that is hidden", "Correct page not displayed");
}
@Then("^the start button is displayed on the page in the new tab$")
public void theStartButtonIsDisplayedOnThePageInTheNewTab()
{
assertTrue(example2Page.isStartButtonDisplayed(), "Start button is not displayed");
}
@And("backtracks and refreshes the page then navigates forward")
public void backtracksAndRefreshesThePageThenNavigatesForward()
{
testContext.getWindowManager().goBack();
testContext.getWindowManager().refreshPage();
testContext.getWindowManager().goForward();
}
}
|
package CSArmyBot.commands;
import java.awt.Color;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.List;
import com.jagrosh.jdautilities.command.Command;
import com.jagrosh.jdautilities.command.CommandEvent;
import CSArmyBot.main;
import net.dv8tion.jda.core.EmbedBuilder;
public class ListBlockedLinksCommand extends Command{
public ListBlockedLinksCommand() {
this.name = "showlinks";
this.help = "Show which types of links are blocked";
this.requiredRole = main.requiredRole;
this.category = main.STAFF;
}
@Override
protected void execute(CommandEvent event) {
List<String> links = new ArrayList<String>(main.userData.get("links").values());
EmbedBuilder linksembed = new EmbedBuilder();
linksembed.setColor(Color.green);
linksembed.setTimestamp(OffsetDateTime.now());
linksembed.setTitle("Blocked Links");
for (int x = 0; x < links.size(); x++ ) {
linksembed.getDescriptionBuilder()
.append("\n" + (x+1) + ". `" + links.get(x) + "`");
}
linksembed.appendDescription("\n");
event.reply(linksembed.build());
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Intrumentos_Virtuales;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.awt.GraphicsConfiguration;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
public class Tanque{
//double ancho_ventana =
double nivel = 0;
Container c;
Graphics2D g;
public BufferedImage im;
int ancho;
int largo;
String titulo1;
Icon icono;
int max_val;
public Tanque(String title, int x, int y, int nivl, int max) {
ancho = x;
largo = y;
nivel = nivl;
titulo1 = title;
max_val = max;
im = new BufferedImage(x,y,BufferedImage.TYPE_INT_BGR);
g = im.createGraphics();
paint(g);
icono = new ImageIcon(im);
}
public void paint (Graphics g){
//Variables
//Ventana
int ancho_ventana = ancho;
int alto_ventana = largo;
//rectangulo exterior
float ancho_linea_ext = 5.0f;
int in_rect_ex_x = 5;
int in_rect_ex_y = in_rect_ex_x + 25;
int ancho_rectangulo_ext = ancho_ventana-in_rect_ex_x-in_rect_ex_x;
int alto_rectangulo_ext = alto_ventana-in_rect_ex_y-in_rect_ex_x;
Color color_rec_ext = Color.GRAY;
//Texto titulo
String titulo = titulo1;
String tipo_letra = "Arial";
int tamaño_letra = 20;
Color color_letra = Color.BLACK;
int ajuste_letra = 6;
//tanque
int margen_tank = 45;
int marg_alto_tank = 15;
int ini_tank_x = in_rect_ex_x + margen_tank;
int ini_tank_y = in_rect_ex_y + margen_tank-marg_alto_tank;
int ancho_tank = ancho_rectangulo_ext-2*margen_tank-(int)ancho_linea_ext/2;
int alto_tank = alto_rectangulo_ext -2*margen_tank + (int)2.0*marg_alto_tank;
Color color_lin_tank = Color.LIGHT_GRAY;
float ancho_linea_tank = 6.0f;
//Relleno tanque
int min_niv_tank_r = 0;
int max_niv_tank_r = alto_tank;
int max_niv_tank_g = max_val;//500;
float unidad_niv_tank = (float)max_niv_tank_r/max_niv_tank_g;
int nivel11 = (int)nivel;
if(nivel>max_niv_tank_g){
nivel11=max_niv_tank_g;
}
float nivel_tank = nivel11*unidad_niv_tank;
float nivel1 = ini_tank_y + alto_tank - nivel_tank;
//Indicador de nivel
Color color_letra_ind = Color.CYAN;
int tamaño_letra_ind = 12;
String tipo_letra_ind = "Arial";
int ajuste_letra_ind = 1;
String unidades = "mm³";
//Indicador escala
int cant = 10;
int val_esc = (int)max_niv_tank_g/cant;
int nivel_es;
float coor_nivel=0;
float coor_nivel2 = 0;
String esc_niv_g ;
int ajuste_esc = 20;
Color color_ind_esc = Color.BLACK;
//------------------------------------------------------------------
//Inicio ventana grafica
Graphics2D g2 = (Graphics2D)g;
//-------------------------------------------------------------------
//Fondo Ventana grafica
Color color = new Color(240,240,240,231);
//AlphaComposite acc =
//AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f);
g2.setColor(color);
Rectangle2D q22 = new Rectangle2D.Double(
0, 0, ancho, largo);
//g2.setComposite(acc);
g2.fill(q22);
//-------------------------------------------------------------------
//Divujo el rectangulo exterior
g2.setColor(color_rec_ext);
Rectangle2D r2 = new Rectangle2D.Double(in_rect_ex_x, in_rect_ex_y,
ancho_rectangulo_ext, alto_rectangulo_ext);
Stroke pincel = new BasicStroke(ancho_linea_ext, BasicStroke.CAP_ROUND,
BasicStroke.CAP_ROUND);//JOIN_MITER
g2.setStroke(pincel);
g2.draw(r2);//Colorea la linea
//Titulo
FontRenderContext frc = g2.getFontRenderContext();
//Dimension tamaño = getSize();
Font f = new Font(tipo_letra, Font.CENTER_BASELINE, tamaño_letra);
TextLayout tl = new TextLayout(titulo, f, frc);
g2.setColor(color_letra);
tl.draw(g2, (float)(ancho - tl.getBounds().getWidth())/2,
in_rect_ex_x+ancho_linea_ext+ajuste_letra);
// Dibujo del rectángulo redondeado (Tanque)
g2.setColor(color_lin_tank);
g2.setStroke(new BasicStroke(ancho_linea_tank));
RoundRectangle2D q = new RoundRectangle2D.Float(
ini_tank_x, ini_tank_y, ancho_tank, alto_tank, 25.0f, 25.0f);
g2.draw(q);
//Dibujo el relleno del tanque
//Coloreo el interior del rectangulo
AlphaComposite ac =
AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.9f);
g2.setColor(Color.BLUE);
RoundRectangle2D q2 = new RoundRectangle2D.Float(
ini_tank_x, nivel1, ancho_tank, alto_tank, 25.0f, 25.0f);
g2.setComposite(ac);
Area a1 = new Area(q);
Area a2 = new Area(q2);
a1.intersect(a2);
g2.fill(a1); //Colorea el fondo, (llenar) fondo
// Dibujo del rectángulo redondeado (Tanque)
g2.setColor(color_lin_tank);
g2.draw(q);
//Indicador de nivel
Font f1 = new Font(tipo_letra_ind, Font.CENTER_BASELINE, tamaño_letra_ind);
TextLayout tl1 = new TextLayout(Double.toString(nivel)+unidades, f1, frc);
g2.setColor(color_letra_ind);
tl1.draw(g2, (float)(ancho - tl1.getBounds().getWidth())/2,
(float)(in_rect_ex_x+alto_tank-ajuste_letra_ind));
//Indicador escala
Font f2 = new Font(tipo_letra_ind, Font.CENTER_BASELINE, 12);
for(int i = 0;i<=cant+1; i++){
nivel_es = val_esc*i;
coor_nivel = ini_tank_y + alto_tank - nivel_es*unidad_niv_tank;
esc_niv_g = Integer.toString(nivel_es);
if(i<=cant){
TextLayout tl2 = new TextLayout(esc_niv_g+"__", f2, frc);
g2.setColor(color_ind_esc);
tl2.draw(g2, (float)(ancho - tl2.getBounds().getWidth())/2-ancho_tank/2-ajuste_esc,
coor_nivel);
}
if(i>0){
TextLayout tl3 = new TextLayout("_", f2, frc);
g2.setColor(color_ind_esc);
tl3.draw(g2, (float)(ancho - tl3.getBounds().getWidth())/2-ancho_tank/2-ajuste_esc+10,
(coor_nivel2-(coor_nivel-coor_nivel2)/2));
coor_nivel2 = coor_nivel;
}
}
//Indicador leds
}
}
|
package com.ewisnor.randomur.iface;
import android.graphics.Bitmap;
/**
* Implementers may receive a Bitmap of an image once it has been downloaded.
*
* Created by evan on 2015-01-04.
*/
public interface OnImageDownloadedListener {
/**
* Handle a downloaded image in Bitmap form.
* @param image image bitmap
*/
void OnImageDownloaded(Bitmap image);
}
|
package excercie;
import java.util.Arrays;
public class test {
public static void main(String[] args) {
int a[] = {22,33,66,88,11};
Arrays.sort(a);
System.out.println(Arrays.toString(a));
min(a);
max(a);
//pour crée Array
int[] b = new int[3];
System.arraycopy(a, 0, b, 0, 3);
//pour print le array
System.out.println(Arrays.toString(b));
}
static void min(int arr[]){
int min = arr[0];
for (int i = 1 ;i<arr.length;i++){
if (min>arr[i]){
min = arr[i];
}
}System.out.println(min);
}
static void max(int arr[]){
int max = arr[0];
for (int i = 1;i<arr.length;i++){
if (max<arr[i]){
max = arr[i] ;
}
}System.out.println(max);
}
//pour copy 1 arr a l'autre
}
|
package mude.srl.ssc.service.payload;
import mude.srl.ssc.rest.controller.command.model.RequestCommandResourceReservation;
public interface RemoteService {
RequestCommandResourceReservation validatePayload(String payload,String requestFrom) throws Exception;
}
|
package com.github.emailtohl.integration.core.common;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* 符合Ztree的数据结构
*
* @author HeLei
*/
public class ZtreeNode implements Serializable {
private static final long serialVersionUID = -7530502845259404928L;
/**
* 自定义属性,用于唯一识别本类的实例
*/
protected final String key;
/**
* 自定义属性,用于标识查询结果
*/
protected boolean selected;
/**
* 节点名称。如果不使用 name 属性保存节点名称,请修改 setting.data.key.name
* 默认值:无
*/
protected String name;
/**
* 记录 treeNode 节点是否为父节点。
* 1、初始化节点数据时,根据 treeNode.children 属性判断,有子节点则设置为 true,否则为 false
* 2、初始化节点数据时,如果设定 treeNode.isParent = true,即使无子节点数据,也会设置为父节点
*/
protected boolean isParent = false;
/**
* 记录 treeNode 节点的 展开 / 折叠 状态。
* 默认值:false
*/
protected boolean open = false;
/**
* 节点的子节点数据集合。如果不使用 children 属性保存子节点数据,请修改 setting.data.key.children
* 默认值:无
*/
protected List<ZtreeNode> children = new ArrayList<ZtreeNode>();
/**
* 节点的 checkBox / radio 的 勾选状态。[setting.check.enable = true & treeNode.nocheck =
* false 时有效]
* 1、如果不使用 checked 属性设置勾选状态,请修改 setting.data.key.checked
* 2、建立 treeNode 数据时设置 treeNode.checked = true 可以让节点的输入框默认为勾选状态
* 3、修改节点勾选状态,可以使用 treeObj.checkNode / checkAllNodes / updateNode
* 方法,具体使用哪种请根据自己的需求而定
* 默认值:false
*/
protected boolean checked = false;
/**
* 1、设置节点的 checkbox / radio 是否禁用 [setting.check.enable = true 时有效]
* 2、为了解决部分朋友生成 json 数据出现的兼容问题, 支持 "false","true" 字符串格式的数据
* 3、请勿对已加载的节点修改此属性,禁止 或 取消禁止 请使用 setChkDisabled() 方法
* 4、初始化时,如果需要子孙节点继承父节点的 chkDisabled 属性,请设置 setting.check.chkDisabledInherit 属性
* 默认值:false
*/
protected boolean chkDisabled = false;
/**
* 最简单的 click 事件操作。相当于 onclick="..." 的内容。 如果操作较复杂,请使用 onClick 事件回调函数。
* 默认值:无
*/
protected String click;
/**
* 强制节点的 checkBox / radio 的 半勾选状态。[setting.check.enable = true &
* treeNode.nocheck = false 时有效]
* 1、强制为半勾选状态后,不再进行自动计算半勾选状态
* 2、设置 treeNode.halfCheck = false 或 null 才能恢复自动计算半勾选状态
*/
protected boolean halfCheck = false;
/**
* 节点自定义图标的 URL 路径。
* 1、父节点如果只设置 icon ,会导致展开、折叠时都使用同一个图标
* 2、父节点展开、折叠使用不同的个性化图标需要同时设置 treeNode.iconOpen / treeNode.iconClose 两个属性
* 3、如果想利用 className 设置个性化图标,需要设置 treeNode.iconSkin 属性
* 默认值:无
*/
protected String icon;
/**
* 父节点自定义折叠时图标的 URL 路径。
* 1、此属性只针对父节点有效
* 2、此属性必须与 iconOpen 同时使用
* 3、如果想利用 className 设置个性化图标,需要设置 treeNode.iconSkin 属性
* 默认值:无
*/
protected String iconClose;
/**
* 父节点自定义展开时图标的 URL 路径。
* 1、此属性只针对父节点有效
* 2、此属性必须与 iconClose 同时使用
* 3、如果想利用 className 设置个性化图标,需要设置 treeNode.iconSkin 属性
* 默认值:无
*/
protected String iconOpen;
/**
* 节点自定义图标的 className
* 默认值:无
*/
protected String iconSkin;
/**
* 判断 treeNode 节点是否被隐藏。
* 1、初始化 zTree 时,如果节点设置 isHidden = true,会被自动隐藏
* 2、请勿对已加载的节点修改此属性,隐藏 / 显示 请使用 hideNode() / hideNodes() / showNode() /
* showNodes() 方法
*/
protected Boolean isHidden = null;
/**
* 设置节点是否隐藏 checkbox / radio [setting.check.enable = true 时有效]
* 默认值:false
*/
protected boolean nocheck = false;
/**
* 设置点击节点后在何处打开 url。[treeNode.url 存在时有效]
* 默认值:无
*/
protected String target;
/**
* 节点链接的目标 URL
* 1、编辑模式 (setting.edit.enable = true) 下此属性功能失效,如果必须使用类似功能,请利用 onClick
* 事件回调函数自行控制。
* 2、如果需要在 onClick 事件回调函数中进行跳转控制,那么请将 URL 地址保存在其他自定义的属性内,请勿使用 url
* 默认值:无
*/
protected String url;
/**
* 自定义挂载的数据信息
*/
protected Object attribute;
public String getKey() {
return key;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isParent() {
return isParent;
}
public void setParent(boolean isParent) {
this.isParent = isParent;
}
public boolean isOpen() {
return open;
}
public void setOpen(boolean open) {
this.open = open;
}
public List<ZtreeNode> getChildren() {
return children;
}
public void setChildren(List<ZtreeNode> children) {
this.children = children;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public boolean isChkDisabled() {
return chkDisabled;
}
public void setChkDisabled(boolean chkDisabled) {
this.chkDisabled = chkDisabled;
}
public String getClick() {
return click;
}
public void setClick(String click) {
this.click = click;
}
public boolean isHalfCheck() {
return halfCheck;
}
public void setHalfCheck(boolean halfCheck) {
this.halfCheck = halfCheck;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getIconClose() {
return iconClose;
}
public void setIconClose(String iconClose) {
this.iconClose = iconClose;
}
public String getIconOpen() {
return iconOpen;
}
public void setIconOpen(String iconOpen) {
this.iconOpen = iconOpen;
}
public String getIconSkin() {
return iconSkin;
}
public void setIconSkin(String iconSkin) {
this.iconSkin = iconSkin;
}
public Boolean getIsHidden() {
return isHidden;
}
public void setIsHidden(Boolean isHidden) {
this.isHidden = isHidden;
}
public boolean isNocheck() {
return nocheck;
}
public void setNocheck(boolean nocheck) {
this.nocheck = nocheck;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Object getAttribute() {
return attribute;
}
public void setAttribute(Object attribute) {
this.attribute = attribute;
}
/**
* 构造
* @param key
*/
public ZtreeNode(String key) {
this.key = key;
}
/**
* 构造
* @param key
*/
public ZtreeNode(String key, String name) {
this(key);
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((key == null) ? 0 : key.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ZtreeNode other = (ZtreeNode) obj;
if (key == null) {
if (other.key != null)
return false;
} else if (!key.equals(other.key))
return false;
return true;
}
@Override
public String toString() {
return "ZtreeNode [key=" + key + ", name=" + name + ", isParent=" + isParent + ", children=" + children
+ ", open=" + open + "]";
}
}
|
package com.jkxy.web.interceptor;
import java.util.Map;
import com.jkxy.web.model.User;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class LoginCheck extends AbstractInterceptor{
@Override
public String intercept(ActionInvocation arg0) throws Exception {
Map session = arg0.getInvocationContext().getSession();
User user = (User)session.get("user");
if(user==null){
return "login";
}
return arg0.invoke();
}
}
|
public class BankAccount
{
private double banlance;
private String owner;
private int accountNum;
public BankAccount()
{
//Negative one means no account given
this(0.0, " ", -1);
}
public BankAccount (double banlance, String owner, int accountNum)
{
this.banlance = banlance;
this.owner = owner;
this.accountNum = accountNum;
}
//Those are the getters
public double getBanlance ()
{
return this.banlance;
}
public String getOwner ()
{
return this.owner;
}
public int getAccountNum ()
{
return this.accountNum;
}
//Those are the setters
public void setOwner (String owner)
{
this.owner = owner;
}
public void setAccountNum (int accountNum)
{
this.accountNum = accountNum;
}
public void deposit (double amonut)
{
this.banlance += amount;
}
public int withdrow (double amount)
{
int returnValue = 0;
if ((this.banlance - amount) < 0)
{
//This method will return -1 if there is no enough banlance
returnValue = -1;
}
else
{
this.banlacne -= amount;
}
return returnValue;
}
} |
package com.epam.guest.mapper;
import com.epam.guest.models.dto.AddressResourceDTO;
import com.epam.guest.models.dto.GuestResourceDTO;
import com.epam.guest.models.entity.AddressEntity;
import com.epam.guest.models.entity.GuestEntity;
import java.util.Optional;
/**
* The interface Guest mapper.
*/
public class GuestMapper {
/**
* To guest resource guest resource dto.
*
* @param guestEntity the guest
* @return the guest resource dto
*/
public static GuestResourceDTO toGuestResource(final GuestEntity guestEntity) {
return GuestResourceDTO.builder()
.guestId(Optional.ofNullable(guestEntity.getId()).orElse(null))
.firstName(guestEntity.getFirstName())
.lastName(guestEntity.getLastName())
.address(toAddressResource(guestEntity.getAddress()))
.email(guestEntity.getEmail())
.mobile(guestEntity.getMobile())
.build();
}
/**
* To address resource address resource dto.
*
* @param addressEntity the address
* @return the address resource dto
*/
public static AddressResourceDTO toAddressResource(final AddressEntity addressEntity) {
return AddressResourceDTO.builder()
.buildingName(addressEntity.getBuildingName())
.city(addressEntity.getCity())
.state(addressEntity.getState())
.country(addressEntity.getCountry())
.postalCode(addressEntity.getPostalCode())
.build();
}
/**
* To guest guest.
*
* @param guestResourceDTO the guest resource dto
* @return the guest
*/
public static GuestEntity toGuest(final GuestResourceDTO guestResourceDTO) {
return GuestEntity.builder()
.firstName(guestResourceDTO.getFirstName())
.lastName(guestResourceDTO.getLastName())
.email(guestResourceDTO.getEmail())
.mobile(guestResourceDTO.getMobile())
.address(toAddress(guestResourceDTO.getAddress()))
.build();
}
/**
* To address address.
*
* @param addressResourceDTO the address resource dto
* @return the address
*/
public static AddressEntity toAddress(final AddressResourceDTO addressResourceDTO) {
return AddressEntity.builder()
.buildingName(addressResourceDTO.getBuildingName())
.city(addressResourceDTO.getCity())
.state(addressResourceDTO.getState())
.country(addressResourceDTO.getCountry())
.postalCode(addressResourceDTO.getPostalCode())
.build();
}
}
|
package com.sdk4.boot.enums;
import lombok.Getter;
@Getter
public enum SmsCodeStatusEnum {
/**
* 已发送待验证
*/
PENDING(10, "待验证"),
/**
* 验证成功
*/
SUCCESS(20, "验证成功"),
/**
* 发送或验证失败
*/
FAIL(40, "发送或验证失败");
private int code;
private String text;
SmsCodeStatusEnum(int code, String text) {
this.code = code;
this.text = text;
}
}
|
import org.junit.Assert;
import org.junit.Test;
public class CalculatorTest {
@Test
public void additionByteCheck() {
Assert.assertEquals(Calculator.getIntResult("+",10,20), (byte)30, 0);
}
@Test
public void additionIntCheck() {
Assert.assertEquals(Calculator.getIntResult("+",100,-100), 0, 0);
}
@Test
public void additionIntSecondCheck() {
Assert.assertEquals(Calculator.getIntResult("+",100,20), 120, 0);
}
@Test
public void additionDoubleCheck() {
Assert.assertEquals(Calculator.getDoubleResult("+",100.879,200.245), 301.124, 0);
}
@Test
public void subtractionDoubleCheck() {
Assert.assertEquals(Calculator.getDoubleResult("-",100.55,100.45), 0.1, 0.01);
}
@Test
public void subtractionIntCheck() {
Assert.assertEquals(Calculator.getIntResult("-",500,100), 400, 0);
}
@Test
public void subtractionByteCheck() {
Assert.assertEquals(Calculator.getIntResult("-",50,100), (byte)-50, 0);
}
@Test
public void multiplicationDoubleCheck() {
Assert.assertEquals(Calculator.getDoubleResult("*",4.5,2.5), 11.25, 0);
}
@Test
public void multiplicationIntCheck() {
Assert.assertEquals(Calculator.getIntResult("*",500,100), 50000, 0);
}
@Test
public void multiplicationByteCheck() {
Assert.assertEquals(Calculator.getIntResult("*",50,2), (byte)100, 0);
}
@Test
public void divisionDoubleCheck() {
Assert.assertEquals(Calculator.getDoubleResult("/",4.5,1.25), 3.6, 0);
}
@Test
public void divisionIntCheck() {
Assert.assertEquals(Calculator.getIntResult("/",500,100), 5, 0);
}
@Test
public void divisionByteCheck() {
Assert.assertEquals(Calculator.getIntResult("/",50,2), (byte)25, 0);
}
@Test
public void divisionByZeroCheck() {
try {
Assert.assertEquals(Calculator.getIntResult("/", 50, 0), 0, 0);
Assert.fail("ArithmeticException");
} catch (ArithmeticException e) {
System.out.println("Error: " + e);
}
}
@Test
public void multiplicationByteOutOfRange() {
try {
Assert.assertEquals(Calculator.getIntResult("*", (byte)50, (byte)50), (byte)2500, 0);
Assert.fail("AssertionError");
} catch (AssertionError e) {
System.out.println("Error: " + e);
}
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi.p;
import com.tencent.mm.plugin.appbrand.jsapi.base.b;
import org.json.JSONObject;
public final class g extends b {
public static final int CTRL_INDEX = 299;
public static final String NAME = "removeHTMLWebView";
protected final int k(JSONObject jSONObject) {
return jSONObject.getInt("htmlId");
}
}
|
package controler;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Iterator;
import model.ChefMagasin;
import model.ChefRayon;
import model.Rayon;
public class gestionUtilisateur {
public static void ajouterChefRayon(String nom, String prenom, String motDePasse, int IDChefMagasin, String nomRayon) {
Iterator<Rayon> iter = RayonDAO.returnAllRayon().iterator();
Rayon tmp;
Rayon rayon = new Rayon();
while(iter.hasNext()) {
tmp = iter.next();
if(tmp.getNom() == nomRayon) {
rayon = tmp;
}
}
ChefMagasin chefMagasin = ChefMagasinDAO.rechercheChefMagasinById(IDChefMagasin);
ChefRayon chefRayon = new ChefRayon(ChefRayonDAO.returnMaxIDChefRayon(), nom, prenom, motDePasse, chefMagasin, rayon);
RayonDAO.ajouterRayonChefRayon(rayon, chefRayon);
ChefRayonDAO.ajouterChefRayon(chefRayon);
}
public static void modifierChefRayon(int idChefRayon, String nom, String prenom, String motDePasse, int IDChefMagasin, String nomRayon) {
Iterator<Rayon> iter = RayonDAO.returnAllRayon().iterator();
Rayon tmp;
Rayon rayon = new Rayon();
while(iter.hasNext()) {
tmp = iter.next();
if(tmp.getNom() == nomRayon) {
rayon = tmp;
}
}
ChefRayon chefRayon = ChefRayonDAO.rechercheChefRayonById(idChefRayon);
chefRayon.setIDChefMagasin(ChefMagasinDAO.rechercheChefMagasinById(IDChefMagasin));
chefRayon.setIDRayon(rayon);
chefRayon.setMotDePasse(motDePasse);
chefRayon.setNom(nom);
chefRayon.setPrenom(prenom);
ChefRayonDAO.modifierChefRayon(idChefRayon, chefRayon);
}
public static int nombreChefRayon() {
return getChefRayon().size();
}
public static void supprimerChefRayon(int IDChefRayon) {
ChefRayonDAO.supprimerChefRayon(ChefRayonDAO.rechercheChefRayonById(IDChefRayon));
}
public static ArrayList<ChefRayon> getChefRayon(){
return ChefRayonDAO.returnAllChefRayon();
}
public static void changerMDP (int IDChefRayon, boolean isChefMagasin, String motDePasse) {
if(isChefMagasin) {
ChefMagasin chefMagasin = ChefMagasinDAO.rechercheChefMagasinById(IDChefRayon);
chefMagasin.setMotDePasse(motDePasse);
ChefMagasinDAO.modifierChefMagasin(IDChefRayon, chefMagasin);
}
else {
ChefRayon chefRayon = ChefRayonDAO.rechercheChefRayonById(IDChefRayon);
chefRayon.setMotDePasse(motDePasse);
ChefRayonDAO.modifierChefRayon(IDChefRayon, chefRayon);
}
}
public static int authentification (int idUser, String password, boolean isChefMagasin) {
if(isChefMagasin) {
ChefMagasin chefMagasin = ChefMagasinDAO.rechercheChefMagasinById(idUser);
if(password.equals(chefMagasin.getMotDePasse())) {
return idUser;
}
}
else {
ChefRayon chefRayon = ChefRayonDAO.rechercheChefRayonById(idUser);
if(password.equals(chefRayon.getMotDePasse())) {
return idUser;
}
}
return -1;
}
public static int getRayonChefRayon(int idUser) {
ChefRayon chefRayon = ChefRayonDAO.rechercheChefRayonById(idUser);
return chefRayon.getIDRayon().getIDRayon();
}
}
|
package com.example.legia.mobileweb;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.Toast;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.sdsmdg.tastytoast.TastyToast;
public class scancode extends AppCompatActivity {
Button btnQRCode, btnBarcode;
private IntentIntegrator qrScan;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scancode);
btnBarcode = findViewById(R.id.btnBarcode);
btnQRCode = findViewById(R.id.btnQRCode);
btnQRCode.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
qrScan = new IntentIntegrator(scancode.this);
qrScan.initiateScan();
}
});
btnBarcode.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
qrScan = new IntentIntegrator(scancode.this);
qrScan.initiateScan();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (scanningResult != null) {
// show result
final String stringResult = scanningResult.getContents();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Kết quả");
builder.setNegativeButton("Thử lại", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
return;
}
});
builder.setPositiveButton("Đến url", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(URLUtil.isValidUrl(stringResult)){
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(stringResult));
startActivity(browserIntent);
}
else {
TastyToast.makeText(scancode.this, "Kết quả không phải đường dẫn web", TastyToast.LENGTH_SHORT, TastyToast.WARNING).show();
}
}
});
builder.setMessage(stringResult);
AlertDialog alert = builder.create();
alert.show();
}
else{
Toast toast = Toast.makeText(getApplicationContext(),
"Không nhận được kết quả", Toast.LENGTH_SHORT);
toast.show();
}
}
}
|
package de.jmda.fx.cdi.viewtemplate;
import de.jmda.fx.cdi.FXAppRunner;
/**
* Starts {@link ViewApp} by invoking {@link FXAppRunner#run(Class, String[])} from {@link #main(String[])}.
*
* @author ruu@jmda.de
*/
public class ViewAppRunner
{
public static void main(String[] args)
{
FXAppRunner.run(ViewApp.class, args);
}
} |
package com.goodhealth.algorithm.lambda;
import com.goodhealth.algorithm.Jackson_FastJson.Student;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.*;
/**
* @Description
* @Author WDH
* @Date 2019/9/19 14:57
**/
public class FunctionInterface {
public static void main(String[] args){
unaryOperator();
}
/**
* public interface Supplier<T> {...} Supplier 接口代表一个结果的提供者。
* 用来生成数据的且必须返回一个数据,数据的类型通过泛型参数给定
* 1.T get()
*/
public static void supplier(){
int a = 10;
int b = 20;
// 用于生产对象
Supplier supplier = ()-> {return new Student(); };
// 直接使用
Supplier supplier1 = ()-> "hanshujiekong";
Supplier supplier2 = ()->{ return (a+b)/5;};
// 用于作为方法的参数 此时 Lambda 表达式相当于方法体
int[] arr ={1,2,4,5,9,6,3};
int maxValues = maxValues(()-> {
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (max < arr[i]) {
max = arr[i];
}
}
return max;
});
}
public static int maxValues(Supplier<Integer> supplier){
return supplier.get();
}
/**
* public interface Consumer<T> {...}
* Consumer 接口代表接受单一的输入变量而且没有返回值的一类操作。
* 它的作用和 Supplier 相反,是消费一个数据的,消费的数据类型需要通过泛型指定。
* 1.void accept(T t);
* 消费一个数据的时候,首先做一个操作,然后再做另一个操作,两个操作依次执行,实现一种组合操作。
* 2.default Consumer<T> andThen(Consumer<T> after)
* 例如:before.andThen(after).accept(s);
* before是一个Consumer,after也是一个Consumer 先执行before的accept在执行after的accept
*/
public void consumer(){
// 直接使用
Consumer consumer = (t)-> System.out.println(t);
consumer.accept(123);
Student student = new Student("xx");
// 作为函数的入参-accept
increaseAge(student,(Student s)->{
s.setAge(1);
});
// 作为函数的入参 - andThen
String[] arr = { "张飞,男", "貂蝉,女", "曹操,男","孙尚香,女"};
//这里的 s 表示数组中的每个元素
printInfo(arr, s ->{
System.out.println("姓名:" + s.split(",")[0]);
},s ->{
System.out.println("性别:" + s.split(",")[1]);
});
}
private void increaseAge(Student student, Consumer<Student> consumer){
consumer.accept(student);
}
private void printInfo(String[] arr, Consumer<String> name, Consumer<String> gender) {
for (String s : arr) {
// 先执行name的accept 再执行gender的accept
name.andThen(gender).accept(s);
}
}
/**
* public interface Predicate<T> {...}
* Predicate 中文意思为谓语,"我是一个程序员","是"或"不是"就是谓语。
* 它代表只有一个变量的函数,返回 boolean 类型。
* 1.boolean test(T t); //抽象方法,对 t 进行测试,返回 boolean 类型
* 组合方法,将当前的谓语与另一个谓语进行短路的与操作,返回一个谓语对象
* 2.default Predicate<T> and(Predicate<? super T> other) {...}
* 对当前的谓语进行逻辑非操作,返回一个谓语对象
* 3. default Predicate<T> negate() {...}
* 组合方法,将当前的谓语与另一个谓语进行短路的或操作,返回一个谓语对象
* 4.default Predicate<T> or(Predicate<? super T> other) {...}
* 静态方法,判断 test(object)方法传入的对象是否与参数 targetRef 对象相等
* 5. static Predicate<T> isEqual(Object targetRef) {...}
*/
public void predicate(){
// 直接使用 test
Predicate<String> predicate = s ->"true".equals(s);
predicate.test("trme");
// 直接使用 and/or
Predicate<String> predicate1 = s -> "tr".equals(s);
predicate.and(predicate1).test("tem");
predicate.or(predicate1).test("tem");
// 直接使用 negate
predicate.negate().test("sd");
}
/**
* public interface Function<T, R> {...}
* 根据一个参数得到另一个参数值,前面称为计算的参数,后面称为计算的结果。有进有出,所以称为“函数 Function”。
* 对给定的变量 t 进行计算,得到返回的结果 R
* 1.R apply(T t);
* 默认组合方法,先计算当前函数,再计算传入的函数
* 2.default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {...}
* 默认组合方法,先计算传入的函数,再计算当前函数
* 3.default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {...}
* 静态方法:总是返回它的输入变量
* 4.static <T> Function<T, T> identity() {...}
*/
public void function(){
// 直接使用 apply
Function<Integer,Integer> function = (i)->2*i;
function.apply(10);
// 直接使用 andThen
Function<Integer,Integer> function1 = (i)->i%10;
function.andThen(function1).apply(100);
// 直接使用compose
function1.compose(function).apply(100);
}
/**
* public interface BinaryOperator<T> extends BiFunction<T,T,T> {...}
* BinaryOperator 表示对两个相同类型的操作数进行操作,产生相同类型的结果。
* 从父接口 BiFunction 中继承下来的抽象方法,传入两个参数 t 和 u 进行函数计算,返回计算的结果。
* 1.T apply(T t, T u);
* 返回一个BinaryOperator ,它根据指定的Comparator返回两个元素中的较大Comparator 。
* 2.static <T> BinaryOperator<T> maxBy(Comparator<? super T> comparator){...}
* 返回BinaryOperator返回根据指定的两个元件的较小的Comparator 。
* 3.static <T> BinaryOperator<T> minBy(Comparator<? super T> comparator){...}
*/
public void binaryOperator(){
// 直接使用apply
BinaryOperator<Integer> binaryOperator = (m,n)->m+n;
binaryOperator.apply(1,2);
// 直接使用 maxBy minBy
BinaryOperator<Integer> binaryOperator1 = BinaryOperator.maxBy(Comparator.naturalOrder());
binaryOperator.apply(4,5);
}
/**
* public interface UnaryOperator<T> extends Function<T, T>{...}
* 从 Function 接口中继承下来的抽象方法,使用给定的参数应用此一元运算函数,返回另一个值。
* 1.T apply(T t);
* 始终返回其输入参数的一元运算符也就是后续 apply()输入的是什么,就返回什么。
* 2.static UnaryOperator identity() {...}
*/
public static void unaryOperator(){
// 直接使用apply
UnaryOperator<Integer> unaryOperator = t-> t*10;
System.out.println(unaryOperator.apply(10));
// 作为函数的参数使用 apply
List names = Arrays.asList("Jack","Rose","Tom","NewBoy");
System.out.println("替换前:" + names);
UnaryOperator<String> unaryOperator1 = s -> s.toUpperCase();
names.replaceAll(unaryOperator1);
System.out.println("替换后:" + names);
}
}
|
package JB15;
import java.util.Scanner;
public class Pr01Book {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int numberOfBookPages = Integer.parseInt(sc.nextLine());
int campingDays = Integer.parseInt(sc.nextLine());
int numberOfPagesRead = Integer.parseInt(sc.nextLine());
int totalDaysToRead = 0;
if (campingDays >= 30) {
System.out.println("Never");
}
if (campingDays > 0){
totalDaysToRead = 30 - campingDays;
numberOfPagesRead = numberOfPagesRead * totalDaysToRead;
int totalMonthsNeeded = (numberOfPagesRead / numberOfBookPages) * 100;
System.out.printf("%d years %d months", totalMonthsNeeded / 12, totalMonthsNeeded % 12);
}
}
}
|
package com.cee.wsr.domain;
public class Appendix {
}
|
/*
* 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 javabankproject.Data;
/**
*
* @author Novin Pendar
*/
public class Branch
{
private int code ;
private String name ;
private City city ;
/**
*
* @param code
* @param name
* @param city
*/
public Branch (int code, String name, City city)
{
this.code = code ;
this.name = name ;
this.city = city ;
}
public int getCode ()
{
return code ;
}
public String getName ()
{
return name ;
}
public City getCity ()
{
return city ;
}
}
|
package com.hcl.dmu.demand.vo;
public class DemandDetailsVo {
private Long Id;
private String streamName;
private String subStreamName;
private String skillName;
private long count;
private long fullfilled;
private long gap;
public Long getId() {
return Id;
}
public void setId(Long id) {
Id = id;
}
public String getStreamName() {
return streamName;
}
public void setStreamName(String streamName) {
this.streamName = streamName;
}
public String getSubStreamName() {
return subStreamName;
}
public void setSubStreamName(String subStreamName) {
this.subStreamName = subStreamName;
}
public String getSkillName() {
return skillName;
}
public void setSkillName(String skillName) {
this.skillName = skillName;
}
public long getCount() {
return count;
}
public void setCount(long count) {
this.count = count;
}
public long getFullfilled() {
return fullfilled;
}
public void setFullfilled(long fullfilled) {
this.fullfilled = fullfilled;
}
public long getGap() {
return gap;
}
public void setGap(long gap) {
this.gap = gap;
}
}
|
package com.tencent.mm.g.a;
import com.tencent.mm.plugin.wallet_core.model.a;
public final class pl$a {
public a cao;
}
|
package com.simpson.kisen.fan.model.service;
import com.simpson.kisen.fan.model.vo.Fan;
public interface FanService {
int updateFan(Fan updateFan);
int deleteFan(String fanId);
}
|
package com.tencent.tencentmap.mapsdk.a;
import android.content.Context;
import android.graphics.PointF;
import android.graphics.Rect;
import com.tencent.map.lib.MapLanguage;
import com.tencent.map.lib.basemap.data.GeoPoint;
import com.tencent.map.lib.d;
import com.tencent.map.lib.gl.JNI;
import com.tencent.map.lib.gl.JNICallback;
import com.tencent.map.lib.gl.JNICallback$c;
import com.tencent.map.lib.gl.JNICallback.a;
import com.tencent.map.lib.gl.JNICallback.b;
import com.tencent.map.lib.gl.JNICallback.e;
import com.tencent.map.lib.gl.JNICallback.f;
import com.tencent.map.lib.gl.JNICallback.h;
import com.tencent.map.lib.gl.JNICallback.j;
import com.tencent.map.lib.gl.JNICallback.k;
import com.tencent.map.lib.mapstructure.MapRouteSectionWithName;
import com.tencent.map.lib.mapstructure.MaskLayer;
import com.tencent.map.lib.mapstructure.Polygon2D;
import com.tencent.map.lib.mapstructure.TappedElement;
import com.tencent.map.lib.mapstructure.TrafficRequestItem;
import com.tencent.map.lib.util.SystemUtil;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import javax.microedition.khronos.opengles.GL10;
public class hq implements a, e, h, jh {
private static boolean i = true;
private JNI a = new JNI();
private long b;
private ie c;
private ji d = new ji();
private jh e;
private e f;
private hv g;
private long h = 0;
private int j = 0;
private float k = 1.0f;
public hq(Context context, hv hvVar) {
this.d.a(this);
this.g = hvVar;
this.k = context.getResources().getDisplayMetrics().density;
if (i) {
jk.a(context, "txmapengine");
}
}
public void a(ie ieVar) {
this.c = ieVar;
}
public void a(jg jgVar) {
this.d.a(jgVar);
}
public void a(e eVar) {
this.f = eVar;
}
public void a() {
this.d.a();
if (this.d != null) {
this.d.a(null);
}
if (this.b != 0) {
synchronized (this) {
this.a.nativeDestroyEngine(this.b);
this.b = 0;
}
}
}
public boolean a(Context context, if ifVar, String str, String str2, String str3, float f) {
boolean a = hw.a();
int[] iArr = new int[1];
this.b = this.a.nativeInitEngine(str, str2, str3, SystemUtil.getDensity(context), 256, SystemUtil.getDensity(context), iArr, a, MapLanguage.LAN_CHINESE.ordinal());
if (iArr[0] != 0) {
d.a("init engine fail:" + iArr[0]);
this.b = 0;
return false;
}
this.a.initCallback(ifVar, this, this, this, this.g.a(), this.b);
this.a.nativeSetTrafficColor(this.b, -14803236, -15611905, -11088785, -16777063);
return true;
}
public boolean b() {
if (this.b == 0) {
return false;
}
return this.a.nativeGenerateTextures(this.b);
}
public boolean c() {
if (this.b == 0) {
return false;
}
this.a.nativeDrawFrame(this.b);
return true;
}
public int d() {
if (this.b == 0) {
return -1;
}
return this.a.nativeClearCache(this.b);
}
public void e() {
if (this.b != 0) {
this.a.nativeLockEngine(this.b);
}
}
public void f() {
if (this.b != 0) {
this.a.nativeUnlockEngine(this.b);
}
}
public boolean g() {
if (this.b == 0) {
return true;
}
boolean nativeIsMapDrawFinished;
synchronized (this) {
nativeIsMapDrawFinished = this.a.nativeIsMapDrawFinished(this.b);
}
return nativeIsMapDrawFinished;
}
public int a(byte[] bArr, int i, boolean z, boolean z2) {
int i2;
synchronized (this) {
if (this.b == 0) {
i2 = -1;
} else {
i2 = this.a.nativeRefreshTrafficData(this.b, bArr, i, z, z2);
}
}
return i2;
}
public void a(int i, int i2, int i3, int i4, int i5) {
if (this.b != 0) {
synchronized (this) {
this.a.nativeCheckTrafficBlockCache(this.b, i, i2, i3, i4, i5);
}
}
}
public TrafficRequestItem[] h() {
TrafficRequestItem[] trafficRequestItemArr = null;
if (this.b != 0) {
synchronized (this) {
int[] nativeFetchLackedTrafficBlocks = this.a.nativeFetchLackedTrafficBlocks(this.b);
if (nativeFetchLackedTrafficBlocks == null || nativeFetchLackedTrafficBlocks.length == 0) {
} else {
trafficRequestItemArr = new TrafficRequestItem[(nativeFetchLackedTrafficBlocks.length / 6)];
for (int i = 0; i < nativeFetchLackedTrafficBlocks.length / 6; i++) {
trafficRequestItemArr[i] = new TrafficRequestItem();
trafficRequestItemArr[i].level = nativeFetchLackedTrafficBlocks[i * 6];
trafficRequestItemArr[i].blockNo = nativeFetchLackedTrafficBlocks[(i * 6) + 1];
trafficRequestItemArr[i].minLon = nativeFetchLackedTrafficBlocks[(i * 6) + 2];
trafficRequestItemArr[i].minLat = nativeFetchLackedTrafficBlocks[(i * 6) + 3];
trafficRequestItemArr[i].maxLon = nativeFetchLackedTrafficBlocks[(i * 6) + 4];
trafficRequestItemArr[i].maxLat = nativeFetchLackedTrafficBlocks[(i * 6) + 5];
}
}
}
}
return trafficRequestItemArr;
}
public int a(Polygon2D polygon2D) {
if (this.b == 0) {
return 0;
}
int nativeAddPolygon;
synchronized (this) {
nativeAddPolygon = this.a.nativeAddPolygon(this.b, polygon2D);
}
return nativeAddPolygon;
}
public void b(Polygon2D polygon2D) {
if (this.b != 0) {
synchronized (this) {
this.a.nativeUpdatePolygon(this.b, polygon2D.polygonId, polygon2D.borldLineId, polygon2D);
}
}
}
public void a(int i, int i2) {
if (this.b != 0 && i >= 0 && this.g != null) {
this.g.a(new 1(this, i, i2));
}
}
public int a(MaskLayer maskLayer) {
if (this.b == 0) {
return 0;
}
return this.a.nativeAddMaskLayer(this.b, maskLayer);
}
public void b(int i, int i2) {
if (this.b != 0) {
this.a.nativeUpdateMaskLayer(this.b, i, i2);
}
}
public void a(int i) {
if (this.b != 0) {
this.a.nativeRemoveMaskLayer(this.b, i);
}
}
public GeoPoint a(byte[] bArr, float f, float f2) {
if (this.b == 0) {
return new GeoPoint();
}
GeoPoint geoPoint;
synchronized (this) {
double[] dArr = new double[2];
this.a.nativeFromScreenLocation(this.b, bArr, f, f2, dArr);
geoPoint = new GeoPoint((int) (dArr[1] * 1000000.0d), (int) (dArr[0] * 1000000.0d));
}
return geoPoint;
}
public PointF a(byte[] bArr, double d, double d2) {
if (this.b == 0) {
return new PointF();
}
PointF pointF;
synchronized (this) {
float[] fArr = new float[2];
this.a.nativeToScreenLocation(this.b, bArr, d, d2, fArr);
pointF = new PointF(fArr[0], fArr[1]);
}
return pointF;
}
public void i() {
if (this.b != 0) {
this.g.a(new hv.a() {
public void a(GL10 gl10) {
hq.this.a.nativeShowStreetRoad(hq.this.b);
}
});
}
}
public void j() {
if (this.b != 0) {
synchronized (this) {
this.a.nativeHideStreetRoad(this.b);
}
}
}
public void a(boolean z) {
if (this.b != 0) {
this.g.a(new 5(this, z));
}
}
public void k() {
if (this.b != 0) {
this.g.a(new 14(this));
}
}
public void l() {
if (this.b != 0) {
this.g.a(new 16(this));
}
}
public String a(GeoPoint geoPoint) {
if (this.b == 0) {
return "";
}
byte[] nativeGetCityName = this.a.nativeGetCityName(this.b, geoPoint);
if (nativeGetCityName != null) {
try {
return new String(nativeGetCityName, "GBK").trim();
} catch (UnsupportedEncodingException e) {
}
}
return "";
}
public void a(String str) {
if (this.b != 0) {
this.g.a(new 17(this, str));
}
}
public int a(iq iqVar) {
if (this.b == 0) {
return -1;
}
int i;
synchronized (this) {
int m = iqVar.m();
boolean z = false;
if (m == 3) {
m = 0;
z = true;
}
boolean z2 = false;
int[] c = iqVar.c();
if (c[0] == 33) {
m = 2;
} else if (c[0] == 20) {
z2 = true;
}
int[] iArr = new int[0];
if (iqVar.y() != null) {
iArr = new int[iqVar.y().size()];
i = 0;
while (true) {
int i2 = i;
if (i2 >= iqVar.y().size()) {
break;
}
iArr[i2] = ((Integer) iqVar.y().get(i2)).intValue();
i = i2 + 1;
}
}
int[] iArr2 = new int[0];
if (iqVar.f() != null) {
iArr2 = new int[iqVar.f().length];
for (i = 0; i < iqVar.f().length; i++) {
iArr2[i] = iqVar.f()[i];
}
}
i = this.a.nativeCreateLine(this.b, iqVar.c(), iqVar.b(), (GeoPoint[]) iqVar.a().toArray(new GeoPoint[0]), iqVar.q(), iqVar.n(), m, z, z2, iqVar.l(), iqVar.j(), iqVar.t(), iqVar.d(), iqVar.e(), iArr2, iqVar.g(), iArr, iqVar.o());
}
return i;
}
public void a(int i, boolean z) {
if (this.b != 0 && i != -1) {
synchronized (this) {
this.a.nativeDeleteLine(this.b, (long) i, z);
}
}
}
public void b(iq iqVar) {
if (this.b != 0) {
int r = iqVar.r();
if (r != -1) {
synchronized (this) {
iq.a p = iqVar.p();
if (p == null) {
return;
}
this.a.nativeSetTurnArrow(this.b, (long) r, p.a, p.b);
}
}
}
}
public void c(iq iqVar) {
if (this.b != 0) {
int r = iqVar.r();
if (r != -1) {
this.g.a(new 18(this, r, iqVar.w()));
}
}
}
public void d(iq iqVar) {
if (this.b != 0) {
int r = iqVar.r();
if (r != -1) {
synchronized (this) {
this.a.nativeSetLineDrawArrow(this.b, (long) r, iqVar.j());
}
}
}
}
public void e(iq iqVar) {
if (this.b != 0) {
int r = iqVar.r();
if (r != -1) {
synchronized (this) {
this.a.nativeSetLineDirectionArrowTextureName(this.b, (long) r, iqVar.u());
}
}
}
}
public void f(iq iqVar) {
if (this.b != 0) {
int r = iqVar.r();
if (r != -1) {
synchronized (this) {
this.a.nativeSetDrawCap(this.b, (long) r, iqVar.k());
}
}
}
}
public void g(iq iqVar) {
if (this.b != 0) {
int r = iqVar.r();
if (r != -1) {
synchronized (this) {
GeoPoint h = iqVar.h();
if (h == null) {
return;
}
this.a.nativeLineInsertPoint(this.b, (long) r, h, iqVar.i());
}
}
}
}
public void h(iq iqVar) {
if (this.b != 0) {
int r = iqVar.r();
if (r != -1) {
synchronized (this) {
GeoPoint h = iqVar.h();
if (h == null) {
return;
}
this.a.nativeLineClearPoint(this.b, (long) r, h, iqVar.i());
}
}
}
}
public TappedElement a(float f, float f2) {
TappedElement tappedElement = null;
if (this.b != 0) {
synchronized (this) {
byte[] nativeOnTap = this.a.nativeOnTap(this.b, f, f2);
if (nativeOnTap == null) {
} else {
try {
tappedElement = TappedElement.fromBytes(nativeOnTap);
} catch (Exception e) {
}
}
}
}
return tappedElement;
}
public void b(boolean z) {
if (0 != this.b) {
synchronized (this) {
this.a.nativeSetBuilding3DEffect(this.b, z);
}
}
}
public void m() {
if (this.b != 0) {
this.g.a(new 11(this));
}
}
public void a(String str, byte[] bArr) {
this.g.a(new 19(this, str, bArr));
if (this.e != null) {
this.e.a(str, bArr);
}
}
public void b(String str) {
this.j++;
if (this.j >= 30) {
m();
this.j = 0;
}
this.g.a(new 20(this, str));
if (this.e != null) {
this.e.b(str);
}
}
public void c(String str) {
this.d.a(str);
}
public void n() {
if (0 != this.b) {
this.g.a(new hv.a() {
public void a(GL10 gl10) {
hq.this.a.nativeHideCompass(hq.this.b);
}
});
}
}
public int a(String str, double d, double d2, float f, float f2, float f3, float f4, float f5, float f6, boolean z, boolean z2, boolean z3, boolean z4, int i) {
if (0 == this.b) {
return 0;
}
int nativeAddMarker;
synchronized (this) {
nativeAddMarker = this.a.nativeAddMarker(this.b, str, d, d2, f, f2, f3, f4, f5, f6, z, z2, z3, z4, i);
}
return nativeAddMarker;
}
public void a(int i, String str, double d, double d2, float f, float f2, float f3, float f4, float f5, float f6, boolean z, boolean z2, boolean z3, boolean z4, int i2) {
if (0 != this.b) {
this.g.a(new 22(this, i, str, d, d2, f, f2, f3, f4, f5, f6, z, z2, z3, z4, i2));
}
}
public void a(int[] iArr, int i) {
if (0 != this.b) {
synchronized (this) {
this.a.nativeDeleteIcons(this.b, iArr, i);
}
}
}
public void c(final boolean z) {
if (0 != this.b) {
this.g.a(new hv.a() {
public void a(GL10 gl10) {
hq.this.a.nativeSetCompassVisible(hq.this.b, z);
}
});
}
}
public void c(int i, int i2) {
if (0 != this.b) {
this.g.a(new 24(this, i, i2));
}
}
public double a(Rect rect, Rect rect2) {
if (0 == this.b) {
return 1.0d;
}
double nativeGetTargetScale;
synchronized (this) {
nativeGetTargetScale = this.a.nativeGetTargetScale(this.b, rect, rect2);
}
return nativeGetTargetScale;
}
public void a(Rect rect, Rect rect2, boolean z) {
if (0 != this.b && this.g != null) {
this.g.a(new 25(this, rect, rect2, z));
}
}
public void d(boolean z) {
if (this.b != 0 && this.g != null) {
synchronized (this) {
this.a.nativeIndoorBuildingEnabled(this.b, z);
}
}
}
public int o() {
if (0 == this.b) {
return -1;
}
int nativeGetIndoorCurrentFloorId;
synchronized (this) {
nativeGetIndoorCurrentFloorId = this.a.nativeGetIndoorCurrentFloorId(this.b);
}
return nativeGetIndoorCurrentFloorId;
}
public String[] p() {
if (0 == this.b) {
return null;
}
String[] nativeGetIndoorFloorNames;
synchronized (this) {
nativeGetIndoorFloorNames = this.a.nativeGetIndoorFloorNames(this.b);
}
return nativeGetIndoorFloorNames;
}
public String b(GeoPoint geoPoint) {
if (0 == this.b) {
return null;
}
String nativeGetCurIndoorName;
synchronized (this) {
nativeGetCurIndoorName = this.a.nativeGetCurIndoorName(this.b, geoPoint);
}
return nativeGetCurIndoorName;
}
public void e(boolean z) {
if (0 != this.b) {
this.g.a(new 3(this, z));
}
}
public void a(float f, float f2, boolean z) {
if (0 != this.b && this.g != null) {
this.g.a(new 4(this, f, f2, z));
}
}
public void a(GeoPoint geoPoint, boolean z) {
if (0 != this.b && this.g != null) {
this.g.a(new 6(this, geoPoint, z));
}
}
public void c(GeoPoint geoPoint) {
if (0 != this.b && this.g != null) {
this.a.nativeSetCenter(this.b, geoPoint, false);
}
}
public GeoPoint q() {
if (0 == this.b) {
return null;
}
GeoPoint geoPoint;
synchronized (this) {
geoPoint = new GeoPoint();
this.a.nativeGetCenterMapPoint(this.b, geoPoint);
}
return geoPoint;
}
public void a(final double d, final boolean z) {
if (0 != this.b && this.g != null) {
this.g.a(new hv.a() {
public void a(GL10 gl10) {
hq.this.a.nativeSetScale(hq.this.b, d, z);
}
});
}
}
public void a(double d) {
if (0 != this.b && this.g != null) {
this.a.nativeSetScale(this.b, d, false);
}
}
public float r() {
if (0 == this.b) {
return 1.0f;
}
float nativeGetScale;
synchronized (this) {
nativeGetScale = (float) this.a.nativeGetScale(this.b);
}
return nativeGetScale;
}
public int s() {
if (0 == this.b) {
return ic.a.c;
}
int nativeGetScaleLevel;
synchronized (this) {
nativeGetScaleLevel = this.a.nativeGetScaleLevel(this.b);
}
return nativeGetScaleLevel;
}
public void b(float f, float f2) {
if (0 != this.b && this.g != null) {
this.g.a(new 8(this, f, f2));
}
}
public void t() {
if (0 != this.b && this.g != null) {
this.g.a(new 9(this));
}
}
public void b(float f, float f2, boolean z) {
if (0 != this.b && this.g != null) {
this.g.a(new 10(this, z, f, f2));
}
}
public void a(int i, int i2, int i3, int i4) {
if (0 != this.b && this.g != null) {
this.g.a(new 12(this, i, i2, i3, i4));
}
}
public void u() {
if (0 != this.b) {
synchronized (this) {
long currentTimeMillis = System.currentTimeMillis();
if (this.h == 0) {
this.a.nativeUpdateFrame(this.b, 0.0d);
} else {
this.a.nativeUpdateFrame(this.b, (double) (currentTimeMillis - this.h));
}
this.h = currentTimeMillis;
}
}
}
public boolean v() {
if (0 == this.b) {
return false;
}
boolean nativeNeedDispaly;
synchronized (this) {
nativeNeedDispaly = this.a.nativeNeedDispaly(this.b);
}
return nativeNeedDispaly;
}
public void f(boolean z) {
if (0 != this.b) {
synchronized (this) {
this.a.nativeSetNeedDisplay(this.b, z);
}
}
}
public void b(int i) {
if (0 != this.b) {
synchronized (this) {
this.a.nativeSetMaxScaleLevel(this.b, i);
}
}
}
public void c(int i) {
if (0 != this.b) {
synchronized (this) {
this.a.nativeSetMinScaleLevel(this.b, i);
}
}
}
public void a(float f) {
if (0 != this.b) {
synchronized (this) {
this.a.nativeSetRotate(this.b, f, false);
}
}
}
public void b(float f) {
if (0 != this.b) {
synchronized (this) {
this.a.nativeSetSkew(this.b, f, false);
}
}
}
public void b(int i, boolean z) {
if (0 != this.b) {
this.g.a(new 13(this, i, z));
}
}
public float w() {
if (0 == this.b) {
return 0.0f;
}
return this.a.nativeGetSkew(this.b);
}
public float x() {
if (0 == this.b) {
return 0.0f;
}
return this.a.nativeGetRotate(this.b);
}
public int y() {
if (0 == this.b) {
return 1;
}
int nativeGetMapMode;
synchronized (this) {
nativeGetMapMode = this.a.nativeGetMapMode(this.b);
}
return nativeGetMapMode;
}
public int c(int i, boolean z) {
if (this.b == 0) {
return -1;
}
int nativeAddHeatTileOverlay;
synchronized (this) {
nativeAddHeatTileOverlay = this.a.nativeAddHeatTileOverlay(this.b, i, z);
}
return nativeAddHeatTileOverlay;
}
public void d(int i) {
if (this.b != 0) {
synchronized (this) {
this.a.nativeRemoveHeatTileOverlay(this.b, i);
}
}
}
public void e(int i) {
if (this.b != 0) {
synchronized (this) {
this.a.nativeReloadHeatTileOverlay(this.b, i);
}
}
}
public void f(int i) {
if (this.g != null) {
ic e = this.g.e();
if (e != null) {
e.a();
}
}
}
public void z() {
if (this.f != null) {
this.f.z();
}
}
public void a(JNICallback.d dVar) {
this.a.setHeatTileLoadCallback(dVar);
}
public void a(j jVar) {
this.a.setWorldTileLoadCallback(jVar);
}
public void a(b bVar) {
this.a.setHandDrawTileLoadCallback(bVar);
}
public void a(JNICallback$c jNICallback$c) {
this.a.setHandDrawTileWriteCallback(jNICallback$c);
}
public void a(k kVar) {
this.a.setTileWriteCallback(kVar);
}
public void a(f fVar) {
this.a.setMapCallbackGetGLContext(fVar);
}
public void d(int i, int i2) {
if (this.b != 0) {
this.a.nativeBringElementAbove(this.b, i, i2);
}
}
public void a(List<MapRouteSectionWithName> list, List<GeoPoint> list2) {
if (0 != this.b) {
synchronized (this) {
if (list != null) {
if (!(list.isEmpty() || list2 == null || list2.isEmpty())) {
int size = list.size();
byte[][] bArr = new byte[size][];
for (int i = 0; i < size; i++) {
MapRouteSectionWithName mapRouteSectionWithName = (MapRouteSectionWithName) list.get(i);
if (mapRouteSectionWithName != null) {
bArr[i] = mapRouteSectionWithName.toBytes();
}
}
int size2 = list2.size();
this.a.nativeAddRouteNameSegments(this.b, bArr, size, (GeoPoint[]) list2.toArray(new GeoPoint[size2]), size2);
}
}
}
}
}
public void A() {
if (0 != this.b) {
synchronized (this) {
this.a.nativeClearRouteNameSegments(this.b);
}
}
}
public List<Integer> a(Rect rect, int i) {
List<Integer> list = null;
if (0 != this.b) {
synchronized (this) {
int[] iArr = new int[100];
int nativeQueryCityCodeList = this.a.nativeQueryCityCodeList(this.b, rect, i, iArr, 100);
if (nativeQueryCityCodeList > 0) {
list = new ArrayList(nativeQueryCityCodeList);
for (int i2 = 0; i2 < nativeQueryCityCodeList; i2++) {
list.add(Integer.valueOf(iArr[i2]));
}
}
}
}
return list;
}
public void d(String str) {
if (this.b != 0) {
synchronized (this) {
this.a.nativeMapLoadKMLFile(this.b, str);
}
}
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
public void a(java.util.List<com.tencent.map.lib.mapstructure.BlockRouteCityData> r8) {
/*
r7 = this;
r0 = 0;
r2 = r7.b;
r0 = (r0 > r2 ? 1 : (r0 == r2 ? 0 : -1));
if (r0 != 0) goto L_0x0009;
L_0x0008:
return;
L_0x0009:
monitor-enter(r7);
if (r8 == 0) goto L_0x0012;
L_0x000c:
r0 = r8.isEmpty(); Catch:{ all -> 0x0014 }
if (r0 == 0) goto L_0x0017;
L_0x0012:
monitor-exit(r7); Catch:{ all -> 0x0014 }
goto L_0x0008;
L_0x0014:
r0 = move-exception;
monitor-exit(r7); Catch:{ all -> 0x0014 }
throw r0;
L_0x0017:
r6 = r8.size(); Catch:{ all -> 0x0014 }
r4 = new int[r6]; Catch:{ all -> 0x0014 }
r5 = new int[r6]; Catch:{ all -> 0x0014 }
r0 = 0;
r1 = r0;
L_0x0021:
if (r1 >= r6) goto L_0x0037;
L_0x0023:
r0 = r8.get(r1); Catch:{ all -> 0x0014 }
r0 = (com.tencent.map.lib.mapstructure.BlockRouteCityData) r0; Catch:{ all -> 0x0014 }
if (r0 == 0) goto L_0x0033;
L_0x002b:
r2 = r0.cityCode; Catch:{ all -> 0x0014 }
r4[r1] = r2; Catch:{ all -> 0x0014 }
r0 = r0.version; Catch:{ all -> 0x0014 }
r5[r1] = r0; Catch:{ all -> 0x0014 }
L_0x0033:
r0 = r1 + 1;
r1 = r0;
goto L_0x0021;
L_0x0037:
r1 = r7.a; Catch:{ all -> 0x0014 }
r2 = r7.b; Catch:{ all -> 0x0014 }
r1.nativeLoadBlockRouteCityList(r2, r4, r5, r6); Catch:{ all -> 0x0014 }
monitor-exit(r7); Catch:{ all -> 0x0014 }
goto L_0x0008;
*/
throw new UnsupportedOperationException("Method not decompiled: com.tencent.tencentmap.mapsdk.a.hq.a(java.util.List):void");
}
public void g(boolean z) {
if (0 != this.b) {
synchronized (this) {
this.a.nativeSetBlockRouteVisible(this.b, z);
}
}
}
public int B() {
if (this.b == 0) {
return 0;
}
int nativeGetLanguage;
synchronized (this) {
nativeGetLanguage = this.a.nativeGetLanguage(this.b);
}
return nativeGetLanguage;
}
public void i(iq iqVar) {
if (this.b != 0) {
int r = iqVar.r();
if (r != -1 && iqVar.v() >= 0.0f) {
int m = iqVar.m();
if (m == 3 || m == 0) {
synchronized (this) {
this.a.nativeSetLineArrowSpacing(this.b, r, iqVar.v());
}
return;
}
synchronized (this) {
this.a.nativeSetLineFootPrintSpacing(this.b, r, iqVar.v());
}
}
}
}
public void e(String str) {
if (this.b != 0) {
this.g.a(new 15(this, str));
}
}
public void h(boolean z) {
if (this.b != 0) {
this.a.nativeEnablePOI(this.b, z);
}
}
public void i(boolean z) {
if (this.b != 0) {
this.a.nativeEnableVectorMap(this.b, z);
}
}
}
|
package com.steatoda.commons.fields;
/** Interface each enum that describes object's fields should implement */
public interface FieldEnum {
/**
* For fields that describes subobjects with their own fields, this method returns subobject's {@link FieldEnum} class
*
* @param <F> Field enum describing field type for subobject this field references
*
* @return this field subobject's {@link FieldEnum} class
*/
<F extends Enum<F> & FieldEnum> Class<F> getFieldsClass();
}
|
package programmers.lv3;
import java.util.Arrays;
public class Change_Test {
//거스름돈
//dp 문제
//너무 어려웠다. 처음에 dfs로 접근했다가 아 이건 아니지 싶어서 검색 후 해결했다.
//풀이를 봐도 처음에는 이해하기 어려웠다.
//계속 보다보니까 어느정도 이해는 되었는데 여전히 어질어질하다.
//https://tosuccess.tistory.com/57
//https://ydeer.tistory.com/59 참고
public int solution(int n, int[] money) {
Arrays.sort(money);
int[] dp = new int[n+1];
for (int i = 0; i <= n; i++) {
if (i % money[0] == 0) {
dp[i] = 1;
}
}
for (int i = 1; i < money.length; i++) {
for (int j = money[i]; j <= n; j++) {
dp[j] = (dp[j] + dp[j - money[i]]) % 1000000007;
}
}
return dp[n];
}
}
|
package com.micro.rest.endpoint.wsc;
import com.micro.db.DbOperation;
import com.micro.pojo.Message;
import com.micro.pojo.Transfer;
import com.micro.wsc.WebsocketClient;
import lombok.extern.slf4j.Slf4j;
import org.jooq.Record;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.json.Json;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import static com.micro.pojo.ResponseMessage.NO_RECORD;
import static org.jooq.h2.generated.tables.Accounts.ACCOUNTS;
@RequestScoped
@Path("/wsc")
@Slf4j
public class WSC {
@Inject
private WebsocketClient websocketClient;
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.TEXT_PLAIN)
public Response createTransfer(String msg) {
websocketClient.sendText(msg);
return Response.ok().build();
}
}
|
package com.flutterwave.raveandroid.rave_core.models;
/**
* Created by hamzafetuga on 25/07/2017.
*/
public class CardDetsToSave {
String first6;
public String getFirst6() {
return first6;
}
public String getLast4() {
return last4;
}
String last4;
public CardDetsToSave(String first6, String last4) {
this.first6 = first6;
this.last4 = last4;
}
}
|
package org.ca.View;
import java.io.IOException;
import java.io.PrintWriter;
import org.ca.Model.RequestPage;
import org.ca.controller.ClinicController;
import org.ca.controller.RequestPageController;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class RequestPageSubmit
*/
@WebServlet("/RequestPageSubmit")
public class RequestPageSubmit extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public RequestPageSubmit() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
PrintWriter out= response.getWriter();
RequestPage R = new RequestPage();
R.setCid(request.getParameter("cid"));
R.setState(request.getParameter("cstate"));
R.setCity(request.getParameter("ccity"));
R.setClinic(request.getParameter("cliid"));
R.setTime(request.getParameter("time"));
R.setDate(request.getParameter("date"));
R.setPurpose(request.getParameter("purpose"));
R.setPurpose(request.getParameter("status"));
boolean st=RequestPageController.addNewRecord(R);
if(st)
{
out.println("record submitted");
}
else
{
out.println("record not found....");
}
}catch(Exception e){System.out.println(e);}
}
}
|
package dev.borowiecki.home.after_week_2.company.standard;
public class OfficeWorker extends Employee {
}
|
package com.saha.test.page;
import com.saha.test.base.BasePage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class ShoesAndBagPage extends BasePage {
public ShoesAndBagPage(WebDriver driver){
super(driver);
}
}
|
package com.example.demo.utility.exceptions.ProductExceptions;
import com.example.demo.utility.exceptions.TechnoMarketException;
public class CategoryAlreadyExistsException extends TechnoMarketException {
public CategoryAlreadyExistsException() {
super("Category already Exists");
}
}
|
package org.fuserleer.database;
import java.io.IOException;
@SuppressWarnings("serial")
public class DatabaseException extends IOException
{
public DatabaseException()
{
super ();
}
public DatabaseException(final String message, final Throwable throwable)
{
super(message, throwable);
}
public DatabaseException(final String message)
{
super(message);
}
public DatabaseException(final Throwable throwable)
{
super (throwable);
}
}
|
package src.facility_maintenance;
public class RequestImpl implements Request {
private String maintRequest;
//Getters and Setters-------------------------------------------------------------------------------------------------------------------
public String getMaintRequest(){//retrieves the string of the date when called
return maintRequest;
}
public void setMaintRequest(String maintRequest){
this.maintRequest = maintRequest; //adds a string of a date to the string maint request
}
} |
import java.util.Scanner;
public class OddDecider2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入数字: ");
int number = scanner.nextInt();
System.out.println("是否为奇数? " + ((number & 1) != 0 ? '是' : '否'));
}
}
|
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* @author liming.gong
*/
public class UseDom {
static String currentPath = Thread.currentThread().getContextClassLoader().getResource("").toString();
public static void main(String[] args) throws Exception {
System.out.println(currentPath);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(currentPath + "/book.xml");
//root
Element e = document.getDocumentElement();
System.out.println(e.getNodeName());
Node f = document.getFirstChild();
System.out.println(f.getNodeName());
test(document);
System.out.println("----------------");
Node firstChild = document.getFirstChild();
NodeList list = firstChild.getChildNodes();
int length = list.getLength();
for (int i = 0; i < length; ++i) {
System.out.println("begin+++++++++++");
System.out.println(list.item(i).getNodeName() + '_' + list.item(i).getTextContent() + '_' + list.item(i).getLocalName());
System.out.println("end-------------");
}
System.out.println("----------------");
System.out.println(firstChild.getChildNodes().getLength());
System.out.println(firstChild.getNodeType());
System.out.println(firstChild.getNodeName());
System.out.println("----------------");
Node root = document.getDocumentElement();
System.out.println(root.getChildNodes().getLength());
System.out.println(root.getNodeType());
System.out.println(root.getNodeName());
}
public static void iterate(Node node) {
if (node.getNodeType() == Node.ELEMENT_NODE) {
System.out.println(node.getNodeName());
}
NodeList nodeList = node.getChildNodes();
int len = nodeList.getLength();
for (int i = 0; i < len; i++) {
Node n = nodeList.item(i);
String text = n.getTextContent();
System.out.println(text);
}
}
public static void test(Document document) throws Exception {
Node n = document.getElementsByTagName("book").item(0);
iterate(n);
Element e = (Element) n;
e.setAttribute("press", "AAA press");
Node bookshelf = n.getParentNode();
bookshelf.appendChild(e);
bookshelf.appendChild(e);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer ts = factory.newTransformer();
ts.transform(new DOMSource(document), new StreamResult(currentPath + "/book.xml"));
}
} |
package com.polsl.edziennik.desktopclient.controller.student.teachers;
import java.awt.event.ActionEvent;
import javax.swing.ImageIcon;
import com.polsl.edziennik.desktopclient.controller.student.StudentAction;
import com.polsl.edziennik.desktopclient.view.common.Teachers;
import com.polsl.edziennik.desktopclient.view.student.StudentMainView;
/**
*
* Klasa odpowiedzialna za wykoananie akcji uruchomienia modułu przegląania
* prowadzących na poziomie studenta
*
* @author Mateusz Gołąb
*
*/
public class TeachersOverviewAction extends StudentAction {
private static String title = menu.getString("viewTeachers");
public TeachersOverviewAction(StudentMainView parent) {
super(title);
this.parent = parent;
}
@Override
public void actionPerformed(ActionEvent e) {
Teachers teacherOverview = new Teachers();
parent.addTab(menu.getString("Teachers") + " ", teacherOverview,
new ImageIcon(bundle.getString("examBrowseIcon")));
parent.invalidate();
parent.validate();
}
}
|
public class DeleteNode {
void deleteNode(Node node)
{
// Your code here
node.data = node.next.data;
node.next = node.next.next;
}
}
|
package com.coates.sharding.entity;
import lombok.Data;
/**
* @ClassName User
* @Description TODO
* @Author mc
* @Date 2019/8/28 16:10
* @Version 1.0
**/
@Data
public class User {
private Long id;
private String city;
private String name;
}
|
package com.zihui.cwoa.processone.dao;
import com.zihui.cwoa.financial.pojo.RoleAllUser;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
@Mapper
public interface HumanMapper {
/**
* 查询请假出差记录
*/
List<Map<String,Object>> queryLeaveByVo(String userId, String project, String leaveYear,
String leaveMonth, int page, int limit);
/**
* 查询请假出差记录条数
*/
Integer countLeaveByVo(String userId, String project, String leaveYear, String leaveMonth);
/**
* 查询用户的出差请假记录详情
*/
List<Map<String,Object>> queryLeaveDetail(String userId, String project, String leaveYear, String leaveMonth);
/**
* 查询所有角色及该角色下的所有用户
*/
List<RoleAllUser> queryRoleAllUser();
/**
* 根据父ID查询菜单名称数组
*/
List<String> queryMenuByParentId(String userId,String parentId);
/**
* 查询角色用以下拉框选择
*/
List<Map<String,Object>> queryRoleSelect();
/**
* 根据用户ID查询用户部门
*/
String selectDepartmentById(String userId);
/**
* 根据所有用户名字部门
*/
List<Map<String,Object>> queryNameDepartment();
}
|
/*
* 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 samples.azure.functions;
import com.microsoft.azure.functions.ExecutionContext;
import com.microsoft.azure.functions.HttpMethod;
import com.microsoft.azure.functions.HttpRequestMessage;
import com.microsoft.azure.functions.HttpResponseMessage;
import com.microsoft.azure.functions.HttpStatus;
import com.microsoft.azure.functions.annotation.AuthorizationLevel;
import com.microsoft.azure.functions.annotation.FunctionName;
import com.microsoft.azure.functions.annotation.HttpTrigger;
import java.util.Optional;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
/**
* Azure Functions with HTTP Trigger.
*/
public class AdvancedHttpFunction {
// This function will return JSON text from a request...
private String getTextFromJSon(HttpRequestMessage<Optional<String>> request) {
return getParam(request,"text");
}
// Get parameter value...
private String getParam(HttpRequestMessage<Optional<String>> request, final String paramName) {
if (request == null) {
return null;
}
String query = null;
String value = null;
try {
if (!request.getQueryParameters().isEmpty()) {
query = request.getQueryParameters().get(paramName);
value = new String(request.getBody().orElse(query));
} else {
value = new String(request.getBody().orElse(query));
}
// We need to massage the string being returned to get rid of POST/GET differences in string
// construction, so the results are the same
String searchStr = paramName+"=";
if (value.contains(searchStr)) {
int loc = value.indexOf(searchStr)+searchStr.length();
value = value.substring(loc,value.length());
if (value.indexOf('&')>0) {
value = value.substring(0,value.indexOf('&'));
}
}
return value;
} catch(Exception e) {
return null;
}
}
// Process a standard Http request...
private HttpResponseMessage processRequest(HttpRequestMessage<Optional<String>> request,
final ExecutionContext context) {
try {
// Parse query parameter
String userName = getParam(request,"username");
String userPriv = getParam(request,"userpriv");
if (userName == null || userPriv == null) {
return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
.body("The required parameters have not been specified").build();
}
StringBuilder str = new StringBuilder();
str.append("<p>This is a GET/POST TEXT funtion call<br>");
str.append("User name is '"+userName+"' <br>");
str.append("User privelege is '"+userPriv+"' <br></p>");
userName = null;
userPriv = null;
return request.createResponseBuilder(HttpStatus.OK).body(str.toString()).build();
} catch(Exception e) {
context.getLogger().severe("Trapped text exception "+e.toString());
}
return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
.body("The function errored").build();
}
// Process a JSON request...
private HttpResponseMessage processRequest(HttpRequestMessage request,
LinkedHashMap body,
final ExecutionContext context) {
try {
// Parse query parameter
String userName = (String)body.get("username");
String userPriv = (String)body.get("userpriv");
if (userName == null || userPriv == null) {
return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
.body("The required parameters have not been specified").build();
}
StringBuilder str = new StringBuilder();
str.append("<p>This is a GET/POST JSON funtion call<br>");
str.append("User name is '"+userName+"' <br>");
str.append("User privelege is '"+userPriv+"' <br></p>");
userName = null;
userPriv = null;
return request.createResponseBuilder(HttpStatus.OK).body(str.toString()).build();
} catch(Exception e) {
context.getLogger().severe("Trapped JSON exception "+e.toString());
}
return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
.body("The function errored").build();
}
/**
* This function listens at endpoint "/api/HttpMethod". Two ways to invoke it using "curl" command in bash:
* 1. curl -d "HTTP Body" {your host}/api/HttpMethod
* 2. curl "{your host}/api/HttpMethod?name=HTTP%20Query"
*/
@FunctionName("HttpMethod")
public HttpResponseMessage run(
@HttpTrigger(
name = "req",
methods = {HttpMethod.GET, HttpMethod.POST},
authLevel = AuthorizationLevel.ANONYMOUS)
HttpRequestMessage<Optional<String>> request,
final ExecutionContext context) {
context.getLogger().info("Java HTTP trigger processed a request.");
try {
Map<String,String> headers = request.getHeaders();
Object body = request.getBody();
// Find out what request content I am...
String contentType = (String)headers.get("Content-Type");
if (contentType == null) {
contentType = (String)headers.get("content-type");
}
if (contentType == null) {
contentType = "text/plain";
}
// Process the request based on content...
switch (contentType) {
case "application/json":
String jsonText = getTextFromJSon(request);
if (jsonText != null) {
// Convert JSON text to Map...
LinkedHashMap<String,String> map = new Gson().fromJson(jsonText, LinkedHashMap.class);
return processRequest(request,map,context);
} else {
// Process default...
return processRequest(request,(LinkedHashMap)body,context);
}
case "text/plain":
case "text/plain; charset=utf-8":
case "application/x-www-form-urlencoded":
return processRequest(request,context);
default:
break;
}
} catch(Exception e) {
context.getLogger().severe("Trapped main exception "+e.toString());
e.printStackTrace();
}
return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
.body("The function errored").build();
}
}
|
/*
* Copyright 2004-2011 H2 Group. Multiple-Licensed under the H2 License, Version
* 1.0, and under the Eclipse Public License, Version 1.0
* (http://h2database.com/html/license.html). Initial Developer: H2 Group
*/
package org.h2.test.store;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import org.h2.dev.store.btree.MVMap;
import org.h2.dev.store.btree.MVStore;
import org.h2.store.fs.FileUtils;
import org.h2.test.TestBase;
import org.h2.util.New;
/**
* Tests the tree map store.
*/
public class TestMVStore extends TestBase {
/**
* Run just this test.
*
* @param a ignored
*/
public static void main(String... a) throws Exception {
TestBase.createCaller().init().test();
}
public void test() throws InterruptedException {
testIterateOldVersion();
testObjects();
testExample();
testIterateOverChanges();
testOpenStoreCloseLoop();
testVersion();
testTruncateFile();
testFastDelete();
testRollbackInMemory();
testRollbackStored();
testMeta();
testInMemory();
testLargeImport();
testBtreeStore();
testDefragment();
testReuseSpace();
testRandom();
testKeyValueClasses();
testIterate();
testSimple();
}
private void testIterateOldVersion() {
MVStore s;
Map<Integer, Integer> map;
s = MVStore.open(null, new TestMapFactory());
map = s.openMap("test");
int len = 100;
for (int i = 0; i < len; i++) {
map.put(i, 10 * i);
}
Iterator<Integer> it = map.keySet().iterator();
s.incrementVersion();
for (int i = 0; i < len; i += 2) {
map.remove(i);
}
int count = 0;
while (it.hasNext()) {
it.next();
count++;
}
assertEquals(len, count);
s.close();
}
private void testObjects() {
String fileName = getBaseDir() + "/testObjects.h3";
FileUtils.delete(fileName);
MVStore s;
Map<Object, Object> map;
s = MVStore.open(fileName, new TestMapFactory());
map = s.openMap("test");
map.put(1, "Hello");
map.put("2", 200);
map.put(new Object[1], new Object[]{1, "2"});
s.store();
s.close();
s = MVStore.open(fileName, new TestMapFactory());
map = s.openMap("test");
assertEquals("Hello", map.get(1).toString());
assertEquals(200, ((Integer) map.get("2")).intValue());
Object[] x = (Object[]) map.get(new Object[1]);
assertEquals(2, x.length);
assertEquals(1, ((Integer) x[0]).intValue());
assertEquals("2", (String) x[1]);
s.close();
}
private void testExample() {
String fileName = getBaseDir() + "/testExample.h3";
FileUtils.delete(fileName);
// open the store (in-memory if fileName is null)
MVStore s = MVStore.open(fileName);
// create/get the map "data"
// the String.class, String.class will be optional later
MVMap<String, String> map = s.openMap("data",
String.class, String.class);
// add some data
map.put("1", "Hello");
map.put("2", "World");
// get the current version, for later use
long oldVersion = s.getCurrentVersion();
// from now on, the old version is read-only
s.incrementVersion();
// more changes, in the new version
// changes can be rolled back if required
// changes always go into 'head' (the newest version)
map.put("1", "Hi");
map.remove("2");
// access the old data (before incrementVersion)
MVMap<String, String> oldMap =
map.openVersion(oldVersion);
// store the newest data to disk
s.store();
// print the old version (can be done
// concurrently with further modifications)
// this will print Hello World
// System.out.println(oldMap.get("1"));
// System.out.println(oldMap.get("2"));
oldMap.close();
// print the newest version ("Hi")
// System.out.println(map.get("1"));
// close the store - this doesn't write to disk
s.close();
}
private void testOpenStoreCloseLoop() {
String fileName = getBaseDir() + "/testOpenClose.h3";
FileUtils.delete(fileName);
for (int k = 0; k < 1; k++) {
// long t = System.currentTimeMillis();
for (int j = 0; j < 3; j++) {
MVStore s = openStore(fileName);
Map<String, Integer> m = s.openMap("data", String.class,
Integer.class);
for (int i = 0; i < 3; i++) {
Integer x = m.get("value");
m.put("value", x == null ? 0 : x + 1);
s.store();
}
s.close();
}
// System.out.println("open/close: " + (System.currentTimeMillis() - t));
// System.out.println("size: " + FileUtils.size(fileName));
}
}
private void testIterateOverChanges() {
String fileName = getBaseDir() + "/testIterate.h3";
FileUtils.delete(fileName);
MVStore s = openStore(fileName);
s.setMaxPageSize(6);
MVMap<Integer, String> m = s.openMap("data", Integer.class, String.class);
for (int i = 0; i < 100; i++) {
m.put(i, "Hi");
}
s.incrementVersion();
s.store();
for (int i = 20; i < 40; i++) {
assertEquals("Hi", m.put(i, "Hello"));
}
s.incrementVersion();
for (int i = 10; i < 15; i++) {
m.put(i, "Hallo");
}
m.put(50, "Hallo");
for (int i = 90; i < 100; i++) {
assertEquals("Hi", m.remove(i));
}
assertEquals(null, m.put(100, "Hallo"));
Iterator<Integer> it = m.changeIterator(s.getCurrentVersion());
ArrayList<Integer> list = New.arrayList();
while (it.hasNext()) {
list.add(it.next());
}
assertEquals("[9, 10, 11, 12, 13, 14, 48, 49, 50, 87, 88, 89, 100]", list.toString());
s.close();
}
private void testVersion() {
String fileName = getBaseDir() + "/testVersion.h3";
FileUtils.delete(fileName);
MVStore s;
s = openStore(fileName);
MVMap<String, String> m;
s = openStore(fileName);
m = s.openMap("data", String.class, String.class);
long first = s.getCurrentVersion();
s.incrementVersion();
m.put("1", "Hello");
m.put("2", "World");
for (int i = 10; i < 20; i++) {
m.put("" + i, "data");
}
long old = s.getCurrentVersion();
s.incrementVersion();
m.put("1", "Hallo");
m.put("2", "Welt");
MVMap<String, String> mFirst;
mFirst = m.openVersion(first);
assertEquals(0, mFirst.size());
MVMap<String, String> mOld;
assertEquals("Hallo", m.get("1"));
assertEquals("Welt", m.get("2"));
mOld = m.openVersion(old);
assertEquals("Hello", mOld.get("1"));
assertEquals("World", mOld.get("2"));
assertTrue(mOld.isReadOnly());
s.getCurrentVersion();
s.setRetainChunk(0);
long old2 = s.store();
// the old version is still available
assertEquals("Hello", mOld.get("1"));
assertEquals("World", mOld.get("2"));
m.put("1", "Hi");
assertEquals("Welt", m.remove("2"));
s.store();
s.close();
s = openStore(fileName);
m = s.openMap("data", String.class, String.class);
assertEquals("Hi", m.get("1"));
assertEquals(null, m.get("2"));
mOld = m.openVersion(old2);
assertEquals("Hallo", mOld.get("1"));
assertEquals("Welt", mOld.get("2"));
s.close();
}
private void testTruncateFile() {
String fileName = getBaseDir() + "/testTruncate.h3";
FileUtils.delete(fileName);
MVStore s;
MVMap<Integer, String> m;
s = openStore(fileName);
m = s.openMap("data", Integer.class, String.class);
for (int i = 0; i < 1000; i++) {
m.put(i, "Hello World");
}
s.store();
s.close();
long len = FileUtils.size(fileName);
s = openStore(fileName);
m = s.openMap("data", Integer.class, String.class);
m.clear();
s.store();
s.compact(100);
s.close();
long len2 = FileUtils.size(fileName);
assertTrue(len2 < len);
}
private void testFastDelete() {
String fileName = getBaseDir() + "/testFastDelete.h3";
FileUtils.delete(fileName);
MVStore s;
MVMap<Integer, String> m;
s = openStore(fileName);
s.setMaxPageSize(100);
m = s.openMap("data", Integer.class, String.class);
for (int i = 0; i < 1000; i++) {
m.put(i, "Hello World");
assertEquals(i + 1, m.size());
}
assertEquals(1000, m.size());
s.store();
assertEquals(3, s.getWriteCount());
s.close();
s = openStore(fileName);
m = s.openMap("data", Integer.class, String.class);
m.clear();
assertEquals(0, m.size());
s.store();
// ensure only nodes are read, but not leaves
assertEquals(4, s.getReadCount());
assertEquals(2, s.getWriteCount());
s.close();
}
private void testRollbackStored() {
String fileName = getBaseDir() + "/testRollback.h3";
FileUtils.delete(fileName);
MVMap<String, String> meta;
MVStore s = openStore(fileName);
assertEquals(-1, s.getRetainChunk());
s.setRetainChunk(0);
assertEquals(0, s.getRetainChunk());
assertEquals(1, s.getCurrentVersion());
assertFalse(s.hasUnsavedChanges());
MVMap<String, String> m = s.openMap("data", String.class, String.class);
assertTrue(s.hasUnsavedChanges());
MVMap<String, String> m0 = s.openMap("data0", String.class, String.class);
m.put("1", "Hello");
assertEquals(1, s.incrementVersion());
s.rollbackTo(1);
assertEquals("Hello", m.get("1"));
long v2 = s.store();
assertEquals(2, v2);
assertEquals(3, s.getCurrentVersion());
assertFalse(s.hasUnsavedChanges());
s.close();
s = openStore(fileName);
assertEquals(3, s.getCurrentVersion());
s.setRetainChunk(0);
meta = s.getMetaMap();
m = s.openMap("data", String.class, String.class);
m0 = s.openMap("data0", String.class, String.class);
MVMap<String, String> m1 = s.openMap("data1", String.class, String.class);
m.put("1", "Hallo");
m0.put("1", "Hallo");
m1.put("1", "Hallo");
assertEquals("Hallo", m.get("1"));
assertEquals("Hallo", m1.get("1"));
assertTrue(s.hasUnsavedChanges());
s.rollbackTo(v2);
assertFalse(s.hasUnsavedChanges());
assertNull(meta.get("map.data1"));
assertNull(m0.get("1"));
assertEquals("Hello", m.get("1"));
s.store();
s.close();
s = openStore(fileName);
s.setRetainChunk(0);
assertEquals(3, s.getCurrentVersion());
meta = s.getMetaMap();
assertTrue(meta.get("map.data") != null);
assertTrue(meta.get("map.data0") != null);
assertNull(meta.get("map.data1"));
m = s.openMap("data", String.class, String.class);
m0 = s.openMap("data0", String.class, String.class);
assertNull(m0.get("1"));
assertEquals("Hello", m.get("1"));
assertFalse(m0.isReadOnly());
m.put("1", "Hallo");
s.incrementVersion();
assertEquals(4, s.getCurrentVersion());
long v4 = s.store();
assertEquals(4, v4);
assertEquals(5, s.getCurrentVersion());
s.close();
s = openStore(fileName);
s.setRetainChunk(0);
m = s.openMap("data", String.class, String.class);
m.put("1", "Hello");
s.store();
s.close();
s = openStore(fileName);
s.setRetainChunk(0);
m = s.openMap("data", String.class, String.class);
assertEquals("Hello", m.get("1"));
s.rollbackTo(v4);
assertEquals("Hallo", m.get("1"));
s.close();
s = openStore(fileName);
s.setRetainChunk(0);
m = s.openMap("data", String.class, String.class);
assertEquals("Hallo", m.get("1"));
s.close();
}
private void testRollbackInMemory() {
String fileName = getBaseDir() + "/testRollback.h3";
FileUtils.delete(fileName);
MVStore s = openStore(fileName);
assertEquals(1, s.getCurrentVersion());
s.setMaxPageSize(5);
MVMap<String, String> m = s.openMap("data", String.class, String.class);
s.rollbackTo(0);
assertTrue(m.isClosed());
assertEquals(1, s.getCurrentVersion());
m = s.openMap("data", String.class, String.class);
MVMap<String, String> m0 = s.openMap("data0", String.class, String.class);
MVMap<String, String> m2 = s.openMap("data2", String.class, String.class);
m.put("1", "Hello");
for (int i = 0; i < 10; i++) {
m2.put("" + i, "Test");
}
long v1 = s.incrementVersion();
assertEquals(1, v1);
assertEquals(2, s.getCurrentVersion());
MVMap<String, String> m1 = s.openMap("data1", String.class, String.class);
assertEquals("Test", m2.get("1"));
m.put("1", "Hallo");
m0.put("1", "Hallo");
m1.put("1", "Hallo");
m2.clear();
assertEquals("Hallo", m.get("1"));
assertEquals("Hallo", m1.get("1"));
s.rollbackTo(v1);
assertEquals(2, s.getCurrentVersion());
for (int i = 0; i < 10; i++) {
assertEquals("Test", m2.get("" + i));
}
assertEquals("Hello", m.get("1"));
assertNull(m0.get("1"));
assertTrue(m1.isClosed());
assertFalse(m0.isReadOnly());
assertTrue(m1.isReadOnly());
s.close();
}
private void testMeta() {
String fileName = getBaseDir() + "/testMeta.h3";
FileUtils.delete(fileName);
MVStore s = openStore(fileName);
MVMap<String, String> m = s.getMetaMap();
s.setRetainChunk(0);
MVMap<String, String> data = s.openMap("data", String.class, String.class);
data.put("1", "Hello");
data.put("2", "World");
s.store();
assertEquals("1/1///", m.get("map.data"));
assertTrue(m.containsKey("chunk.1"));
assertEquals("Hello", data.put("1", "Hallo"));
s.store();
assertEquals("1/1///", m.get("map.data"));
assertTrue(m.get("root.1").length() > 0);
assertTrue(m.containsKey("chunk.1"));
assertTrue(m.containsKey("chunk.2"));
s.rollbackTo(1);
assertTrue(m.containsKey("chunk.1"));
assertFalse(m.containsKey("chunk.2"));
s.close();
}
private void testInMemory() {
for (int j = 0; j < 1; j++) {
MVStore s = openStore(null);
// s.setMaxPageSize(10);
// long t;
int len = 100;
// TreeMap<Integer, String> m = new TreeMap<Integer, String>();
// HashMap<Integer, String> m = New.hashMap();
MVMap<Integer, String> m = s.openMap("data", Integer.class, String.class);
// t = System.currentTimeMillis();
for (int i = 0; i < len; i++) {
assertNull(m.put(i, "Hello World"));
}
// System.out.println("put: " + (System.currentTimeMillis() - t));
// t = System.currentTimeMillis();
for (int i = 0; i < len; i++) {
assertEquals("Hello World", m.get(i));
}
// System.out.println("get: " + (System.currentTimeMillis() - t));
// t = System.currentTimeMillis();
for (int i = 0; i < len; i++) {
assertEquals("Hello World", m.remove(i));
}
// System.out.println("remove: " + (System.currentTimeMillis() - t));
// System.out.println();
assertEquals(null, m.get(0));
assertEquals(0, m.size());
s.close();
}
}
private void testLargeImport() {
String fileName = getBaseDir() + "/testImport.h3";
int len = 1000;
for (int j = 0; j < 5; j++) {
FileUtils.delete(fileName);
MVStore s = openStore(fileName);
// s.setCompressor(null);
s.setMaxPageSize(40);
MVMap<Integer, Object[]> m = s.openMap("data", "", "i", "r(i,,)");
// Profiler prof = new Profiler();
// prof.startCollecting();
// long t = System.currentTimeMillis();
for (int i = 0; i < len;) {
Object[] o = new Object[3];
o[0] = i;
o[1] = "Hello World";
o[2] = "World";
m.put(i, o);
i++;
if (i % 10000 == 0) {
s.store();
}
}
s.store();
s.close();
// System.out.println(prof.getTop(5));
// System.out.println("store time " + (System.currentTimeMillis() - t));
// System.out.println("store size " + FileUtils.size(fileName));
}
}
private void testBtreeStore() {
String fileName = getBaseDir() + "/testBtreeStore.h3";
FileUtils.delete(fileName);
MVStore s = openStore(fileName);
s.close();
s = openStore(fileName);
MVMap<Integer, String> m = s.openMap("data", Integer.class, String.class);
int count = 2000;
// Profiler p = new Profiler();
// p.startCollecting();
// long t = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
assertNull(m.put(i, "hello " + i));
assertEquals("hello " + i, m.get(i));
}
// System.out.println("put: " + (System.currentTimeMillis() - t));
// System.out.println(p.getTop(5));
// p = new Profiler();
//p.startCollecting();
// t = System.currentTimeMillis();
s.store();
// System.out.println("store: " + (System.currentTimeMillis() - t));
// System.out.println(p.getTop(5));
assertEquals("hello 0", m.remove(0));
assertNull(m.get(0));
for (int i = 1; i < count; i++) {
assertEquals("hello " + i, m.get(i));
}
s.store();
s.close();
s = openStore(fileName);
m = s.openMap("data", Integer.class, String.class);
assertNull(m.get(0));
for (int i = 1; i < count; i++) {
assertEquals("hello " + i, m.get(i));
}
for (int i = 1; i < count; i++) {
m.remove(i);
}
s.store();
assertNull(m.get(0));
for (int i = 0; i < count; i++) {
assertNull(m.get(i));
}
s.close();
}
private void testDefragment() {
String fileName = getBaseDir() + "/testDefragment.h3";
FileUtils.delete(fileName);
long initialLength = 0;
for (int j = 0; j < 20; j++) {
MVStore s = openStore(fileName);
MVMap<Integer, String> m = s.openMap("data", Integer.class, String.class);
for (int i = 0; i < 10; i++) {
m.put(j + i, "Hello " + j);
}
s.store();
s.compact(80);
s.close();
long len = FileUtils.size(fileName);
// System.out.println(" len:" + len);
if (initialLength == 0) {
initialLength = len;
} else {
assertTrue("initial: " + initialLength + " len: " + len, len <= initialLength * 3);
}
}
// long len = FileUtils.size(fileName);
// System.out.println("len0: " + len);
MVStore s = openStore(fileName);
MVMap<Integer, String> m = s.openMap("data", Integer.class, String.class);
for (int i = 0; i < 100; i++) {
m.remove(i);
}
s.store();
s.compact(80);
s.close();
// len = FileUtils.size(fileName);
// System.out.println("len1: " + len);
s = openStore(fileName);
m = s.openMap("data", Integer.class, String.class);
s.compact(80);
s.close();
// len = FileUtils.size(fileName);
// System.out.println("len2: " + len);
}
private void testReuseSpace() {
String fileName = getBaseDir() + "/testReuseSpace.h3";
FileUtils.delete(fileName);
long initialLength = 0;
for (int j = 0; j < 20; j++) {
MVStore s = openStore(fileName);
MVMap<Integer, String> m = s.openMap("data", Integer.class, String.class);
for (int i = 0; i < 10; i++) {
m.put(i, "Hello");
}
s.store();
for (int i = 0; i < 10; i++) {
assertEquals("Hello", m.get(i));
assertEquals("Hello", m.remove(i));
}
s.store();
s.close();
long len = FileUtils.size(fileName);
if (initialLength == 0) {
initialLength = len;
} else {
assertTrue(len <= initialLength * 2);
}
}
}
private void testRandom() {
String fileName = getBaseDir() + "/testRandom.h3";
FileUtils.delete(fileName);
MVStore s = openStore(fileName);
MVMap<Integer, Integer> m = s.openMap("data", Integer.class, Integer.class);
TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
Random r = new Random(1);
int operationCount = 1000;
int maxValue = 30;
Integer expected, got;
for (int i = 0; i < operationCount; i++) {
int k = r.nextInt(maxValue);
int v = r.nextInt();
boolean compareAll;
switch (r.nextInt(3)) {
case 0:
log(i + ": put " + k + " = " + v);
expected = map.put(k, v);
got = m.put(k, v);
if (expected == null) {
assertNull(got);
} else {
assertEquals(expected, got);
}
compareAll = true;
break;
case 1:
log(i + ": remove " + k);
expected = map.remove(k);
got = m.remove(k);
if (expected == null) {
assertNull(got);
} else {
assertEquals(expected, got);
}
compareAll = true;
break;
default:
Integer a = map.get(k);
Integer b = m.get(k);
if (a == null || b == null) {
assertTrue(a == b);
} else {
assertEquals(a.intValue(), b.intValue());
}
compareAll = false;
break;
}
if (compareAll) {
Iterator<Integer> it = m.keyIterator(null);
Iterator<Integer> itExpected = map.keySet().iterator();
while (itExpected.hasNext()) {
assertTrue(it.hasNext());
expected = itExpected.next();
got = it.next();
assertEquals(expected, got);
}
assertFalse(it.hasNext());
}
}
s.close();
}
private void testKeyValueClasses() {
MVStore s;
s = MVStore.open(null);
s.openMap("test", String.class, String.class);
try {
s.openMap("unsupportedKey", ArrayList.class, String.class);
fail();
} catch (RuntimeException e) {
// expected
}
try {
s.openMap("unsupportedValue", String.class, ArrayList.class);
fail();
} catch (RuntimeException e) {
// expected
}
s.close();
String fileName = getBaseDir() + "/testKeyValueClasses.h3";
FileUtils.delete(fileName);
s = openStore(fileName);
MVMap<Integer, String> is = s.openMap("intString", Integer.class, String.class);
is.put(1, "Hello");
MVMap<Integer, Integer> ii = s.openMap("intInt", Integer.class, Integer.class);
ii.put(1, 10);
MVMap<String, Integer> si = s.openMap("stringInt", String.class, Integer.class);
si.put("Test", 10);
MVMap<String, String> ss = s.openMap("stringString", String.class, String.class);
ss.put("Hello", "World");
s.store();
s.close();
s = openStore(fileName);
is = s.openMap("intString", Integer.class, String.class);
assertEquals("Hello", is.get(1));
ii = s.openMap("intInt", Integer.class, Integer.class);
assertEquals(10, ii.get(1).intValue());
si = s.openMap("stringInt", String.class, Integer.class);
assertEquals(10, si.get("Test").intValue());
ss = s.openMap("stringString", String.class, String.class);
assertEquals("World", ss.get("Hello"));
s.close();
}
private void testIterate() {
String fileName = getBaseDir() + "/testIterate.h3";
FileUtils.delete(fileName);
MVStore s = openStore(fileName);
MVMap<Integer, String> m = s.openMap("data", Integer.class, String.class);
Iterator<Integer> it = m.keyIterator(null);
assertFalse(it.hasNext());
for (int i = 0; i < 10; i++) {
m.put(i, "hello " + i);
}
s.store();
it = m.keyIterator(null);
it.next();
assertThrows(UnsupportedOperationException.class, it).remove();
it = m.keyIterator(null);
for (int i = 0; i < 10; i++) {
assertTrue(it.hasNext());
assertEquals(i, it.next().intValue());
}
assertFalse(it.hasNext());
assertNull(it.next());
for (int j = 0; j < 10; j++) {
it = m.keyIterator(j);
for (int i = j; i < 10; i++) {
assertTrue(it.hasNext());
assertEquals(i, it.next().intValue());
}
assertFalse(it.hasNext());
}
s.close();
}
private void testSimple() {
String fileName = getBaseDir() + "/testSimple.h3";
FileUtils.delete(fileName);
MVStore s = openStore(fileName);
MVMap<Integer, String> m = s.openMap("data", Integer.class, String.class);
for (int i = 0; i < 3; i++) {
m.put(i, "hello " + i);
}
s.store();
assertEquals("hello 0", m.remove(0));
assertNull(m.get(0));
for (int i = 1; i < 3; i++) {
assertEquals("hello " + i, m.get(i));
}
s.store();
s.close();
s = openStore(fileName);
m = s.openMap("data", Integer.class, String.class);
assertNull(m.get(0));
for (int i = 1; i < 3; i++) {
assertEquals("hello " + i, m.get(i));
}
s.close();
}
/**
* Open a store for the given file name, using a small page size.
*
* @param fileName the file name (null for in-memory)
* @return the store
*/
protected static MVStore openStore(String fileName) {
MVStore store = MVStore.open(fileName, new TestMapFactory());
store.setMaxPageSize(10);
return store;
}
/**
* Log the message.
*
* @param msg the message
*/
protected static void log(String msg) {
// System.out.println(msg);
}
}
|
package pt.ulisboa.tecnico.cmov.projectcmu;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import pt.ulisboa.tecnico.cmov.projectcmu.database.DatabaseHelper;
import pt.ulisboa.tecnico.cmov.projectcmu.util.DatabaseConstants;
public class ReceivePosts extends AppCompatActivity {
//TODO receber posts do servidor
private ListView mTaskListView;
private ArrayAdapter<String> mAdapter;
private DatabaseHelper mHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receive_posts);
mTaskListView = (ListView) findViewById(R.id.receive_list_view);
receiveLoader();
}
public void showReceiveContent(View view){
TextView titleText = (TextView) view.findViewById(R.id.receive_text_view);
final String titleString = String.valueOf(titleText.getText());
final String body = null; //TODO pedir body de post ao server
// Creating alert Dialog with one Button
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
//AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
// Setting Dialog Title
alertDialog.setTitle(titleString);
// Setting Dialog Message
alertDialog.setMessage(body);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
savePostOnDatabase(titleString, body);
receiveLoader();
dialog.dismiss();
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
private void savePostOnDatabase(String title, String body){
SQLiteDatabase db = mHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DatabaseConstants.PublicationsEntry.COL_TASK_TITLE, title);
values.put(DatabaseConstants.PublicationsEntry.COL_TASK_CONTENT, body);
db.insertWithOnConflict(DatabaseConstants.PublicationsEntry.TABLE,
null,
values,
SQLiteDatabase.CONFLICT_REPLACE);
db.close();
Toast.makeText(this, "Publication Stored!", Toast.LENGTH_SHORT).show();
finish();
}
private void receiveLoader(){
ArrayList<String> receiveListTitles = new ArrayList();
//TODO make receiveListTitles receive titles' list from server
//TODO remove already Received messages from receiveListTitles
if (mAdapter == null) {
mAdapter = new ArrayAdapter<>(this,
R.layout.posts_list,
R.id.post_text_view,
receiveListTitles);
mTaskListView.setAdapter(mAdapter);
} else {
mAdapter.clear();
mAdapter.addAll(receiveListTitles);
mAdapter.notifyDataSetChanged();
mTaskListView.setAdapter(mAdapter);
}
if(mTaskListView.getCount() == 0 && receiveListTitles.size()==0){
TextView nullListView = (TextView) findViewById(R.id.null_receive_list_label);
nullListView.setVisibility(TextView.VISIBLE);
mTaskListView.setVisibility(ListView.INVISIBLE);
}
}
}
|
import java.util.ArrayList;
import java.util.HashMap;
public class Tokenization {
public HashMap<String, Integer> tokenAll(ArrayList<Table> table){
HashMap<String, Integer> map = new HashMap<>();
for(int i=0;i<table.size();i++){
String str = table.get(i).getText();
if(str!=null){
String temp[] = str.split(" ");
for(int j=0;j<temp.length;j++){
if (map.containsKey(temp[j])) {
Integer a = map.get(temp[j]);
a++;
map.put(temp[j], a);
}
else{
map.put(temp[j], 1);
}
}
}
}
return map;
}
public HashMap<String, Integer> tokenSpam(ArrayList<Table> table){
HashMap<String, Integer> map = new HashMap<>();
for(int i=0;i<table.size();i++){
if(table.get(i).getLabel()==1){
String str = table.get(i).getText();
if(str!=null){
String temp[] = str.split(" ");
for(int j=0;j<temp.length;j++){
if (map.containsKey(temp[j])) {
Integer a = map.get(temp[j]);
a++;
map.put(temp[j], a);
}
else{
map.put(temp[j], 1);
}
}
}
}
}
return map;
}
public HashMap<String, Integer> tokenHam(ArrayList<Table> table){
HashMap<String, Integer> map = new HashMap<>();
for(int i=0;i<table.size();i++){
if(table.get(i).getLabel()==0){
String str = table.get(i).getText();
if(str!=null){
String temp[] = str.split(" ");
for(int j=0;j<temp.length;j++){
if (map.containsKey(temp[j])) {
Integer a = map.get(temp[j]);
a++;
map.put(temp[j], a);
}
else{
map.put(temp[j], 1);
}
}
}
}
}
return map;
}
}
|
package logic;
import java.math.BigInteger;
public class HexBin implements Calculation {
public String getoutput(String input) {
return new BigInteger(input, 16).toString(2);
}
}
|
package org.chouchou;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import javafx.application.Platform;
import javafx.event.*;
import javafx.fxml.FXML;
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceDialog;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextField;
import javafx.scene.control.TextInputDialog;
import javafx.scene.input.KeyCode;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
public class Controller extends FAVOMain {
@FXML
private AnchorPane ap;
@FXML
private MenuItem importMenu;
@FXML
private MenuItem saveMenu;
@FXML
private MenuItem closeMenu;
@FXML
private MenuItem rewindMenu;
@FXML
private MenuItem about;
@FXML
private MenuItem readme;
@FXML
private ArrayList<Label> boardArray;
@FXML
private ArrayList<Label> brick1Array;
@FXML
private ArrayList<Label> brick2Array;
@FXML
private ArrayList<Label> brick3Array;
@FXML
private Button takeStepBTN;
@FXML
private Button customBTN;
@FXML
private Button rewindBTN;
@FXML
private TextField codeField;
@FXML
private Button commitBTN;
@FXML
private Button saveBTN;
@FXML
private Label stepLayout;
@FXML
private Label maxLayout;
@FXML
private ArrayList<GridPane> brickPaneArray;
private int stepCount = 0;
private static boolean brickCondition[] = new boolean[3];
private Status maxStatus;
private int maxSelection;
private Solver solver = new Solver(board, brickBuffer);
@FXML
void close(ActionEvent event) {
Platform.exit();
}
@FXML
void commit(ActionEvent event) {
commitAction();
}
private void commitAction(){
String brickCode = codeField.getText();
codeField.clear();
int count = 0;
for (int i = 0; i < 3; i++) {
if (!brickCondition[i]) {
brickBuffer[i] = new Brick();
brickBuffer[i].setType(brickCode);
brickSetup(i, brickBuffer[i].getType());
brickCondition[i] = true;
brickPaneArray.get(i).setBackground(
new Background(new BackgroundFill(Color.web("#d4d2d2"), CornerRadii.EMPTY, Insets.EMPTY)));
break;
}
}
for (int i = 0; i < 3; i++)
if (brickCondition[i])
count++;
if (count == 3) {
solve();
} else {
for (int i = 0; i < 3; i++)
if (!brickCondition[i]) {
codeField.setPromptText("Please Enter brick " + (i + 1));
break;
}
}
}
private void brickSetup(int i, String brickCode) {
ArrayList<Label> brickArray;
switch (i) {
case 0:
brickArray = brick1Array;
break;
case 1:
brickArray = brick2Array;
break;
case 2:
brickArray = brick3Array;
break;
default:
brickArray = brick1Array;
}
for (int j = 0; j < 7; j++) {
if (brickCode.charAt(j) != '0') {
if (brickBuffer[i].getIsMerge())
brickArray.get(j).setText(" m ");
else
brickArray.get(j).setText(" " + brickCode.charAt(j) + " ");
colorUp(brickArray.get(j), brickCode.charAt(j));
} else
brickArray.get(j).setText("");
}
}
private void colorUp(Label label, char color) {
label.setTextFill(Color.web("#ffffff"));
switch (color) {
case 'R':
label.setStyle("-fx-background-color: RED");
break;
case 'G':
label.setStyle("-fx-background-color: GREEN");
break;
case 'B':
label.setStyle("-fx-background-color: BLUE");
break;
}
}
private void solve() {
codeField.setDisable(true);
customBTN.setDisable(false);
takeStepBTN.setDisable(false);
maxStatus = solver.solve();
for (int i = 0; i < 3; i++) {
if (maxStatus.getOriginal().equals(brickBuffer[i].getType())) {
maxSelection = i;
brickSetup(i, maxStatus.getBrick());
brickPaneArray.get(i).setBackground(
new Background(new BackgroundFill(Color.DARKGRAY, CornerRadii.EMPTY, Insets.EMPTY)));
break;
}
}
maxLayout.setText("Three Step Evaluation: " + maxStatus.getEvaluation());
stepLayout.setText("Step: " + stepCount);
int count = 0;
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
if (board[i][j].getValidity()) {
if (maxStatus.getColumn() == i && maxStatus.getRow() == j) {
boardArray.get(count).setStyle("-fx-background-color: DARKGRAY");
boardArray.get(count).setText(" E ");
}
count++;
}
}
}
}
@FXML
void customSetup(ActionEvent event) {
stepCount++;
codeField.setDisable(false);
customBTN.setDisable(true);
takeStepBTN.setDisable(true);
final ChoiceDialog<Integer> brickDialog = new ChoiceDialog<Integer>(1, 2, 3);
brickDialog.setTitle("Brick Choice");
brickDialog.setHeaderText("");
brickDialog.setContentText("Please select the brick you want to put: ");
Optional<Integer> opt = brickDialog.showAndWait();
int brickChoice;
try {
brickChoice = opt.get() - 1;
} catch (final NoSuchElementException ex) {
brickChoice = 0;
}
ArrayList<String> rotateBuffer = new ArrayList<String>();
for (int i = 0; i < brickBuffer[brickChoice].getBlockCost(); i++) {
rotateBuffer.add(brickBuffer[brickChoice].getRotate(i));
}
final ChoiceDialog<String> rotateDialog = new ChoiceDialog<String>(rotateBuffer.get(0), rotateBuffer);
for (int i = 0; i < brickBuffer[brickChoice].getBlockCost(); i++) {
rotateDialog.setSelectedItem(brickBuffer[brickChoice].getRotate(i));
}
rotateDialog.setTitle("Rotation Choice");
rotateDialog.setHeaderText("");
rotateDialog.setContentText("Please select the rotation type of the brick: ");
Optional<String> str = rotateDialog.showAndWait();
String rotateChoice;
try {
rotateChoice = str.get();
} catch (final NoSuchElementException ex) {
rotateChoice = "";
}
final ChoiceDialog<Integer> columnDialog = new ChoiceDialog<Integer>(0, 1, 2, 3, 4, 5, 6);
columnDialog.setTitle("Column Choice");
columnDialog.setHeaderText("");
columnDialog.setContentText("Please select the COLUMN you want to put: ");
opt = columnDialog.showAndWait();
int columnChoice;
try {
columnChoice = opt.get();
} catch (final NoSuchElementException ex) {
columnChoice = 0;
}
final ChoiceDialog<Integer> rowDialog = new ChoiceDialog<Integer>(0, 1, 2, 3, 4, 5, 6);
rowDialog.setTitle("Row Choice");
rowDialog.setHeaderText("");
rowDialog.setContentText("Please select the ROW you want to put: ");
opt = rowDialog.showAndWait();
int rowChoice;
try {
rowChoice = opt.get();
} catch (final NoSuchElementException ex) {
rowChoice = 0;
}
Status status = new Status(columnChoice, rowChoice, brickBuffer[brickChoice].getType(), rotateChoice,
brickBuffer[brickChoice].getIsMerge());
solver.placeBrick(brickBuffer[brickChoice], status, board, 0);
brickCondition[brickChoice] = false;
boardChange();
brickPaneArray.get(maxSelection).setBackground(
new Background(new BackgroundFill(Color.web("#d4d2d2"), CornerRadii.EMPTY, Insets.EMPTY)));
brickPaneArray.get(brickChoice)
.setBackground(new Background(new BackgroundFill(Color.BROWN, CornerRadii.EMPTY, Insets.EMPTY)));
}
@FXML
void importFile(ActionEvent event) {
Path p = Paths.get("data/saved");
if(!Files.exists(p)){
try{
Files.createDirectories(p);
}catch(IOException e){
System.out.println("ERROR: Directory Creation Failed.");
}
}
Stage stage = (Stage) ap.getScene().getWindow();
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Select the board data");
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("TXT", "*.txt"));
fileChooser.setInitialDirectory(new File("data/saved"));
File file = fileChooser.showOpenDialog(stage);
// Read in files. Inclusive of 'last.txt' and 'lastmove.txt'
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
board[i][j].changeFeature('N', 0);
}
}
try {
Scanner reader = new Scanner(file);
int count = 0;
while (reader.hasNextLine()) {
String str = reader.nextLine();
if (str.charAt(0) == '(') {
int column = str.charAt(1) - '0';
int row = str.charAt(3) - '0';
char type = str.charAt(6);
int value = Integer.parseInt(str.substring(8, str.indexOf(']')));
board[column][row].setBlockType(type);
board[column][row].setValue(value);
} else {
brickBuffer[count].setType(str.substring(0, 7));
if (str.length() == 8)
brickBuffer[count].setMerge(true);
brickSetup(count, brickBuffer[count].getType());
brickCondition[count] = true;
count++;
}
}
reader.close();
boardChange();
solve();
} catch (FileNotFoundException e) {
System.out.println("ERROR: FILE NOT FOUND.");
}
}
@FXML
void rewind(ActionEvent event) {
// TODO: NO IDEA!!!
}
@FXML
void save(ActionEvent event) {
Stage stage = (Stage) ap.getScene().getWindow();
FileChooser chooser = new FileChooser();
chooser.setInitialDirectory(new File("data/saved"));
chooser.setTitle("Save Board");
chooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("TXT", "*.txt"));
try {
PrintWriter writer = new PrintWriter(chooser.showSaveDialog(stage).getAbsolutePath());
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
if (board[i][j].getValue() != 0)
writer.printf("(%d,%d)[%c,%d]\n", i, j, board[i][j].getBlockType(), board[i][j].getValue());
}
}
for (int i = 0; i < 3; i++) {
writer.print(brickBuffer[i].getType());
if (brickBuffer[i].getIsMerge())
writer.print("m");
writer.println();
}
writer.flush();
writer.close();
} catch (NullPointerException ex) {
System.out.println("ERROR: NULL POINTER");
} catch (FileNotFoundException e) {
System.out.println("ERROR: FILE NOT FOUND.");
}
}
@FXML
void showAbout(ActionEvent event) {
}
@FXML
void showReadme(ActionEvent event) {
}
@FXML
void takeStep(ActionEvent event) {
stepCount++;
codeField.setDisable(false);
customBTN.setDisable(true);
takeStepBTN.setDisable(true);
for (int i = 0; i < 3; i++) {
if (brickBuffer[i].getType().equals(maxStatus.getOriginal())) {
solver.placeBrick(brickBuffer[i], maxStatus, board, 0);
brickCondition[i] = false;
break;
}
}
boardChange();
brickPaneArray.get(maxSelection).setBackground(
new Background(new BackgroundFill(Color.web("#d4d2d2"), CornerRadii.EMPTY, Insets.EMPTY)));
brickPaneArray.get(maxSelection)
.setBackground(new Background(new BackgroundFill(Color.BROWN, CornerRadii.EMPTY, Insets.EMPTY)));
}
void boardChange() {
int count = 0;
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
if (board[i][j].getValidity()) {
boardArray.get(count).setText(" " + board[i][j].getValue() + " ");
boardArray.get(count).setTextFill(Color.LIGHTGRAY);
switch (board[i][j].getBlockType()) {
case 'R':
boardArray.get(count).setStyle("-fx-background-color: RED");
break;
case 'G':
boardArray.get(count).setStyle("-fx-background-color: GREEN");
break;
case 'B':
boardArray.get(count).setStyle("-fx-background-color: BLUE");
break;
case 'N':
boardArray.get(count).setStyle("-fx-background-color: WHITE");
boardArray.get(count).setText(i + "," + j);
boardArray.get(count).setTextFill(Color.LIGHTGRAY);
break;
}
count++;
}
}
}
}
public void initialize() {
boardChange();
// add listener to the block labels
boardArray.forEach(this::colorChange);
codeField.setOnKeyPressed(event -> {
if(event.getCode() == KeyCode.ENTER){
commitAction();
}
});
}
private void colorChange(Label callLabel){
callLabel.setOnMouseClicked(event -> {
if(event.getButton() == MouseButton.PRIMARY){
//left mouse change color
int count = 0;
for(int i = 0; i < 7; i++){
for(int j = 0; j < 7; j++){
if(board[i][j].getValidity()){
if(boardArray.get(count).equals(callLabel)){
switch(board[i][j].getBlockType()){
case 'N':
callLabel.setStyle("-fx-background-color: RED");
callLabel.setText(" 1 ");
board[i][j].setBlockType('R');
board[i][j].setValue(1);
break;
case 'R':
callLabel.setStyle("-fx-background-color: GREEN");
board[i][j].setBlockType('G');
break;
case 'G':
callLabel.setStyle("-fx-background-color: BLUE");
board[i][j].setBlockType('B');
break;
case 'B':
callLabel.setStyle("-fx-background-color: WHITE");
callLabel.setText(i + "," + j);
board[i][j].setBlockType('N');
board[i][j].setValue(0);
break;
}
}
count++;
}
}
}
}else if(event.getButton() == MouseButton.SECONDARY){
//right mouse to set up the value
int count = 0;
for(int i = 0; i < 7; i++){
for(int j = 0; j < 7; j++){
if(board[i][j].getValidity()){
if(boardArray.get(count).equals(callLabel) && board[i][j].getBlockType() != 'N'){
final TextInputDialog textInputDialog = new TextInputDialog("1");
textInputDialog.setTitle("Set Up Block Value");
textInputDialog.setHeaderText("Please set up the block value");
textInputDialog.setContentText("Input a positive integer :");
final Optional<String> opt = textInputDialog.showAndWait();
String rtn = "0";
try{
rtn = opt.get();
}catch(final NoSuchElementException ex){
System.out.println("No input");
}
try{
if(Integer.parseInt(rtn) < 0) throw new NumberFormatException();
board[i][j].setValue(Integer.parseInt(rtn));
boardArray.get(count).setText(" " + rtn + " ");
}catch(NumberFormatException e){
System.out.println("Wrong number format, please set up one more time.");
}
}
count++;
}
}
}
}
});
}
}
|
package com.tencent.mm.plugin.account.friend.ui;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import com.tencent.mm.a.o;
import com.tencent.mm.aa.c;
import com.tencent.mm.kernel.g;
import com.tencent.mm.model.q;
import com.tencent.mm.plugin.account.a.e;
import com.tencent.mm.plugin.account.a.i;
import com.tencent.mm.plugin.account.friend.a.ao;
import com.tencent.mm.plugin.account.friend.a.ap;
import com.tencent.mm.plugin.account.friend.ui.d.a;
import com.tencent.mm.pluginsdk.ui.a.b;
import com.tencent.mm.pluginsdk.ui.d.j;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.MMActivity;
import java.util.LinkedList;
public final class f extends d {
private final int GG;
private final MMActivity bGc;
private String eIs;
private a eMD;
boolean eML = false;
private a eMM = new a() {
public final void d(int i, String str, int i2) {
x.d("MicroMsg.QQFriendAdapterCaseB", "[cpan] postion:%d qq:%s status:%d", new Object[]{Integer.valueOf(i), str, Integer.valueOf(i2)});
ao aoVar = (ao) f.this.getItem(i);
if (aoVar == null) {
x.e("MicroMsg.QQFriendAdapterCaseB", "[cpan] qq friend is null. qq:%s", new Object[]{str});
return;
}
x.d("MicroMsg.QQFriendAdapterCaseB", "qq friend:%s", new Object[]{aoVar.toString()});
if (aoVar.eLx == 1) {
com.tencent.mm.pluginsdk.ui.applet.a aVar = new com.tencent.mm.pluginsdk.ui.applet.a(f.this.bGc, new 1(this));
aVar.eNh = aoVar.eLw;
aVar.qIe = false;
LinkedList linkedList = new LinkedList();
linkedList.add(Integer.valueOf(12));
if (bi.oW(aoVar.getUsername())) {
x.w("MicroMsg.QQFriendAdapterCaseB", "[cpan] qq friend username is null.");
return;
}
aVar.b(aoVar.getUsername(), linkedList, true);
aoVar.dHO = 1;
((ap) ((com.tencent.mm.plugin.account.a.a.a) g.n(com.tencent.mm.plugin.account.a.a.a.class)).getQQListStg()).a(aoVar.eLw, aoVar);
f.this.WT();
}
}
};
public final /* synthetic */ Object a(Object obj, Cursor cursor) {
ao aoVar = (ao) obj;
if (aoVar == null) {
aoVar = new ao();
}
aoVar.d(cursor);
return aoVar;
}
public f(MMActivity mMActivity, int i) {
super(mMActivity, new ao());
this.bGc = mMActivity;
this.GG = i;
this.eML = mMActivity.getIntent().getBooleanExtra("qqgroup_sendmessage", false);
lB(true);
}
public final void a(a aVar) {
this.eMD = aVar;
}
public final void pi(String str) {
this.eIs = bi.oU(str.trim());
aYc();
WT();
}
protected final void WS() {
WT();
}
public final void WT() {
aYc();
if (bi.oW(this.eIs)) {
setCursor(((ap) ((com.tencent.mm.plugin.account.a.a.a) g.n(com.tencent.mm.plugin.account.a.a.a.class)).getQQListStg()).z(this.GG, this.eML));
} else {
setCursor(((ap) ((com.tencent.mm.plugin.account.a.a.a) g.n(com.tencent.mm.plugin.account.a.a.a.class)).getQQListStg()).c(this.GG, this.eIs, this.eML));
}
if (!(this.eMD == null || this.eIs == null)) {
this.eMD.ja(getCursor().getCount());
}
notifyDataSetChanged();
}
public final View getView(int i, View view, ViewGroup viewGroup) {
b bVar;
ao aoVar = (ao) getItem(i);
if (view == null) {
view = View.inflate(this.bGc, com.tencent.mm.plugin.account.a.g.friend_list_item, null);
b bVar2 = new b(this, view);
view.setTag(bVar2);
bVar = bVar2;
} else {
bVar = (b) view.getTag();
}
bVar.eIy = i;
bVar.account = aoVar.eLw;
bVar.status = aoVar.eLx;
bVar.eIH.setText(j.a(this.bGc, aoVar.getDisplayName(), bVar.eIH.getTextSize()));
bVar.eII.setText(j.a(this.bGc, aoVar.wO(), bVar.eII.getTextSize()));
if (this.eML) {
Bitmap aY;
if (o.cx(bVar.account) != 0) {
aY = c.aY(aoVar.eLw);
} else {
aY = null;
}
if (aY == null) {
bVar.eBM.setImageDrawable(com.tencent.mm.bp.a.f(this.bGc, i.default_avatar));
} else {
bVar.eBM.setImageBitmap(aY);
}
} else {
b.a(bVar.eBM, aoVar.getUsername());
}
if (!this.eML) {
switch (aoVar.eLx) {
case 1:
case 2:
if (!((com.tencent.mm.plugin.messenger.foundation.a.i) g.l(com.tencent.mm.plugin.messenger.foundation.a.i.class)).FR().Yc(aoVar.getUsername()) && !q.GF().equals(aoVar.getUsername())) {
if (aoVar.dHO != 2) {
bVar.eIA.setClickable(true);
bVar.eIA.setBackgroundResource(e.btn_solid_green);
bVar.eBR.setText(com.tencent.mm.plugin.account.a.j.friend_add);
bVar.eBR.setTextColor(this.bGc.getResources().getColor(com.tencent.mm.plugin.account.a.c.white));
break;
}
bVar.eIA.setClickable(false);
bVar.eIA.setBackgroundDrawable(null);
bVar.eBR.setText(com.tencent.mm.plugin.account.a.j.friend_waiting_ask);
bVar.eBR.setTextColor(this.bGc.getResources().getColor(com.tencent.mm.plugin.account.a.c.lightgrey));
break;
}
bVar.eIA.setClickable(false);
bVar.eIA.setBackgroundDrawable(null);
bVar.eBR.setText(com.tencent.mm.plugin.account.a.j.friend_added);
bVar.eBR.setTextColor(this.bGc.getResources().getColor(com.tencent.mm.plugin.account.a.c.lightgrey));
break;
break;
}
switch (aoVar.dHO) {
case 0:
case 2:
bVar.eBR.setVisibility(0);
bVar.eIJ.setVisibility(4);
break;
case 1:
bVar.eBR.setVisibility(4);
bVar.eIJ.setVisibility(0);
break;
}
}
bVar.eIA.setVisibility(8);
ao aoVar2 = (ao) getItem(i - 1);
int i2 = aoVar2 == null ? -1 : aoVar2.dHN;
String str = "MicroMsg.QQFriendAdapterCaseB";
String str2 = "qq friend pre:%s";
Object[] objArr = new Object[1];
objArr[0] = aoVar2 != null ? aoVar2.toString() : "";
x.d(str, str2, objArr);
str = "MicroMsg.QQFriendAdapterCaseB";
str2 = "qq friend:%s";
objArr = new Object[1];
objArr[0] = aoVar != null ? aoVar.toString() : "";
x.d(str, str2, objArr);
if (i == 0) {
CharSequence b = b(aoVar);
if (bi.oW(b)) {
x.w("MicroMsg.QQFriendAdapterCaseB", "get display show head return null, user[%s] pos[%d]", new Object[]{aoVar.getUsername(), Integer.valueOf(i)});
bVar.eIG.setVisibility(8);
} else {
bVar.eIG.setVisibility(0);
bVar.eIG.setText(b);
bVar.eIG.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
}
} else {
boolean z;
if (aoVar.dHN != i2) {
z = true;
} else {
z = false;
}
CharSequence b2 = b(aoVar);
if (bi.oW(b2) || !z) {
x.w("MicroMsg.QQFriendAdapterCaseB", "get display show head return null, user[%s] pos[%d]", new Object[]{aoVar.getUsername(), Integer.valueOf(i)});
bVar.eIG.setVisibility(8);
} else {
bVar.eIG.setVisibility(0);
bVar.eIG.setText(b2);
bVar.eIG.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
}
}
return view;
}
private static String b(ao aoVar) {
if (aoVar.dHN == 123) {
return "#";
}
return String.valueOf((char) aoVar.dHN);
}
public final void jX(String str) {
}
}
|
package VSMTests;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class TestPrintWriter {
/*
* Testing whether print writer makes the file or not if the file does not
* already exist
*/
public static void main(String... args) {
PrintWriter writer = null;
try {
writer = new PrintWriter(
"/Users/sameerkhurana10/Documents/My Documents/My_Documents/vectorspacemodellingnlp/test.txt");
writer.println("test");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
writer.flush();
writer.close();
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package view;
import helper.DialogHelper;
import helper.ShareHelper;
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.Timer;
/**
*
* @author ASUS
*/
public class MainJFrame extends javax.swing.JFrame {
/**
* Creates new form MainJFrame
*/
public MainJFrame() {
initComponents();
setSize(700, 800);
setIconImage(ShareHelper.APP_ICON);
setLocationRelativeTo(null);
new Timer(1000, new ActionListener() {
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss a");
@Override
public void actionPerformed(ActionEvent e) {
lbldongHo.setText(format.format(new Date()));
}
}).start();
this.openWelcome();
this.openLogin();
}
void openLogin() {
new DangNhapJDialog(this, true).setVisible(true);
}
void openWelcome() {
new ChaoJDialog(this, true).setVisible(true);
}
void logoff() {
ShareHelper.logoff();
this.openLogin();
}
void exit() {
if (DialogHelper.confirm(this, "Bạn thực sự muốn kết thúc?")) {
System.exit(0);
}
}
void openThongKe(int index) {
if (ShareHelper.authenticated()) {
new ThongKeJFrame().setVisible(true);
} else {
DialogHelper.alert(this, "Vui lòng đăng nhập!");
}
}
void openNhanVien() {
if (ShareHelper.authenticated()) {
new NhanVienJFrame().setVisible(true);
} else {
DialogHelper.alert(this, "Vui lòng đăng nhập!");
}
}
void openKhoaHoc() {
if (ShareHelper.authenticated()) {
new KhoJFrame().setVisible(true);
} else {
DialogHelper.alert(this, "Vui lòng đăng nhập!");
}
}
void openSanPham() {
if (ShareHelper.authenticated()) {
new SanPhamJFrame().setVisible(true);
} else {
DialogHelper.alert(this, "Vui lòng đăng nhập!");
}
}
void openNguoiHoc() {
if (ShareHelper.authenticated()) {
new KhachHangJFrame().setVisible(true);
} else {
DialogHelper.alert(this, "Vui lòng đăng nhập!");
}
}
void openAbout() {
new GioiThieuJDialog(this, true).setVisible(true);
}
void openWebsite() {
try {
Desktop.getDesktop().browse(new File("help/index.html").toURI());
} catch (IOException ex) {
DialogHelper.alert(this, "Không tìm thấy file hướng dẫn!");
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jSeparator1 = new javax.swing.JSeparator();
toolBar = new javax.swing.JToolBar();
btnDangxuat = new javax.swing.JButton();
btnKetthuc = new javax.swing.JButton();
jSeparator7 = new javax.swing.JToolBar.Separator();
btnSanPham = new javax.swing.JButton();
btnKhacHang = new javax.swing.JButton();
btnKho = new javax.swing.JButton();
btnThongKe = new javax.swing.JButton();
lblNoidung = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
lbldongHo = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
mnuHethong = new javax.swing.JMenu();
mniDangnhap = new javax.swing.JMenuItem();
mniDangxuat = new javax.swing.JMenuItem();
jSeparator2 = new javax.swing.JPopupMenu.Separator();
mniDoimatkhau = new javax.swing.JMenuItem();
jSeparator3 = new javax.swing.JPopupMenu.Separator();
mniKetthuc = new javax.swing.JMenuItem();
mnuQuanly = new javax.swing.JMenu();
mniNguoihoc = new javax.swing.JMenuItem();
mniSanPham = new javax.swing.JMenuItem();
mniKho = new javax.swing.JMenuItem();
mniQuanlynhanvien = new javax.swing.JMenuItem();
about = new javax.swing.JMenu();
mniAbout = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("QUẢN LÝ BÁN HÀNG LƯU NIỆM");
toolBar.setRollover(true);
btnDangxuat.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img_FPOLY/Exit.png"))); // NOI18N
btnDangxuat.setText("Đăng xuất");
btnDangxuat.setFocusable(false);
btnDangxuat.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnDangxuat.setMargin(new java.awt.Insets(2, 10, 2, 10));
btnDangxuat.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnDangxuat.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDangxuatActionPerformed(evt);
}
});
toolBar.add(btnDangxuat);
btnKetthuc.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img_FPOLY/Stop.png"))); // NOI18N
btnKetthuc.setText("Kết thúc");
btnKetthuc.setFocusable(false);
btnKetthuc.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnKetthuc.setMargin(new java.awt.Insets(2, 10, 2, 10));
btnKetthuc.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnKetthuc.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnKetthucActionPerformed(evt);
}
});
toolBar.add(btnKetthuc);
toolBar.add(jSeparator7);
btnSanPham.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icons8-product-25.png"))); // NOI18N
btnSanPham.setText("Sản phẩm");
btnSanPham.setFocusable(false);
btnSanPham.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnSanPham.setMargin(new java.awt.Insets(2, 10, 2, 10));
btnSanPham.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnSanPham.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSanPhamActionPerformed(evt);
}
});
toolBar.add(btnSanPham);
btnKhacHang.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icons8-customer-25.png"))); // NOI18N
btnKhacHang.setText("Khách hàng");
btnKhacHang.setFocusable(false);
btnKhacHang.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnKhacHang.setMargin(new java.awt.Insets(2, 10, 2, 10));
btnKhacHang.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnKhacHang.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnKhacHangActionPerformed(evt);
}
});
toolBar.add(btnKhacHang);
btnKho.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icons8-warehouse-25.png"))); // NOI18N
btnKho.setText("Kho");
btnKho.setFocusable(false);
btnKho.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnKho.setMargin(new java.awt.Insets(2, 10, 2, 10));
btnKho.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnKho.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnKhoActionPerformed(evt);
}
});
toolBar.add(btnKho);
btnThongKe.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icons8-statistics-25.png"))); // NOI18N
btnThongKe.setText("Thống kê");
btnThongKe.setFocusable(false);
btnThongKe.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnThongKe.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnThongKe.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnThongKeActionPerformed(evt);
}
});
toolBar.add(btnThongKe);
lblNoidung.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/logo.jpg"))); // NOI18N
lblNoidung.addAncestorListener(new javax.swing.event.AncestorListener() {
public void ancestorMoved(javax.swing.event.AncestorEvent evt) {
}
public void ancestorAdded(javax.swing.event.AncestorEvent evt) {
lblNoidungAncestorAdded(evt);
}
public void ancestorRemoved(javax.swing.event.AncestorEvent evt) {
}
});
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img_FPOLY/Info.png"))); // NOI18N
jLabel1.setText("Cửa hàng lưu niệm");
lbldongHo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img_FPOLY/Alarm.png"))); // NOI18N
lbldongHo.setText("10:55 PM");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 474, Short.MAX_VALUE)
.addComponent(lbldongHo)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(lbldongHo))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
mnuHethong.setText("Hệ thống");
mniDangnhap.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L, java.awt.event.InputEvent.CTRL_MASK));
mniDangnhap.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img_FPOLY/Key.png"))); // NOI18N
mniDangnhap.setText("Đăng nhập");
mniDangnhap.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mniDangnhapActionPerformed(evt);
}
});
mnuHethong.add(mniDangnhap);
mniDangxuat.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
mniDangxuat.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img_FPOLY/Log out.png"))); // NOI18N
mniDangxuat.setText("Đăng xuất");
mniDangxuat.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mniDangxuatActionPerformed(evt);
}
});
mnuHethong.add(mniDangxuat);
mnuHethong.add(jSeparator2);
mniDoimatkhau.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img_FPOLY/Refresh.png"))); // NOI18N
mniDoimatkhau.setText("Đổi mật khẩu");
mniDoimatkhau.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mniDoimatkhauActionPerformed(evt);
}
});
mnuHethong.add(mniDoimatkhau);
mnuHethong.add(jSeparator3);
mniKetthuc.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F10, 0));
mniKetthuc.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img_FPOLY/Stop.png"))); // NOI18N
mniKetthuc.setText("Kết thúc");
mniKetthuc.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mniKetthucActionPerformed(evt);
}
});
mnuHethong.add(mniKetthuc);
jMenuBar1.add(mnuHethong);
mnuQuanly.setText("Quản lý");
mniNguoihoc.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icons8-customer-25.png"))); // NOI18N
mniNguoihoc.setText("Khách hàng");
mniNguoihoc.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mniNguoihocActionPerformed(evt);
}
});
mnuQuanly.add(mniNguoihoc);
mniSanPham.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icons8-product-25.png"))); // NOI18N
mniSanPham.setText("Sản phẩm");
mniSanPham.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mniSanPhamActionPerformed(evt);
}
});
mnuQuanly.add(mniSanPham);
mniKho.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icons8-warehouse-25.png"))); // NOI18N
mniKho.setText("Kho");
mniKho.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mniKhoActionPerformed(evt);
}
});
mnuQuanly.add(mniKho);
mniQuanlynhanvien.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icons8-employee-25.png"))); // NOI18N
mniQuanlynhanvien.setText("Quản lý nhân viên");
mniQuanlynhanvien.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mniQuanlynhanvienActionPerformed(evt);
}
});
mnuQuanly.add(mniQuanlynhanvien);
jMenuBar1.add(mnuQuanly);
about.setText("Trợ giúp");
about.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
aboutActionPerformed(evt);
}
});
mniAbout.setText("About");
mniAbout.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mniAboutActionPerformed(evt);
}
});
about.add(mniAbout);
jMenuItem2.setText("Hướng dẫn");
about.add(jMenuItem2);
jMenuBar1.add(about);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(lblNoidung)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(toolBar, javax.swing.GroupLayout.DEFAULT_SIZE, 565, Short.MAX_VALUE)
.addGap(119, 119, 119))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(toolBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lblNoidung)
.addGap(1, 1, 1)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
getAccessibleContext().setAccessibleName("Quản lý bán hàng lưu niệm");
pack();
}// </editor-fold>//GEN-END:initComponents
private void mniDoimatkhauActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniDoimatkhauActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_mniDoimatkhauActionPerformed
private void mniSanPhamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniSanPhamActionPerformed
openSanPham();
}//GEN-LAST:event_mniSanPhamActionPerformed
private void mniQuanlynhanvienActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniQuanlynhanvienActionPerformed
openNhanVien();
}//GEN-LAST:event_mniQuanlynhanvienActionPerformed
private void mniDoanhthutungSanPhamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniDoanhthutungSanPhamActionPerformed
openThongKe(4);
}//GEN-LAST:event_mniDoanhthutungSanPhamActionPerformed
private void mniDangnhapActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniDangnhapActionPerformed
new DangNhapJDialog(this, true).setVisible(true);
}//GEN-LAST:event_mniDangnhapActionPerformed
private void lblNoidungAncestorAdded(javax.swing.event.AncestorEvent evt) {//GEN-FIRST:event_lblNoidungAncestorAdded
// TODO add your handling code here:
}//GEN-LAST:event_lblNoidungAncestorAdded
private void btnDangxuatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDangxuatActionPerformed
System.exit(0);
}//GEN-LAST:event_btnDangxuatActionPerformed
private void mniDangxuatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniDangxuatActionPerformed
ShareHelper.logoff();
this.openLogin();
}//GEN-LAST:event_mniDangxuatActionPerformed
private void btnKetthucActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnKetthucActionPerformed
System.exit(0);
}//GEN-LAST:event_btnKetthucActionPerformed
private void mniKetthucActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniKetthucActionPerformed
exit();
}//GEN-LAST:event_mniKetthucActionPerformed
private void mniNguoihocActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniNguoihocActionPerformed
openNguoiHoc();
}//GEN-LAST:event_mniNguoihocActionPerformed
private void mniKhoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniKhoActionPerformed
openKhoaHoc();
}//GEN-LAST:event_mniKhoActionPerformed
private void btnKhacHangActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnKhacHangActionPerformed
openNguoiHoc();
}//GEN-LAST:event_btnKhacHangActionPerformed
private void btnSanPhamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSanPhamActionPerformed
openSanPham();
}//GEN-LAST:event_btnSanPhamActionPerformed
private void btnKhoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnKhoActionPerformed
openKhoaHoc();
}//GEN-LAST:event_btnKhoActionPerformed
private void btnThongKeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnThongKeActionPerformed
// TODO add your handling code here:
openThongKe(WIDTH);
}//GEN-LAST:event_btnThongKeActionPerformed
private void aboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_aboutActionPerformed
private void mniAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniAboutActionPerformed
// TODO add your handling code here:
openAbout();
}//GEN-LAST:event_mniAboutActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenu about;
private javax.swing.JButton btnDangxuat;
private javax.swing.JButton btnKetthuc;
private javax.swing.JButton btnKhacHang;
private javax.swing.JButton btnKho;
private javax.swing.JButton btnSanPham;
private javax.swing.JButton btnThongKe;
private javax.swing.JLabel jLabel1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JPanel jPanel1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JPopupMenu.Separator jSeparator2;
private javax.swing.JPopupMenu.Separator jSeparator3;
private javax.swing.JToolBar.Separator jSeparator7;
private javax.swing.JLabel lblNoidung;
private javax.swing.JLabel lbldongHo;
private javax.swing.JMenuItem mniAbout;
private javax.swing.JMenuItem mniDangnhap;
private javax.swing.JMenuItem mniDangxuat;
private javax.swing.JMenuItem mniDoimatkhau;
private javax.swing.JMenuItem mniKetthuc;
private javax.swing.JMenuItem mniKho;
private javax.swing.JMenuItem mniNguoihoc;
private javax.swing.JMenuItem mniQuanlynhanvien;
private javax.swing.JMenuItem mniSanPham;
private javax.swing.JMenu mnuHethong;
private javax.swing.JMenu mnuQuanly;
private javax.swing.JToolBar toolBar;
// End of variables declaration//GEN-END:variables
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package view;
import java.util.Calendar;
/**
*
* @author Caio
*/
public class Funcionarios extends Pessoas{
private String codigodetrabalho;
private String cargo;
public Funcionarios(String codigodetrabalho, String cargo) {
this.codigodetrabalho = codigodetrabalho;
this.cargo = cargo;
}
public String getCodigodetrabalho() {
return codigodetrabalho;
}
public String getCargo() {
return cargo;
}
public void setCodigodetrabalho(String codigodetrabalho) {
this.codigodetrabalho = codigodetrabalho;
}
public void setCargo(String cargo) {
this.cargo = cargo;
}
@Override
public String toString(){
return "Funcionário{"+" Nome: " + this.getNome()+" Código de trabalho: "+this.getCodigodetrabalho() +" Cargo: "+this.getCargo()+" CPF: " + this.getCpf()+"}";
}
@Override
public void fazerAniversario(Calendar c) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void definirAltura() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
|
package pl.edu.amu.datasupplier.repository;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Sort;
import pl.edu.amu.datasupplier.config.SpringUnitTest;
import pl.edu.amu.datasupplier.model.TestCaseTemplate;
import javax.validation.ConstraintViolationException;
import java.util.Arrays;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@SpringBootTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class TestCaseTemplateRepositoryTest extends SpringUnitTest {
@Autowired
private TestCaseTemplateRepository repository;
@BeforeAll
public void setup() {
System.out.println("init mongodb database, add testCaseTemplate to repository");
importJSON("testCaseTemplate", "src/test/resources/testCaseTemplates.txt");
}
@Test
void Should_ReturnTestCaseTemplates_When_ValidTags() {
System.out.println("Find testCaseTemplates by tags");
assertTrue(repository.findByTagsIn(Arrays.asList(new String[]{"verification"}), new Sort(Sort.Direction.ASC, "group")).size() == 1);
}
@Test
public void Should_ThrowConstraintViolationException_When_BlankName() {
System.out.println("Throw error when save testTemplate with blank name.");
TestCaseTemplate testCaseTemplate = new TestCaseTemplate();
testCaseTemplate.setName("");
testCaseTemplate.setSteps(Optional.of(Arrays.asList("step 1", "step 2")));
testCaseTemplate.setTags(Arrays.asList("tag 1", "tag 2"));
Throwable exception = assertThrows(ConstraintViolationException.class,
() -> repository.save(testCaseTemplate));
}
@Test
public void Should_ThrowConstraintViolationException_When_EmptyTags() {
System.out.println("Throw error when save testTemplate with empty tags.");
TestCaseTemplate testCaseTemplate = new TestCaseTemplate();
testCaseTemplate.setName("Not blank test");
testCaseTemplate.setSteps(Optional.of(Arrays.asList("step 1", "step 2")));
Throwable exception = assertThrows(ConstraintViolationException.class,
() -> repository.save(testCaseTemplate));
}
} |
package com.tencent.mm.plugin.exdevice.a;
import com.tencent.mm.ab.l;
public interface b<T extends l> {
void b(int i, int i2, String str, T t);
}
|
package com.algaworks.ecommerce.jpql;
import com.algaworks.ecommerce.EntityManagerTest;
import com.algaworks.ecommerce.dto.ProdutoDTO;
import com.algaworks.ecommerce.model.Cliente;
import com.algaworks.ecommerce.model.Pedido;
import org.junit.Assert;
import org.junit.Test;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import java.util.List;
public class BasicoJPQLTest extends EntityManagerTest {
@Test
public void projetarOResultadoComDto() {
final String jpql = "select new com.algaworks.ecommerce.dto.ProdutoDTO(id, nome) from Produto";
TypedQuery<ProdutoDTO> typedQuery = entityManager.createQuery(jpql, ProdutoDTO.class);
List<ProdutoDTO> objects = typedQuery.getResultList();
Assert.assertFalse(objects.isEmpty());
objects.forEach(dto -> System.out.println(dto.getId() + " - " + dto.getNome()));
}
@Test
public void projetarOResultado() {
TypedQuery<Object[]> typedQuery = entityManager.createQuery("select id, nome from Produto", Object[].class);
List<Object[]> objects = typedQuery.getResultList();
Assert.assertTrue(objects.get(0).length == 2);
objects.forEach(array -> System.out.println(array[0] + " - " + array[1]));
}
@Test
public void buscandoUmUnicoAtributoDaEntidade() {
TypedQuery<String> stringTypedQuery = entityManager.createQuery("select p.nome from Produto p", String.class);
List<String> produtos = stringTypedQuery.getResultList();
Assert.assertTrue(String.class.equals(produtos.get(0).getClass()));
TypedQuery<Cliente> clienteTypedQuery = entityManager.createQuery("select p.cliente from Pedido p", Cliente.class);
List<Cliente> clientes = clienteTypedQuery.getResultList();
Assert.assertTrue(Cliente.class.equals(clientes.get(0).getClass()));
}
@Test
public void buscaPorId() {
Pedido pedido = entityManager.find(Pedido.class, 1);
Assert.assertNotNull(pedido);
TypedQuery<Pedido> typedQuery = entityManager.createQuery("select p from Pedido p where p.id = :id", Pedido.class);
typedQuery.setParameter("id", 1);
Pedido pedido1 = typedQuery.getSingleResult();
Assert.assertNotNull(pedido1);
}
@Test
public void diferencaEntreQueryETypedQuery() {
final String jpql = "select p from Pedido p where p.id = :id";
Query query = entityManager.createQuery(jpql);
query.setParameter("id", 1);
Pedido pedidoUm = (Pedido) query.getSingleResult();
Assert.assertNotNull(pedidoUm);
TypedQuery<Pedido> typedQuery = entityManager.createQuery(jpql, Pedido.class);
typedQuery.setParameter("id", 1);
Pedido pedidoDois = typedQuery.getSingleResult();
Assert.assertNotNull(pedidoDois);
}
}
|
package sos.pojo.dto;
import java.util.Calendar;
public class Driver extends Person {
private String tcno;
private int birthYear;
public Driver(){}
public Driver(String name, String surname, String phone, String tcno,
int birthYear) {
super(name, surname, phone);
this.tcno = tcno;
this.birthYear = birthYear;
}
public String getTcno() {
return tcno;
}
public void setTcno(String tcno) {
this.tcno = tcno;
}
public int getBirthYear() {
return birthYear;
}
public void setBirthYear(int birthYear) {
this.birthYear = birthYear;
}
public int getAge(){
int year=Calendar.getInstance().get(Calendar.YEAR);
return year-this.birthYear;
}
}
|
package com.manage.salary.employee;
import org.springframework.data.jpa.repository.Modifying;
import java.util.List;
import java.util.Optional;
public interface EmployeeService {
List<Employee> getEmployees();
void saveOrUpdateEmployee(Employee theEmployee);
Employee getEmployeeById(Long theId);
void deleteEmployee(Long employeeId);
}
|
package com.vouz.mobileV2.Utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Util {
public static void copyStream(InputStream Input, OutputStream Output) throws IOException {
byte[] buffer = new byte[5120];
int length = Input.read(buffer);
while (length > 0) {
Output.write(buffer, 0, length);
length = Input.read(buffer);
}
}
public static void copyFromAssetsToStorage(Context Context, String SourceFile, String DestinationFile) throws IOException {
InputStream IS = Context.getAssets().open(SourceFile);
OutputStream OS = new FileOutputStream(DestinationFile);
copyStream(IS, OS);
OS.flush();
OS.close();
IS.close();
}
public static boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
public static String getDatabasePath(Context context) {
if (context != null){
return context.getFilesDir().getPath() + File.separator + "db.sqlite";
} else {
return "";
}
}
}
|
package org.rtmplite.main;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import org.apache.mina.core.buffer.IoBuffer;
import org.rtmplite.amf.AMFObjectEncoder;
import org.rtmplite.amf.RTMPDecoder;
import org.rtmplite.amf.XRTMPDecoder;
import org.rtmplite.messages.HeaderEncoder;
import org.rtmplite.messages.Message;
import org.rtmplite.messages.RTMPDecodeState;
import org.rtmplite.utils.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.xml.internal.fastinfoset.Encoder;
public class MessageReader {
private List<MessageListener> listeners = new ArrayList<MessageListener>();
private List<MessageRawListener> rawListeners = new ArrayList<MessageRawListener>();
private Connection connection;
private SynchronizedWriter writer;
private InputStream inputStream;
public MessageReader(Connection connection) {
this.connection = connection;
this.writer = connection.getSynchronizedWriter();
}
public void addRawListener(MessageRawListener listener) {
rawListeners.add(listener);
}
public void addListener(MessageListener listener) {
listeners.add(listener);
}
public void removeListener(MessageListener listener) {
listeners.remove(listener);
}
public boolean runWorker() {
try {
this.inputStream = connection.getSocket().getInputStream();
Reader reader = new Reader();
reader.setName("Reader thread");
reader.start();
return true;
} catch(Exception e) {
e.printStackTrace();
return false;
}
}
public class Reader extends Thread {
private int totalBytesRead = 100000;
@Override
public void run() {
new Thread() {
public void run() {
try {
while(true) {
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HeaderEncoder header = new HeaderEncoder();
header.setChannelId((byte) 2);
header.setPacketType((byte)0x3);
AMFObjectEncoder amfObject = new AMFObjectEncoder();
amfObject.addBytes(NumberUtils.intToBytes(totalBytesRead));
Message message = new Message(header, amfObject);
writer.write(message.getRawBytes());
}
} catch (IOException e) {}
}
}.start();
//byte[] buf = new byte[65536]; // Adjust if you want
//Logger log = LoggerFactory.getLogger(MessageReader.class);
//RTMPDecodeState state = new RTMPDecodeState("1");
//RTMPDecoder rtmpDecoder = new RTMPDecoder(MessageReader.this.writer, state, listeners, rawListeners);
//byte[] lastBuffer = null;
//int bytesRead;
try {
XRTMPDecoder decoder = new XRTMPDecoder(connection, inputStream, writer, listeners, rawListeners);
decoder.process();
/*if(1 == 1) return;
while ((bytesRead = inputStream.read(buf)) > 0) {
System.out.println("BYTES READ: " + bytesRead);
totalBytesRead += bytesRead;
IoBuffer buffer = IoBuffer.allocate(bytesRead);
buffer.put(buf, 0, bytesRead);
buffer.rewind();
while(buffer.hasRemaining()) {
final int remaining = buffer.remaining();
if (state.canStartDecoding(remaining)) {
log.trace("Can start decoding");
state.startDecoding();
} else {
log.trace("Cannot start decoding");
break;
}
if(lastBuffer == null) {
rtmpDecoder.onData(buffer, bytesRead, inputStream);
} else {
IoBuffer newBuffer = IoBuffer.allocate(lastBuffer.length+buffer.remaining());
newBuffer.put(lastBuffer);
newBuffer.put(buffer);
newBuffer.rewind();
buffer = newBuffer;
rtmpDecoder.onData(buffer, bytesRead, inputStream);
lastBuffer = null;
}
if (state.hasDecodedObject()) {
log.trace("Has decoded object");
//if (decodedObject != null) {
// result.add(decodedObject);
//}
} else if (state.canContinueDecoding()) {
log.trace("Can continue decoding");
continue;
} else {
log.trace("Cannot continue decoding");
if(buffer.remaining() < state.getDecoderBufferAmount()) {
int pos = 0;
lastBuffer = new byte[buffer.remaining()];
for(int i=buffer.position(); i<buffer.limit(); i++) {
lastBuffer[pos++] = buffer.get(i);
}
}
break;
}
}
}
*/
} catch (IOException e) {
try {
connection.disconnect();
} catch (IOException e1) {}
return;
}
}
}
}
|
package com.example.root.monerotest.InitActivity.RestoreWallet;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import com.example.root.monerotest.R;
public class RestoreWalletActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.restore_wallet_activity);
}
}
|
package com.neuedu.test;
public class Test02 {
public static void main(String[] args) {
SalaryiedEmployee sa = new SalaryiedEmployee(1000,5);
HourlyEmployee hourlyEmployee = new HourlyEmployee(5,500,12);
SalesEmployee SalesEmployee = new SalesEmployee(120000,0.08,7);
System.out.println(sa.getSalary(5));
System.out.println(hourlyEmployee.getSalary(5));
System.out.println(SalesEmployee.getSalary(5));
}
}
|
public class Conversion {
public static void main(String[] args) {
byte b;
int i=257;
double d=323.142;
System.out.println("conversion of int to byte");
b=(byte)i;
System.out.println("b and i "+b+" "+i);
System.out.println("conversion of double to int");
i = (int)d;
System.out.println("i and d "+i+" "+d);
System.out.println("conversion of double to byte");
b=(byte)d;
System.out.println("d and b "+d+" "+b);
}
}
|
package br.com.test;
import java.util.concurrent.TimeUnit;
import javax.management.RuntimeErrorException;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import cucumber.api.java.Before;
public class PurchasePageObject {
public static WebDriver driver;
public static RecorderEvidence recorderEvidence = new RecorderEvidence();
// public static WebDriverWait wait = new WebDriverWait(driver, 10);
// @Before
public static void preCondicao() throws Exception {
//Start record
recorderEvidence.startRecord();
//Open browser Google Chrome
System.setProperty("webdriver.chrome.driver", "C://chromedriver.exe");
driver = new ChromeDriver();
//Maximize browser
driver.manage().window().maximize();
//Access Automation Practice
driver.get("http://automationpractice.com/index.php?");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
public static String getProductName() {
String productName = driver.findElement(By.xpath("//*[@id= 'homefeatured']/li[1]/div/div[2]/h5/a")).getText();
System.out.println(productName);
return productName;
}
public static void clickButtonProductAddCart() {
// driver.findElement(By.xpath("//*[@id='homefeatured']/li[1]/div[1]/div[2]/div[2]/a[1]/span")).click();
// Actions acao = new Actions(driver);
WebElement element = driver
.findElement(By.xpath("//*[@id= 'homefeatured']/li[1]/div[1]/div[2]/div[2]/a[1]/span"));
// acao.moveToElement(element).click().build().perform();
// it works too
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", element);
}
public static void clickButtonPopupProceedToCheckout() {
WebDriverWait wait = new WebDriverWait(driver, 20);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(
driver.findElement(By.xpath("//*[@class = 'btn btn-default button button-medium']/span/i"))));
element.click();
}
public static void compareProductSelected(String productName) {
try {
if (driver.findElement(By.xpath("//*[@id= 'product_1_1_0_0']/td[2]/p/a")).getText().equals(productName)) {
System.out.println("Validate correct(s) product(s) in Summary screen");
} else {
throw new RuntimeErrorException(null, "Incorrect(s) product(s)");
}
} catch (NoSuchElementException e) {
throw new RuntimeErrorException(null, "Product not found");
}
}
public static void validateProductInStock() {
try {
if (driver.findElement(By.xpath("//*[@id= 'product_1_1_0_0']/td[3]/span")).getText().equals("In stock")) {
System.out.println("Validate product in stock");
} else {
throw new RuntimeErrorException(null, "Product out of stock");
}
} catch (NoSuchElementException e) {
throw new RuntimeErrorException(null, "Product out of stock");
}
}
public static String getTotalPrice() {
String totalPrice = driver.findElement(By.id("total_price")).getText();
System.out.println(totalPrice);
return totalPrice;
}
public static void clickButtonProceedToCheckoutSummaryPage() {
driver.findElement(By.xpath("//*[@class= 'button btn btn-default standard-checkout button-medium']/span/i"))
.click();
}
public static void createAccountEmailAddress(String emailAddress) {
driver.findElement(By.id("email_create")).sendKeys(emailAddress);
}
public static void clickButtonCreateAnAccount() {
driver.findElement(By.xpath("//*[@id= 'SubmitCreate']/span/i")).click();
}
public static void clickRadioButtonGender() {
driver.findElement(By.xpath("//*[@id= 'uniform-id_gender1']/span/input")).click();
}
public static void inputFirstName(String firstName) {
driver.findElement(By.id("customer_firstname")).sendKeys(firstName);
}
public static void inputLastName(String lastName) {
driver.findElement(By.id("customer_lastname")).sendKeys(lastName);
}
public static void inputPassword(String pwd) {
driver.findElement(By.id("passwd")).sendKeys(pwd);
}
public static void inputAddressRegister(String address) {
driver.findElement(By.id("address1")).sendKeys(address);
}
public static void inputCity(String city) {
driver.findElement(By.id("city")).sendKeys(city);
}
public static void selectState(String state) {
Select combo = new Select(driver.findElement(By.id("id_state")));
combo.selectByVisibleText(state);
}
public static void inputPostcode(String postcode) {
driver.findElement(By.id("postcode")).sendKeys(postcode);
}
public static void inputMobilePhone(String mobilePhone) {
driver.findElement(By.id("phone_mobile")).sendKeys(mobilePhone);
}
public static void clickButtonRegister() {
driver.findElement(By.xpath("//*[@id= 'submitAccount']/span/i")).click();
}
public static String getCityStatePostcode(String address, String city, String state, String postcode) {
String cityStatePostcode = city + ", " + state + " " + postcode;
return cityStatePostcode;
}
public static String getAddressSpace(String address) {
String addressSpace = address + " ";
return addressSpace;
}
public static void validateDeliveryAddress(String address, String cityStatePostcode) {
try {
if (driver.findElement(By.xpath("//*[@id= 'address_delivery']/li[3]")).getText().equals(address)
&& (driver.findElement(By.xpath("//*[@id= 'address_delivery']/li[4]")).getText()
.equals(cityStatePostcode))) {
System.out.println("Validate correct address");
} else {
throw new RuntimeErrorException(null, "Incorrect delivery address");
}
} catch (NoSuchElementException e) {
throw new RuntimeErrorException(null, "Address not found");
}
}
public static void clickButtonProceedToCheckoutAddressPage() {
driver.findElement(By.xpath("//*[@class= 'button btn btn-default button-medium']/span/i")).click();
}
public static void clickCheckboxAgreeTermsService() {
driver.findElement(By.id("cgv")).click();
}
public static void clickButtonProceedToCheckoutShippingPage() {
driver.findElement(By.xpath("//*[@class= 'button btn btn-default standard-checkout button-medium']/span/i"))
.click();
}
public static void validateTotalPrice(String totalPrice) {
try {
if (driver.findElement(By.id("total_price")).getText().equals(totalPrice)) {
System.out.println("Validate correct total price");
} else {
throw new RuntimeErrorException(null, "Total price is incorrect");
}
} catch (NoSuchElementException e) {
throw new RuntimeErrorException(null, "Total price is incorrect");
}
}
public static void clickPaymentBankWire() {
driver.findElement(By.xpath("//*[@class= 'bankwire']/span")).click();
}
public static void clickButtonConfirmOrderBankWire() {
driver.findElement(By.xpath("//*[@class= 'button btn btn-default button-medium']/span/i")).click();
}
public static void clickPaymentCheck() {
driver.findElement(By.xpath("//*[@class= 'cheque']/span")).click();
}
public static void clickButtonConfirmOrderCheck() {
driver.findElement(By.xpath("//*[@class= 'button btn btn-default button-medium']/span/i")).click();
}
public static void validateOrderConfirmation() {
String txtOrderConfirmSuccess = driver.findElement(By.xpath("//*[@class= 'box']/p/strong")).getText();
try {
if (txtOrderConfirmSuccess.contains("is complete.")) {
System.out.println(txtOrderConfirmSuccess);
} else {
throw new RuntimeErrorException(null, "Error order confirmation");
}
} catch (RuntimeErrorException errorOrderConf) {
throw new RuntimeErrorException(null, "Error order confirmation");
}
}
public static void clickLinkBackToOrders() {
driver.findElement(By.xpath("//*[@class= 'button-exclusive btn btn-default']/i")).click();
System.out.println("Success order confirmation!");
}
public static void exitBrowser() {
driver.close();
}
public static void finishRecord() throws Exception {
recorderEvidence.finishRecord();
}
}
|
package com.example.androidhiveapp.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.androidhiveapp.R;
import com.example.androidhiveapp.model.Movie;
import com.squareup.picasso.Picasso;
import java.util.List;
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MovieViewHolder> {
private Context mContext;
private List<Movie> movies;
private int rowLayout;
public MovieAdapter(List<Movie> movies, int rowLayout, Context context){
this.movies = movies;
this.mContext = context;
this.rowLayout = rowLayout;
}
@NonNull
@Override
public MovieAdapter.MovieViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout,parent,false);
return new MovieViewHolder(view);
}
@Override
public void onBindViewHolder(MovieViewHolder holder, final int position) {
final Movie movie = movies.get(position);
holder.movieTitle.setText(movie.getTitle());
holder.releaseDate.setText(movie.getReleaseDate());
holder.movieDescription.setText(movie.getOverview());
// holder.rating.setText(movie.getVoteAverage().toString());
// This is how we use Picasso to load images from the internet.
Picasso.get()
.load("http://image.tmdb.org/t/p/w500" + movie.getPosterPath())
.error(R.color.colorAccent)
.into(holder.imageView);
}
@Override
public int getItemCount() {
return movies.size();
}
public static class MovieViewHolder extends RecyclerView.ViewHolder {
LinearLayout moviesLayout;
TextView movieTitle;
TextView releaseDate;
TextView movieDescription;
TextView rating;
ImageView imageView;
public MovieViewHolder(View v) {
super(v);
moviesLayout = (LinearLayout) v.findViewById(R.id.movies_layout);
imageView = (ImageView) itemView.findViewById(R.id.imageView);
movieTitle = (TextView)v.findViewById(R.id.title);
releaseDate = (TextView) v.findViewById(R.id.release);
movieDescription = (TextView)v.findViewById(R.id.description);
}
}
}
|
package br.ita.sem6dia2.HandsOnInterfaces;
public class Cachorro implements Barulhento {
@Override
public String fazerBarulho() {
return "AU au AU au AU au";
}
}
|
public class BowlingGame {
public int getBowlingScore(String bowlingCode) {
// a miss means get 0 score
bowlingCode = bowlingCode.replace('-', '0');
String[] frames = bowlingCode.split("\\|+");
int[] scores = new int[10];
int score = 0;
for (int i = 9; i >= 0; i--) {
scores[i] = getFrameScore(frames, i);
}
for (int i = 0; i < scores.length; i++) {
score += scores[i];
}
return score;
}
private int getFrameScore(String[] frames, int currentIndex) {
int score = 0;
switch (frames[currentIndex].length()) {
case 1:
// this frame is a strike
score += 10;
score += getBallScore(frames, currentIndex + 1, 2);
break;
case 2:
if (frames[currentIndex].charAt(1) == '/') {
// this frame is a spare
score += 10;
score += getBallScore(frames, currentIndex + 1, 1);
} else {
// this frame have a miss
score += frames[currentIndex].charAt(0) - '0' + frames[currentIndex].charAt(1) - '0';
}
break;
}
return score;
}
private int getBallScore(String[] frames, int index, int balls) {
int score = 0;
if (balls == 1) {
score += frames[index].charAt(0) == 'X' ? 10 : frames[index].charAt(0) - '0';
return score;
}
// ball=2
if (frames[index].length() == 2) {
// good
if (frames[index].charAt(1) == '/') {
// this frame is spare
score += 10;
// done
} else {
// XX or like 81,72
for (int i = 0; i < frames[index].length(); i++) {
score += frames[index].charAt(i) == 'X' ? 10 : frames[index].charAt(i) - '0';
}
}
// can return a score
} else {
// this is a strike, go to next frame find a score
score += 10;
score += getBallScore(frames, index + 1, 1);
}
return score;
}
}
|
package net.youzule.shiro.chapter03;
/**
* @description:
* @company:
* @author:Sean
* @date:2018/7/13 11:48
**/
public class App {
}
|
package uk.co.jassoft.markets;
import org.springframework.beans.factory.annotation.Value;
import uk.co.jassoft.markets.datamodel.company.Company;
import uk.co.jassoft.markets.datamodel.company.CompanyBuilder;
import uk.co.jassoft.markets.datamodel.company.sentiment.StorySentiment;
import uk.co.jassoft.markets.datamodel.sources.SourceBuilder;
import uk.co.jassoft.markets.datamodel.story.*;
import uk.co.jassoft.markets.datamodel.system.Topic;
import uk.co.jassoft.markets.repository.CompanyRepository;
import uk.co.jassoft.markets.repository.SourceRepository;
import uk.co.jassoft.markets.repository.StoryRepository;
import uk.co.jassoft.markets.repository.StorySentimentRepository;
import uk.co.jassoft.markets.sentiment.SpringConfiguration;
import uk.co.jassoft.markets.sentiment.StorySentimentListener;
import uk.co.jassoft.markets.sentiment.lingual.SentimentAnalyser;
import uk.co.jassoft.utils.BaseRepositoryTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.*;
/**
* Created by jonshaw on 18/03/2016.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringConfiguration.class)
@IntegrationTest(value = "SENTIMENT_API_REST_URL=http://sentiment-api:8888")
public class StorySentimentListenerTest extends BaseRepositoryTest {
@Autowired
private StoryRepository storyRepository;
@Autowired
private CompanyRepository companyRepository;
@Autowired
private SourceRepository sourceRepository;
@Autowired
private StorySentimentRepository storySentimentRepository;
@Autowired
private RestOperations restOperations;
@Autowired
@InjectMocks
private SentimentAnalyser sentimentAnalyser;
@Autowired
@InjectMocks
private StorySentimentListener target;
@Mock
private RestTemplate restTemplate;
@Mock
private JmsTemplate jmsTemplate;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
super.setUp();
storyRepository.deleteAll();
companyRepository.deleteAll();
sourceRepository.deleteAll();
storySentimentRepository.deleteAll();
}
@Test
public void onMessage_storyMatchesSourceExclusion_isDeleted() throws Exception {
String sourceId = sourceRepository.save(SourceBuilder.aSource()
.withExclusionList(Arrays.asList("test.com"))
.build())
.getId();
String storyId = storyRepository.save(new StoryBuilder()
.setParentSource(sourceId)
.setUrl(new URL("http://test.com"))
.createStory())
.getId();
target.sentimentAnalyse(storyId);
assertEquals(0, storyRepository.count());
}
@Test
public void onMessage_storyWithNoEntities_isDeleted() throws Exception {
String sourceId = sourceRepository.save(SourceBuilder.aSource()
.withExclusionList(Arrays.asList())
.build())
.getId();
String storyId = storyRepository.save(new StoryBuilder()
.setParentSource(sourceId)
.setUrl(new URL("http://test.com"))
.createStory())
.getId();
target.sentimentAnalyse(storyId);
assertEquals(0, storyRepository.count());
}
@Test
public void onMessage_storyWithEntities_generatesSentiment() throws Exception {
String sourceId = sourceRepository.save(SourceBuilder.aSource()
.withExclusionList(Arrays.asList())
.build())
.getId();
String companyId = companyRepository.save(CompanyBuilder.aCompany()
.withEntities(NamedEntitiesBuilder.aNamedEntities()
.withOrganisation(NamedEntityBuilder.aNamedEntity()
.withName("TestOrganisation")
.withCount(5)
.build())
.withOrganisation(NamedEntityBuilder.aNamedEntity()
.withName("Test Company")
.withCount(5)
.build())
.build())
.build())
.getId();
String storyId = storyRepository.save(new StoryBuilder()
.setParentSource(sourceId)
.setUrl(new URL("http://test.com"))
.setEntities(NamedEntitiesBuilder.aNamedEntities()
.withOrganisation(NamedEntityBuilder.aNamedEntity()
.withName("TestOrganisation")
.withCount(2)
.withMatched(true)
.withSentiments(Arrays.asList(
SentimentBuilder.aSentiment()
.withSentence("This is a really good sentiment for testing sentiment")
.build()
))
.build())
.build())
.setMatchedCompanies(Arrays.asList(companyId))
.createStory())
.getId();
when(restTemplate.postForObject(eq("http://sentiment-api:8888"), any(MultiValueMap.class), eq(String.class)))
.thenReturn("{\"score\":3,\"comparative\":0.3333333333333333,\"tokens\":[\"this\",\"is\",\"a\",\"really\",\"good\",\"sentiment\",\"for\",\"testing\",\"sentiment\"],\"words\":[\"good\"],\"positive\":[\"good\"],\"negative\":[]}");
target.sentimentAnalyse(storyId);
assertEquals(1, storyRepository.count());
final Story resultStory = storyRepository.findOne(storyId);
assertNotNull(resultStory.getEntities());
assertEquals(1, companyRepository.count());
final Company resultCompany = companyRepository.findOne(companyId);
List<StorySentiment> storySentimentList = storySentimentRepository.findAll();
assertNotNull(storySentimentList);
assertEquals(storyId, storySentimentList.get(0).getStory());
assertEquals("TestOrganisation", storySentimentList.get(0).getEntitySentiment().get(0).getEntity());
assertEquals(new Integer(15), storySentimentList.get(0).getEntitySentiment().get(0).getSentiment());
Mockito.verify(jmsTemplate, Mockito.times(1)).convertAndSend(Mockito.eq(Topic.SentimentUpdated.toString()), Mockito.eq(companyId));
}
@Test
public void onMessage_storyWithUnmatchedEntities_generatesSentiment() throws Exception {
String sourceId = sourceRepository.save(SourceBuilder.aSource()
.withExclusionList(Arrays.asList())
.build())
.getId();
String companyId = companyRepository.save(CompanyBuilder.aCompany()
.withEntities(NamedEntitiesBuilder.aNamedEntities()
.withOrganisation(NamedEntityBuilder.aNamedEntity()
.withName("TestOrganisation")
.withCount(5)
.build())
.build())
.build())
.getId();
String storyId = storyRepository.save(new StoryBuilder()
.setParentSource(sourceId)
.setUrl(new URL("http://test.com"))
.setEntities(NamedEntitiesBuilder.aNamedEntities()
.withOrganisation(NamedEntityBuilder.aNamedEntity()
.withName("TestOrganisation")
.withCount(2)
.withSentiments(Arrays.asList(SentimentBuilder.aSentiment()
.withSentence("This is a really good sentiment for testing sentiment")
.build()))
.build())
.build())
.setMatchedCompanies(Arrays.asList(companyId))
.createStory())
.getId();
target.sentimentAnalyse(storyId);
assertEquals(1, storyRepository.count());
final Story resultStory = storyRepository.findOne(storyId);
assertNotNull(resultStory.getEntities());
assertEquals(1, companyRepository.count());
final Company resultCompany = companyRepository.findOne(companyId);
List<StorySentiment> storySentimentList = storySentimentRepository.findAll();
assertNotNull(storySentimentList);
assertEquals(storyId, storySentimentList.get(0).getStory());
assertEquals("TestOrganisation", storySentimentList.get(0).getEntitySentiment().get(0).getEntity());
assertEquals(new Integer(0), storySentimentList.get(0).getEntitySentiment().get(0).getSentiment());
}
} |
package com.Appthuchi.Appqlthuchi.moder;
public class KhoanChi {
public String soTien,moTa,loaiChi;
public int maKhoanChi;
public String ngayChi;
public String getSoTien() {
return soTien;
}
public void setSoTien(String soTien) {
this.soTien = soTien;
}
public String getMoTa() {
return moTa;
}
public void setMoTa(String moTa) {
this.moTa = moTa;
}
public String getLoaiChi() {
return loaiChi;
}
public void setLoaiChi(String loaiChi) {
this.loaiChi = loaiChi;
}
public int getMaKhoanChi() {
return maKhoanChi;
}
public void setMaKhoanChi(int maKhoanChi) {
this.maKhoanChi = maKhoanChi;
}
public String getNgayChi() {
return ngayChi;
}
public void setNgayChi(String ngayChi) {
this.ngayChi = ngayChi;
}
@Override
public String toString() {
return getLoaiChi();
}
}
|
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ReadingExcel {
public static void main(String[] args) throws EncryptedDocumentException, IOException {
File f= new File("F:\\Sahil\\Selenium_doc\\Files\\myExcel.xlsx");
FileInputStream fi= new FileInputStream(f);
Workbook workbook= WorkbookFactory.create(fi);
Sheet sheet0= workbook.getSheetAt(0);
/*for(Row row:sheet0)
{
for(Cell cell:row){
switch(cell.getCellType()){
case Cell.CELL
}
}
}*/
Row row0= sheet0.getRow(4);
System.out.println(row0);
Cell cellA= row0.getCell(4);
System.out.println(cellA);
Cell cellB= row0.getCell(5);
System.out.println(cellA+"..."+cellB);
fi.close();
}
}
|
package com.snab.tachkit.databaseRealm.structureTableDatabase;
import io.realm.RealmObject;
/**
* Created by Таня on 27.03.2015.
* таблица для мото - расположение цилиндров
*/
public class CylinderLocation extends RealmObject {
private int id_moto_cylinder_location;
private String mcl_name;
private int mcl_active;
public int getId_moto_cylinder_location() {
return id_moto_cylinder_location;
}
public void setId_moto_cylinder_location(int id_moto_cylinder_location) {
this.id_moto_cylinder_location = id_moto_cylinder_location;
}
public String getMcl_name() {
return mcl_name;
}
public void setMcl_name(String mcl_name) {
this.mcl_name = mcl_name;
}
public int getMcl_active() {
return mcl_active;
}
public void setMcl_active(int mcl_active) {
this.mcl_active = mcl_active;
}
}
|
package com.ybg.component.email.receivemail;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Session;
import javax.mail.Store;
import com.ybg.component.email.EmailConstant;
public class ReceiveQQMailImpl extends AbstractReceiveMail {
@Override
public Store getStore(Session session) throws Exception {
Store store = session.getStore(EmailConstant.PROTOCOL);
store.connect(EmailConstant.POPqqSERVER, EmailConstant.getEmailaccount(), EmailConstant.getEmailpwd());
return store;
}
@Override
public Properties getProperties() {
String host = EmailConstant.POPqqSERVER;
String port = EmailConstant.SSLPOP3PORT;
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties props = new Properties();
props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.pop3.socketFactory.port", port);
props.setProperty("mail.store.protocol", EmailConstant.PROTOCOL);
props.setProperty("mail.pop3.host", host);
props.setProperty("mail.pop3.port", port);
props.setProperty("mail.pop3.auth.login.disable", "true");
return props;
}
@Override
public Folder getFolder(Store store) throws Exception {
Folder inbox = null;
inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
return inbox;
}
@Override
public Session getSession(Properties pros) {
Session session = Session.getDefaultInstance(pros, null);
session.setDebug(false);
return session;
}
}
|
package cn.uway.util;
import java.io.UnsupportedEncodingException;
import java.text.FieldPosition;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import cn.uway.config.LogMgr;
/**
* 实现采集路径时间通配符等处理
*
* @ClassName: FTPPathUtil
* @author Niow
* @date: 2014-6-20
* @version 1.0
* @since 1.3.0
*/
public class FTPPathUtil{
protected static Logger logger = LogMgr.getInstance().getSystemLogger();
public static final String BENGIN_TAG = "{d";
public static final String END_TAG = "}";
public static SimpleDateFormat format = new TimeSimpleFormat();
/**
* 替换采集路径中的所有时间
*
* @param gatherPath
* 例如:/ftp/lte/telecom/test_nokia/pm/neexport_{dyyyyMMdd}/A{
* dyyyyMMdd.HHmm}*.xml.gz
* @param date
* @return
*/
public static String getReplacedPath(String gatherPath, Date date){
if(gatherPath == null || gatherPath.length() == 0){
return "";
}
int pos = 0;
StringBuilder path = new StringBuilder(gatherPath);
while(pos > -1){
int bPos = path.indexOf(BENGIN_TAG);
pos = bPos;
if(bPos < 0){
return path.toString();
}
int ePos = path.indexOf(END_TAG, bPos);
pos = ePos;
if(ePos < 0){
return path.toString();
}
String pattern = path.substring(bPos + BENGIN_TAG.length(), ePos);
format.applyPattern(pattern);
String strDate = format.format(date);
path.replace(bPos, ePos + 1, strDate);
}
return path.toString();
}
/**
* 从采集路径中提取所有时间格式
*
* @param gatherPath
* @return
*/
public static List<String> getDatePatterns(String gatherPath){
List<String> patterns = new ArrayList<String>();
if(StringUtil.isEmpty(gatherPath)){
return patterns;
}
StringBuilder path = new StringBuilder(gatherPath);
String pattern = extractPattern(path);
while(pattern != ""){
patterns.add(pattern);
pattern = extractPattern(path);
}
return patterns;
}
/**
* 从一段字符中提取第一个时间格式
*
* @param startIndex
* @param path 会对path做截取动作,因此path需要copy一份
* @return
*/
public static String extractPattern(StringBuilder path){
if(path == null || path.length() == 0){
return "";
}
int bPos = path.indexOf(BENGIN_TAG);
if(bPos < 0){
return "";
}
int ePos = path.indexOf(END_TAG, bPos);
if(ePos < 0){
return "";
}
String pattern = path.substring(bPos + BENGIN_TAG.length(), ePos);
path.delete(0, ePos);
return pattern;
}
/**
* 计算路径的最大层级数
*
* @param path
* @return
*/
public static int getPathMaxLevel(String gatherPath){
if(gatherPath.endsWith("/")){
gatherPath = gatherPath.substring(0, gatherPath.length() - 1);
}
if(!gatherPath.startsWith("/")){
gatherPath = "/" + gatherPath;
}
String [] split = gatherPath.split("/");
return split.length - 1;
}
/**
* 编码一条FTP路径
*
* @param ftpPath FTP路径
* @return 编码后的路径
*/
public String encodeFTPPath(String ftpPath, String charset){
try{
String str = StringUtil.isNotEmpty(charset) ? new String(ftpPath.getBytes(charset), "iso_8859_1") : ftpPath;
return str;
}catch(UnsupportedEncodingException e){
logger.error("设置的编码不正确:" + charset, e);
}
return ftpPath;
}
/**
* 解码一条FTP路径
*
* @param ftpPath FTP路径
* @return 解码后的路径
*/
public String decodeFTPPath(String ftpPath, String charset){
try{
String str = StringUtil.isNotEmpty(charset) ? new String(ftpPath.getBytes("iso_8859_1"), charset) : ftpPath;
return str;
}catch(UnsupportedEncodingException e){
logger.error("设置的编码不正确:" + charset, e);
}
return ftpPath;
}
/**
* 对周的时间做转换
*
* @ClassName: TimeSimpleFormat
* @author Niow
* @date: 2014-7-17
*/
static class TimeSimpleFormat extends SimpleDateFormat{
int weekDays[] = {7,1,2,3,4,5,6};
/** */
private static final long serialVersionUID = -5563073568524624529L;
public TimeSimpleFormat(String pattern){
super(pattern);
}
public TimeSimpleFormat(){
super();
}
/*
* (non-Javadoc)
*
* @see java.text.SimpleDateFormat#format(java.util.Date,
* java.lang.StringBuffer, java.text.FieldPosition)
*/
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition pos){
String pattern = super.toPattern();
if(pattern == null || pattern.equals("")){
return super.format(date, toAppendTo, pos);
}
calendar.setTime(date);
int dayOfWeek = weekDays[calendar.get(Calendar.DAY_OF_WEEK) - 1];
int ePos = pattern.indexOf('E');
while(ePos > -1){
pattern = pattern.replaceAll("E", String.valueOf(dayOfWeek));
ePos = pattern.indexOf('E');
}
super.applyPattern(pattern);
return super.format(date, toAppendTo, pos);
}
}
public static void main(String [] args) throws ParseException{
// String path = "/ftp/lte/telecom/test_nokia/pm/neexport{dE}/A20140526.0000+0800-0015+0800_FBJ900001.xml.gz/";
String path2 = "/ftp/lte/telecom/test_nokia/pm{dE}/neexport_{dyyyyMMdd}{dyyyy-MM-dd}/*/A{dyyyyMMdd.HHmm}+0800-0015+0800_FBJ900001.xml.gz";
// List<String> datePatterns = getDatePatterns(path2);
// for(String p : datePatterns){
// System.out.println(p);
// }
// System.out.println(getReplacedPath(path2, new Date()));
Date a = TimeUtil.getDate("2014-07-17 10:11:17");
Calendar c = Calendar.getInstance();
c.setTime(a);
// System.out.println(format.getDateInstance(SimpleDateFormat.DAY_OF_WEEK_FIELD).format(a));
System.out.println(getReplacedPath(path2, a));
}
}
|
package com.china.rescue.framework.security.service;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.china.rescue.framework.redis.RedisCache;
import com.china.rescue.framework.security.jwt.JWTProperties;
import com.china.rescue.po.LoginUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* @Author: xbronze
* @CreateTime: 2022-07-21 10:54
* @Description: TODO
*/
@Component
@Slf4j
public class TokenService {
@Autowired
private RedisCache redisCache;
@Autowired
private JWTProperties jwtProperties;
/**
* 生成token
*/
public String createToken(LoginUser loginUser){
String cust_token = IdUtil.fastUUID(); // 自定义token
loginUser.setToken(cust_token);
refreshToken(loginUser);
Map<String, Object> claims = new HashMap<>();
claims.put("login_user_key", loginUser.getToken());
return Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS256,jwtProperties.getSecret()).compact();
}
/**
* 根据认证的token获取用户信息
*/
public LoginUser getLoginUserByToken(HttpServletRequest request){
// 从请求信息中获取token数据
String authToken = request.getHeader("Authorization");
if (StringUtils.hasText(authToken)) {
// 从自定义tokenProvider中解析用户
authToken = authToken.replace("Bearer ", "");
}
if (StrUtil.hasEmpty(authToken))
return null;
Claims body = Jwts.parser().setSigningKey(jwtProperties.getSecret()).parseClaimsJws(authToken).getBody();
String token = body.get("login_user_key") == null ? null : (String) body.get("login_user_key");
Object redisValue = redisCache.getCacheObject("login_tokens:" + token);
if (redisValue == null)
return null;
return JSONObject.parseObject(redisValue.toString(), LoginUser.class);
}
/**
* 跟新token有效时间
*/
public void refreshToken(LoginUser loginUser){
loginUser.setLoginTime(System.currentTimeMillis()); // 登录时间
loginUser.setExpireTime(loginUser.getLoginTime() + 30 * 60 * 1000); // 过期时间
String userKey = "login_tokens:" + loginUser.getToken();
redisCache.setCacheObject(userKey, JSONObject.toJSONString(loginUser), 30, TimeUnit.MINUTES);
}
}
|
package com.komaxx.komaxx_gl.texturing;
import java.nio.FloatBuffer;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.RectF;
import android.opengl.GLES20;
import android.opengl.GLUtils;
import com.komaxx.komaxx_gl.MipMapBitmaps;
import com.komaxx.komaxx_gl.RenderConfig;
import com.komaxx.komaxx_gl.RenderContext;
import com.komaxx.komaxx_gl.primitives.TexturedQuad;
import com.komaxx.komaxx_gl.util.KoLog;
import com.komaxx.komaxx_gl.util.RenderUtil;
public class TextureSegment {
private Texture texture;
private final short id;
protected int ownerId;
protected int lastUsedFrame = -1;
protected final Rect pixelCoords = new Rect();
protected final RectF uvCoords;
protected final boolean vertical;
private static Matrix bitmapRotMatrix = new Matrix();
private static RectF tmpRect = new RectF();
public TextureSegment(Texture t, short id, Rect pixelCoords, boolean rotated){
this.texture = t;
this.id = id;
this.vertical = rotated;
this.pixelCoords.set(pixelCoords);
this.uvCoords = t.getUvCoords(pixelCoords);
// if (vertical) {
// this.uvCoords.set(
// uvCoords.left, uvCoords.top,
// uvCoords.left + uvCoords.height(), uvCoords.top + uvCoords.width()
// );
// }
}
public short getId() {
return id;
}
public int getOwnerId() {
return ownerId;
}
/**
* Call this to mark the segment as still used by the current owner.
*/
public void finger(int frame) {
lastUsedFrame = frame;
}
public int getPixelWidth(){
return pixelCoords.width();
}
public int getPixelHeight(){
return pixelCoords.height();
}
public Rect getPixelCoords() {
return pixelCoords;
}
public RectF getUvCoords(){
return uvCoords;
}
/**
* Takes pixel coords inside of the Segment and returns texture-wide uvCoords
*/
public RectF getUvCoords(Rect r) {
return texture.getUvCoords(
r.left + pixelCoords.left,
r.top + pixelCoords.top,
r.right + pixelCoords.left,
r.bottom + pixelCoords.top);
}
public boolean update(RenderContext rc, Bitmap updateBitmap, int mipMapLevel){
TextureConfig config = texture.getConfig();
int sWidth = vertical ? pixelCoords.height() : pixelCoords.width();
int sHeight = vertical ? pixelCoords.width() : pixelCoords.height();
for (int i = 0; i < mipMapLevel; i++){
sWidth = sWidth/2;
sHeight = sHeight/2;
}
sWidth = Math.max(sWidth, 1);
sHeight = Math.max(sHeight, 1);
// does the configuration of the update image fit the texture?
if (
(config.alphaChannel && updateBitmap.getConfig() != Texture.ALPHA_CONFIG ) ||
(!config.alphaChannel && updateBitmap.getConfig() != Texture.OPAQUE_CONFIG) ||
(updateBitmap.getWidth() != sWidth || updateBitmap.getHeight() != sHeight)
){
Bitmap tmpBitmap = getTmpBitmap(sWidth, sHeight);
Canvas c = new Canvas(tmpBitmap);
tmpRect.left = 0; tmpRect.right = sWidth;
tmpRect.top = 0; tmpRect.bottom = sHeight;
c.drawBitmap(updateBitmap, null, tmpRect, null);
updateBitmap = tmpBitmap;
if (RenderConfig.GL_DEBUG){
KoLog.w(this, "Warning, incorrect update bitmap. Was adapted (slow)");
}
}
if (vertical){
bitmapRotMatrix.reset();
bitmapRotMatrix.postRotate(90);
bitmapRotMatrix.postTranslate(sHeight, 0);
Bitmap rotBitmap = getTmpBitmap(sHeight, sWidth);
rotBitmap.eraseColor(Color.TRANSPARENT);
Canvas c = new Canvas(rotBitmap);
c.drawBitmap(updateBitmap, bitmapRotMatrix, null);
updateBitmap = rotBitmap;
}
if (rc.boundTexture != texture.getHandle()){
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture.getHandle());
}
int format = config.alphaChannel ? GLES20.GL_RGBA : GLES20.GL_RGB;
int type = Texture.highResolutionColor ? GLES20.GL_UNSIGNED_BYTE :
(config.alphaChannel ? GLES20.GL_UNSIGNED_SHORT_4_4_4_4 : GLES20.GL_UNSIGNED_SHORT_5_6_5);
GLUtils.texSubImage2D(GLES20.GL_TEXTURE_2D, mipMapLevel,
pixelCoords.left >> mipMapLevel,
pixelCoords.top >> mipMapLevel,
updateBitmap, format, type);
// GLES20.glTexSubImage2D(GLES20.GL_TEXTURE_2D, mipMapLevel,
// pixelCoords.left >> mipMapLevel, pixelCoords.top >> mipMapLevel,
// sWidth, sHeight, format, type, updateBitmap.);
if (RenderConfig.GL_DEBUG) return !RenderUtil.checkGlError("Updating texture segment");
return true;
}
/**
* GL THREAD ONLY!
* @param sHeight
*/
protected Bitmap getTmpBitmap(int sWidth, int sHeight){
// TODO: A pooling/caching might be in order here!
// if (vertical && segmentTmpBmpVertical==null){
// segmentTmpBmpVertical = new MipMapBitmaps(config.segmentHeight, config.segmentWidth,
// getBitmapConfig(), 1000);
// } else if (!vertical && segmentTmpBmpHorizontal==null){
// segmentTmpBmpHorizontal = new MipMapBitmaps(config.segmentWidth, config.segmentHeight,
// getBitmapConfig(), 1000);
// }
// return vertical
// ? segmentTmpBmpVertical.getBitmaps()[mipMapLevel]
// : segmentTmpBmpHorizontal.getBitmaps()[mipMapLevel];
// TODO: MipMap levels!
return Bitmap.createBitmap(sWidth, sHeight, texture.getBitmapConfig());
}
@Override
public String toString() {
StringBuffer ret = new StringBuffer();
ret.append(id).append(": owner ").append(ownerId).append('(').append(lastUsedFrame).append("): ");
ret.append(vertical ? "|| " : "== ");
ret.append(pixelCoords.toShortString()).append(" -> ").append(uvCoords.toString());
return ret.toString();
}
/**
* Call this, when not the full segment is to be used as texture but only a horizontal part.
* Vertical, the full height will be used.
*/
public void applyUvMappingToQuad(FloatBuffer quadsData, int currentOffset, float widthPercentage){
tmpRect.set(uvCoords);
if (vertical){
tmpRect.bottom = uvCoords.top + uvCoords.height()*widthPercentage;
TexturedQuad.setUVMappingRotated(quadsData, currentOffset, tmpRect);
} else {
tmpRect.right = uvCoords.left + uvCoords.width()*widthPercentage;
TexturedQuad.setUVMapping(quadsData, currentOffset, tmpRect);
}
}
/**
* Call this, when not the full segment is to be used as texture but only a horizontal part.
* Vertical, the full height will be used.
*/
public void applyUvMappingToQuad(FloatBuffer quadsData, int currentOffset,
float hZoomFactor, float vZoomFactor){
tmpRect.set(uvCoords);
if (vertical){
tmpRect.bottom = uvCoords.top + uvCoords.height()*hZoomFactor;
tmpRect.left = uvCoords.right - uvCoords.width()*vZoomFactor;
TexturedQuad.setUVMappingRotated(quadsData, currentOffset, tmpRect);
} else {
tmpRect.right = uvCoords.left + uvCoords.width()*hZoomFactor;
tmpRect.bottom = uvCoords.top + uvCoords.height()*vZoomFactor;
TexturedQuad.setUVMapping(quadsData, currentOffset, tmpRect);
}
}
public void applyUvMappingToQuad(FloatBuffer quadsData, int currentOffset) {
if (vertical){
TexturedQuad.setUVMappingRotated(quadsData, currentOffset, uvCoords);
} else {
TexturedQuad.setUVMapping(quadsData, currentOffset, uvCoords);
}
}
public void update(RenderContext rc, MipMapBitmaps updateBitmaps, int startLevel) {
Bitmap[] bitmaps = updateBitmaps.getBitmaps();
int l = bitmaps.length;
for (int i = 0; i < l; i++){
update(rc, bitmaps[i], startLevel + i);
}
}
/**
* Builds a bitmap that fits the segment regarding size and config. The segment will
* not hold any references. Should be recycled as soon as the caller doesn't need it
* anymore.
*/
public Bitmap createTmpBmp() {
return Bitmap.createBitmap(
vertical ? pixelCoords.height() : pixelCoords.width(),
vertical ? pixelCoords.width() : pixelCoords.height(),
texture.getBitmapConfig());
}
public boolean isVertical() {
return vertical;
}
public void own(int nuOwnerId, int frame) {
ownerId = nuOwnerId;
lastUsedFrame = frame;
}
public int getLastUsedFrame() {
return lastUsedFrame;
}
public Texture getTexture() {
return texture;
}
}
|
package com.simplewidget.demo;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
public class DateTimePickerDemo extends Activity {
/** Called when the activity is first created. */
private TextView view = null;
private DatePicker date = null;
private TimePicker time = null;
private Button button1 = null;
private Button button2 = null;
Calendar c;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.datetimepicker);
view = (TextView) findViewById(R.id.dateview);
view.setText("当前时间");
// 取得系统时间对象
c = Calendar.getInstance();
date = (DatePicker) findViewById(R.id.date);
time = (TimePicker) findViewById(R.id.time);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button1.setText("a");
button2.setText("b");
date.init(c.get(Calendar.DAY_OF_YEAR), c.get(Calendar.MONTH), c
.get(Calendar.DAY_OF_MONTH),
new DatePicker.OnDateChangedListener() {
public void onDateChanged(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// 当日期改变时,在这里处理
c.set(year, monthOfYear, dayOfMonth);
}
});
// 设置为24小时制
time.setIs24HourView(true);
time.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
// 当前时间改变时,在这里处理
c.set(c.get(Calendar.DAY_OF_YEAR), c.get(Calendar.MONTH), c
.get(Calendar.DAY_OF_MONTH), c
.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), c
.get(Calendar.SECOND));
}
});
button1.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
new DatePickerDialog(DateTimePickerDemo.this,
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// 设置日历
}
}, c.get(Calendar.DAY_OF_YEAR), c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH)).show();
}
});
button2.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
new TimePickerDialog(DateTimePickerDemo.this,
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view,
int hourOfDay, int minute) {
// 设置时间
}
}, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE),
true).show();
}
});
}
}
|
package creational.factory.method;
public class SonyASeries extends Mobile {
public void experience() {
System.out.println("Sony Premium Hardware.");
}
}
|
package cn.tarena.ht.controller;
import cn.tarena.ht.pojo.Dept;
import cn.tarena.ht.pojo.Module;
import cn.tarena.ht.pojo.Role;
import cn.tarena.ht.pojo.User;
import cn.tarena.ht.service.DeptService;
import cn.tarena.ht.service.RoleService;
import cn.tarena.ht.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* Created by 12863 on 2017/7/10.
*/
@Controller
@RequestMapping("/sysadmin/user")
public class UserController {
@Resource
private UserService userService;
@Resource
private DeptService deptService;
@Resource
RoleService roleService;
//为用户分配角色
@RequestMapping("toRole")
public String toUserRole(Model model,String userId) throws JsonProcessingException {
//给所有角色信息
List<Role> list=roleService.findAllRoles();
//
/* StringBuffer zTree=new StringBuffer("[");
for (Role role:list) {
zTree.append("{id:\""+role.getId()+"\",name:\""+role.getName()+"\"},");
}
String s = zTree.substring(0, zTree.length() - 1);
s+="]";*/
List<String> roleList=roleService.findUSerRoleList(userId);
for (Role role:list) {
if (roleList.contains(role.getRoleId())){
role.setChecked("true");
}
}
ObjectMapper objectMapper=new ObjectMapper();
String s = objectMapper.writeValueAsString(list);
model.addAttribute("zTree",s);
model.addAttribute("userId",userId);
return "/sysadmin/user/jRoleUser";
}
//保存用户角色信息保存
@RequestMapping("saveUserRole")
public String saveUserRole(String userId,String[] roleIds){
userService.saveUserRole(userId,roleIds);
return "redirect:/sysadmin/user/list";
}
@RequestMapping("/list")
public String toUserList(Model model){
//获取user列表数据
List<User> userList = userService.findUserList();
model.addAttribute("userList", userList);
return "sysadmin/user/juserList";
}
@RequestMapping("delete")
public String deleteUser(@RequestParam("userId") String[] userIds){
userService.deleteUsers(userIds);
return "redirect:/sysadmin/user/list ";
}
@RequestMapping("start")
public String start(@RequestParam("userId") String[] userIds){
userService.updateUserState(userIds,1);
return "redirect:/sysadmin/user/list ";
}
@RequestMapping("stop")
public String stop(@RequestParam("userId") String[] userIds){
userService.updateUserState(userIds,0);
return "redirect:/sysadmin/user/list ";
}
//跳转添加页面
@RequestMapping("tocreate")
public String tocreate(Model model){
//获取部门列表
List<Dept> deptList = deptService.findDeptList();
model.addAttribute("deptList",deptList);
return "sysadmin/user/juserCreate";
}
@RequestMapping("save")
public String saveuser(User user){
userService.saveUser(user);
return "redirect:/sysadmin/user/list ";
}
@RequestMapping("manger")
@ResponseBody
public List<Map<String,Object>> userManger(String deptId){
List<Map<String,Object>> map=userService.findMangerList(deptId);
System.out.println(map);
return map;
}
}
|
package com.mygdx.ObjectInfo;
public class SkillDamageInfo extends AbstractStatsInfo {
public float skillAreaWidth;
public float skillAreaHeight;
public long duration;
public String skillTyp;
public String skillGroup;
}
|
package com.products.domain;
import com.products.data.entities.ProductEntity;
import com.products.domain.dto.Product;
import com.products.domain.filters.FilterByProducts;
import com.products.domain.mappers.ProductsMapper;
import com.products.domain.respository.ProductsRepository;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class UseCaseProducts {
private FilterByProducts filterByProducts;
private final ProductsRepository productListRepository;
private final Converter<List<ProductEntity>, List<Product>> productsMapper = new ProductsMapper();
private final double PERCENT_TO_DISCOUNT = 0.5;
public UseCaseProducts(final ProductsRepository useCaseProductsRepository,final FilterByProducts filterByProducts) {
this.productListRepository = useCaseProductsRepository;
this.filterByProducts = filterByProducts;
}
public List<Product> products(String searchedWord) {
List<ProductEntity> productsEntity = productListRepository.productsEntity();
productsEntity = this.filterProductsEntity(productsEntity, searchedWord);
List<Product> products = productsMapper.convert(productsEntity);
if (this.isPalindrome(searchedWord)) {
products = this.getDiscount(products);
}
return products;
}
public List<Product> products() {
List<ProductEntity> productsEntity = productListRepository.productsEntity();
List<Product> products = productsMapper.convert(productsEntity);
return products;
}
private List<ProductEntity> filterProductsEntity(List<ProductEntity> productsEntity, String filter) {
List<ProductEntity> productsEntityFilter;
if (this.isNumeric(filter)) {
int id = this.stringToInt(filter);
productsEntityFilter = filterByProducts.filterById(productsEntity, id);
} else {
productsEntityFilter = filterByProducts.filterByWord(productsEntity, filter);
}
return productsEntityFilter;
}
private boolean isNumeric(String searchedWord) {
String regex = "[0-9]*";
return searchedWord.matches(regex);
}
private int stringToInt(String wordSearched) {
return Integer.parseInt(wordSearched);
}
private boolean isPalindrome(String searchedWord) {
StringBuffer reverseString = new StringBuffer("");
for (int i = searchedWord.length() - 1; i >= 0; i--) {
reverseString.append(searchedWord.charAt(i));
}
if (searchedWord.equalsIgnoreCase(reverseString.toString())) {
return true;
}
return false;
}
private List<Product> getDiscount(List<Product> products) {
return products.stream()
.map(product -> Product.builder()
.id(product.getId())
.brand(product.getBrand())
.image(product.getImage())
.price(this.calculatePercent(product.getPrice(), PERCENT_TO_DISCOUNT))
.description(product.getDescription())
.discount(true)
.build())
.collect(Collectors.toList());
}
private Long calculatePercent(Long price, double percent) {
return (long) (price * percent);
}
}
|
package com.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.Bean.UserBean;
import com.Dao.UserDao;
public class UserServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
String username=req.getParameter("username");
String password=req.getParameter("password");
if (username==""||username==null) {
req.setAttribute("flag", "用户名不能为空");
req.getRequestDispatcher("login.jsp").forward(req, resp);
}
if (password==""||password==null) {
req.setAttribute("username",username);
req.setAttribute("flag", "密码不能为空");
req.getRequestDispatcher("login.jsp").forward(req, resp);
}
UserBean user=UserDao.get_User(username);
if (user.getPassword()==""||user.getPassword()==null) {
req.setAttribute("username",username);
req.setAttribute("flag", "用户名不存在");
req.getRequestDispatcher("login.jsp").forward(req, resp);
}
else if(password.equals(user.getPassword())){
req.getRequestDispatcher("MyJsp.jsp").forward(req, resp);
}else{
req.setAttribute("username",username);
req.setAttribute("flag", "密码错误");
req.getRequestDispatcher("login.jsp").forward(req, resp);
}
}
}
|
package com.hesoyam.pharmacy.util.report;
import com.hesoyam.pharmacy.util.report.label.ReportLabel;
import java.util.Objects;
public class ReportData<T extends ReportLabel<T>> implements Comparable<ReportData<T>>{
private T label;
private Double data;
public ReportData(T label, Double data){
this.label = label;
this.data = data;
}
public ReportData(T label, Integer data){
this.label = label;
this.data = Double.valueOf(data);
}
public T getLabel() {
return label;
}
public Double getData() {
return data;
}
public void addResult(ReportData<T> result){
this.data += result.getData();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ReportData)) return false;
ReportData<?> that = (ReportData<?>) o;
return getLabel().equals(that.getLabel());
}
@Override
public int hashCode() {
return Objects.hash(getLabel());
}
@Override
public int compareTo(ReportData<T> o) {
return this.label.compareTo(o.getLabel());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.