text
stringlengths 10
2.72M
|
|---|
package com.snxy.pay.serviceImpl;
import com.snxy.pay.config.BusinessTypeEnum;
import com.snxy.pay.dao.mapper.TradeResultMapper;
import com.snxy.pay.domain.TradeResult;
import com.snxy.pay.service.TradeResultService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Created by 24398 on 2018/11/19.
*/
@Service
@Slf4j
public class TradeResultServiceImpl implements TradeResultService {
@Resource
private TradeResultMapper tradeResultMapper;
@Override
@Transactional(rollbackFor = Exception.class)
public void logResult(TradeResult tradeResult) {
// 不同的交易类型不同的方式
String outTradeNo = tradeResult.getOutTradeNo();
Integer businessTypeId = tradeResult.getBusinessTypeId().intValue();
TradeResult historyTradeResult = null;
if(businessTypeId == BusinessTypeEnum.ENTRY_FEE.getBusinessTypeId()
|| businessTypeId == BusinessTypeEnum.ENTRY_DEPOSIT_FEE.getBusinessTypeId()){
// 进门收费
List<Integer> businessTypes = new ArrayList<>();
businessTypes.add(BusinessTypeEnum.ENTRY_FEE.getBusinessTypeId());
businessTypes.add(BusinessTypeEnum.ENTRY_DEPOSIT_FEE.getBusinessTypeId());
historyTradeResult = this.tradeResultMapper.selectPayResult(outTradeNo,businessTypes,false);
}else if(businessTypeId == BusinessTypeEnum.REFUND_DEPOSIT_FEE.getBusinessTypeId()
|| businessTypeId == BusinessTypeEnum.REFUND_ENTRY_FEE.getBusinessTypeId()){
// 退进门费和押金 退押金
// 先查寻
String outFundNo = tradeResult.getOutRefundNo();
historyTradeResult = this.tradeResultMapper.selectByOutTradeNoAndOutFundNo(outTradeNo,outFundNo,false);
}else if(businessTypeId == BusinessTypeEnum.CANCEL_PAY.getBusinessTypeId()){
// 撤销订单
// 有无历史撤销订单
historyTradeResult = this.tradeResultMapper.selectByOutTradeNoAndBusinessType(outTradeNo,businessTypeId,false);
}
if(historyTradeResult != null){
// 已有历史交易订单修改
this.insertOrUpdateTradeResult(tradeResult,historyTradeResult);
}else{
// 新建
this.tradeResultMapper.insertSelective(tradeResult);
}
}
public void insertOrUpdateTradeResult(TradeResult tradeResult,TradeResult historyTradeResult ){
if(historyTradeResult != null){
String resultCode = historyTradeResult.getResultCode();
if("SUCCESS".equalsIgnoreCase(resultCode)){
return;
}else{
tradeResult.setId(historyTradeResult.getId());
tradeResult.setGmtModified(new Date());
this.tradeResultMapper.updateByPrimaryKeySelective(tradeResult);
return;
}
}
}
@Override
public void updateSelective(TradeResult tradeResult) {
this.tradeResultMapper.updateByPrimaryKeySelective(tradeResult);
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.filter;
import java.io.IOException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.Test;
import org.springframework.web.testfixture.servlet.MockHttpServletRequest;
import org.springframework.web.testfixture.servlet.MockHttpServletResponse;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link HiddenHttpMethodFilter}.
*
* @author Arjen Poutsma
* @author Brian Clozel
*/
public class HiddenHttpMethodFilterTests {
private final HiddenHttpMethodFilter filter = new HiddenHttpMethodFilter();
@Test
public void filterWithParameter() throws IOException, ServletException {
filterWithParameterForMethod("delete", "DELETE");
filterWithParameterForMethod("put", "PUT");
filterWithParameterForMethod("patch", "PATCH");
}
@Test
public void filterWithParameterDisallowedMethods() throws IOException, ServletException {
filterWithParameterForMethod("trace", "POST");
filterWithParameterForMethod("head", "POST");
filterWithParameterForMethod("options", "POST");
}
@Test
public void filterWithNoParameter() throws IOException, ServletException {
filterWithParameterForMethod(null, "POST");
}
private void filterWithParameterForMethod(String methodParam, String expectedMethod)
throws IOException, ServletException {
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/hotels");
if(methodParam != null) {
request.addParameter("_method", methodParam);
}
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = (filterRequest, filterResponse) ->
assertThat(((HttpServletRequest) filterRequest).getMethod())
.as("Invalid method").isEqualTo(expectedMethod);
this.filter.doFilter(request, response, filterChain);
}
}
|
package com.raghu.alogirthms.sequencesandnumbers;
import java.util.Scanner;
/**
* Generate and print Fibonacci number by both recursion and iterative approaches.
* Fibonacci number is sum of previous two Fibonacci numbers fn= fn-1+ fn-2
* first 10 Fibonacci numbers are 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
*
* @author Raghavendra M Boregowda
*/
public class Fibonacci {
public static void main(String[] args) {
System.out.println("Enter number upto which Fibonacci series to print: ");
int fibonacciLength = new Scanner(System.in).nextInt();
System.out.println("Fibonacci series upto " + fibonacciLength + " numbers : ");
System.out.println("\nIterative approach:");
for (int i = 1; i <= fibonacciLength; i++) {
System.out.print(fibonacciIterative(i) + " ");
}
System.out.println("\n\n\nRecursive approach:");
for (int i = 1; i <= fibonacciLength; i++) {
System.out.print(fibonacciRecursive(i) + " ");
}
}
/*
* Generates Fibonacci number using recursive function.
* @return Fibonacci number
*/
private static int fibonacciRecursive(final int fibonacciLength){
if(fibonacciLength == 1 || fibonacciLength == 2){
return 1;
}
return fibonacciRecursive(fibonacciLength - 1) + fibonacciRecursive(fibonacciLength - 2);
}
/*
* Generates Fibonacci number using iteration.
* @return Fibonacci number
*/
private static int fibonacciIterative(final int fibonacciLength){
if(fibonacciLength == 1 || fibonacciLength == 2){
return 1;
}
int first = 1, second = 1, fibonacci = 1;
for(int i = 3; i <= fibonacciLength; i++){
fibonacci = first + second;
first = second;
second = fibonacci;
}
return fibonacci;
}
}
|
package com.wadi.set.logic;
import com.wadi.set.exceptions.WrongCardsAddedException;
import java.util.ArrayList;
import java.util.Collections;
public class CardState extends ArrayList<Card> {
public CardState() {
}
public void addCards(Card ... cards) throws WrongCardsAddedException {
if (cards.length == 3) {
Collections.addAll(this, cards);
} else {
throw new WrongCardsAddedException();
}
}
}
|
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.io.PrintStream;
import static java.lang.System.out;
public class writer {
Date today;
String pattern;
SimpleDateFormat Pattern;
PrintStream x;
PrintStream console;
public writer() throws FileNotFoundException{
//formatting the date
today = new Date();
pattern = "yyyy-MM-dd";
Pattern = new SimpleDateFormat(pattern);
Pattern.format(today);
//creating a file to read the date from.
x = new PrintStream(new File(today + " TASKS.txt"));
console = System.out;
}
public void setOutputConsole(PrintStream console){
System.setOut(console);
}
public void setOutputTasklist(PrintStream tasklist){
System.setOut(tasklist);
}
}
|
package com.deepakm.ui;
import com.deepakm.impl.Key;
import com.deepakm.impl.instrument.guitar.FretPosition;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
import java.awt.Color;
import java.awt.Component;
/**
* Created by dmarathe on 11/10/16.
*/
public class RadioButtonRenderer implements TableCellRenderer {
JRadioButton button;
Key key;
public RadioButtonRenderer(Key key) {
this.button = new JRadioButton();
this.button.setSelected(Boolean.FALSE);
this.key = key;
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
// System.out.println(value);
Object val = table.getModel().getValueAt(row, column);
if (val == null) {
return new JLabel(String.valueOf(""));
} else {
JRadioButton button = new JRadioButton();
button.setForeground(Color.RED);
button.updateUI();
if (val instanceof FretPosition) {
if (((FretPosition) val).getNote() == key) {
button.setSelected(Boolean.TRUE);
}
// button.getGraphics().setColor(Color.GREEN);
// table.setCellSelectionEnabled(true);
// table.getCellEditor().getTableCellEditorComponent(table, value, isSelected, row,
// column).setBackground(Color.GREEN);
}
button.setText(String.valueOf(val));
return button;
}
}
}
|
/*
* Copyright 2015-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.nanoframework.concurrent.scheduler.defaults.etcd;
import static org.nanoframework.core.context.ApplicationContext.Scheduler.ETCD_APP_NAME;
import static org.nanoframework.core.context.ApplicationContext.Scheduler.ETCD_CLIENT_ID;
import static org.nanoframework.core.context.ApplicationContext.Scheduler.ETCD_KEY_TTL;
import static org.nanoframework.core.context.ApplicationContext.Scheduler.ETCD_MAX_RETRY_COUNT;
import static org.nanoframework.core.context.ApplicationContext.Scheduler.ETCD_SCHEDULER_ANALYSIS;
import static org.nanoframework.core.context.ApplicationContext.Scheduler.ETCD_URI;
import static org.nanoframework.core.context.ApplicationContext.Scheduler.ETCD_USER;
import static org.nanoframework.concurrent.scheduler.SchedulerFactory.DEFAULT_SCHEDULER_NAME_PREFIX;
import static org.nanoframework.concurrent.scheduler.SchedulerFactory.THREAD_FACTORY;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.net.Inet4Address;
import java.net.URI;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import org.nanoframework.commons.crypt.CryptUtil;
import org.nanoframework.commons.util.Assert;
import org.nanoframework.commons.util.CollectionUtils;
import org.nanoframework.commons.util.MD5Utils;
import org.nanoframework.commons.util.StringUtils;
import org.nanoframework.concurrent.exception.SchedulerException;
import org.nanoframework.concurrent.scheduler.BaseScheduler;
import org.nanoframework.concurrent.scheduler.SchedulerAnalysis;
import org.nanoframework.concurrent.scheduler.SchedulerConfig;
import org.nanoframework.concurrent.scheduler.SchedulerFactory;
import org.nanoframework.concurrent.scheduler.SchedulerStatus;
import org.nanoframework.concurrent.scheduler.SchedulerStatus.Status;
import org.nanoframework.concurrent.scheduler.defaults.monitor.LocalJmxMonitorScheduler;
import com.google.common.collect.Lists;
import mousio.client.retry.RetryWithExponentialBackOff;
import mousio.etcd4j.EtcdClient;
import mousio.etcd4j.responses.EtcdKeysResponse;
/**
*
* @author yanghe
* @since 1.3
*/
public class EtcdScheduler extends BaseScheduler implements EtcdSchedulerOperate {
public static final String SYSTEM_ID = MD5Utils.md5(UUID.randomUUID().toString() + System.currentTimeMillis() + Math.random());
public static final String ROOT_RESOURCE = "/machairodus/" + System.getProperty(ETCD_USER, "");
public static final String DIR = ROOT_RESOURCE + '/' + SYSTEM_ID;
public static final String CLS_KEY = DIR + "/Scheduler.class";
public static final String INSTANCE_KEY = DIR + "/Scheduler.list";
public static final String INFO_KEY = DIR + "/App.info";
public static final boolean SCHEDULER_ANALYSIS_ENABLE = Boolean.parseBoolean(System.getProperty(ETCD_SCHEDULER_ANALYSIS, "false"));
private static String APP_NAME;
private final Set<Class<?>> clsSet;
private final int maxRetryCount = Integer.parseInt(System.getProperty(ETCD_MAX_RETRY_COUNT, "1"));
private final int timeout = Integer.parseInt(System.getProperty(ETCD_KEY_TTL, "120"));
private Map<Class<?>, String> clsIndex = new HashMap<Class<?>, String>();
private Map<String, String> indexMap = new HashMap<String, String>();
private boolean init = false;
private EtcdClient etcd;
public EtcdScheduler(final Set<Class<?>> clsSet) {
Assert.notNull(clsSet);
this.clsSet = clsSet;
final SchedulerConfig config = new SchedulerConfig();
config.setId("EtcdScheduler-0");
config.setName(DEFAULT_SCHEDULER_NAME_PREFIX + "EtcdScheduler-0");
config.setGroup("EtcdScheduler");
THREAD_FACTORY.setBaseScheduler(this);
config.setService((ThreadPoolExecutor) Executors.newFixedThreadPool(1, THREAD_FACTORY));
config.setInterval(60_000L);
config.setTotal(1);
config.setDaemon(Boolean.TRUE);
config.setBeforeAfterOnly(Boolean.TRUE);
config.setLazy(Boolean.TRUE);
setConfig(config);
setClose(false);
initEtcdClient();
if (etcd == null) {
throw new SchedulerException("Can not init Etcd Client");
}
}
@Override
public void before() {
}
@Override
public void execute() {
syncBaseDirTTL();
syncInfo();
if (SCHEDULER_ANALYSIS_ENABLE)
syncInstance();
}
public void syncBaseDirTTL() {
try {
if (!init) {
etcd.putDir(DIR).ttl(timeout).prevExist(false).send().get();
init = true;
} else {
etcd.putDir(DIR).ttl(timeout).prevExist(true).send().get();
}
} catch (final Throwable e) {
LOGGER.error("Put base dir error: " + e.getMessage(), e);
if (e.getMessage() != null && e.getMessage().indexOf("Key not found") > -1) {
reSync();
return;
}
if (e.getMessage() != null && e.getMessage().indexOf("Key already exists") > -1) {
init = true;
syncBaseDirTTL();
return;
}
// 异常2秒重试
thisWait(2000);
syncBaseDirTTL();
}
}
private void reSync() {
init = false;
clsIndex.clear();
indexMap.clear();
syncBaseDirTTL();
syncInfo();
syncClass();
syncInstance();
}
public void syncInfo() {
EtcdAppInfo info = new EtcdAppInfo();
info.setSystemId(SYSTEM_ID);
info.setAppName(APP_NAME);
info.setJmxEnable(LocalJmxMonitorScheduler.JMX_ENABLE);
info.setJmxRate(LocalJmxMonitorScheduler.JMX_RATE);
RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
info.setStartTime(runtime.getStartTime());
info.setUptime(runtime.getUptime());
String[] rt = runtime.getName().split("@");
info.setHostName(rt[1]);
info.setPid(rt[0]);
info.setAvailableProcessors(ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors());
try {
info.setIp(Inet4Address.getLocalHost().getHostAddress());
String value = CryptUtil.encrypt(info.toString(), SYSTEM_ID);
etcd.put(INFO_KEY, value).send().get();
} catch (Exception e) {
LOGGER.error("Send App info error: " + e.getMessage());
// 异常2秒重试
thisWait(2000);
syncBaseDirTTL();
}
}
public void syncClass() {
if (!CollectionUtils.isEmpty(clsSet)) {
final Iterator<Class<?>> iter = clsSet.iterator();
while (iter.hasNext()) {
try {
final Class<?> cls = iter.next();
String index;
EtcdKeysResponse response;
if ((index = clsIndex.get(cls)) != null) {
response = etcd.put(CLS_KEY + '/' + index, cls.getName()).prevExist(true).send().get();
} else {
response = etcd.post(CLS_KEY, cls.getName()).send().get();
if (response.node != null) {
if ((index = response.node.key.substring(response.node.key.lastIndexOf('/'))) != null) {
clsIndex.put(cls, index);
}
}
}
LOGGER.debug("Class Sync: " + cls.getName());
} catch (Exception e) {
LOGGER.error("Send to Etcd error: " + e.getMessage());
}
}
}
}
public void syncInstance() {
final Collection<BaseScheduler> started = SchedulerFactory.getInstance().getStartedScheduler();
final Collection<BaseScheduler> stopping = SchedulerFactory.getInstance().getStoppingScheduler();
final Collection<BaseScheduler> stopped = SchedulerFactory.getInstance().getStoppedScheduler();
if (!CollectionUtils.isEmpty(started)) {
for (BaseScheduler scheduler : started) {
start(scheduler.getConfig().getGroup(), scheduler.getConfig().getId(), scheduler.getAnalysis());
}
}
if (!CollectionUtils.isEmpty(stopping)) {
for (BaseScheduler scheduler : stopping) {
stopping(scheduler.getConfig().getGroup(), scheduler.getConfig().getId(), scheduler.getAnalysis());
}
}
if (!CollectionUtils.isEmpty(stopped)) {
for (BaseScheduler scheduler : stopped) {
stopped(scheduler.getConfig().getGroup(), scheduler.getConfig().getId(), false, scheduler.getAnalysis());
}
}
}
@Override
public void after() {
}
@Override
public void destroy() {
}
private final void initEtcdClient() {
/** create ETCD client instance */
final String username = System.getProperty(ETCD_USER, "");
final String clientId = CryptUtil.decrypt(System.getProperty(ETCD_CLIENT_ID, ""), username);
APP_NAME = System.getProperty(ETCD_APP_NAME, "");
final String[] uris = System.getProperty(ETCD_URI, "").split(",");
if (!StringUtils.isEmpty(username.trim()) && !StringUtils.isEmpty(clientId.trim()) && !StringUtils.isEmpty(APP_NAME.trim())
&& uris.length > 0) {
final List<URI> uriList = Lists.newArrayList();
for (String uri : uris) {
if (StringUtils.isEmpty(uri)) {
continue;
}
try {
uriList.add(URI.create(uri));
} catch (final Throwable e) {
LOGGER.error("Etcd URI Error: " + e.getMessage());
}
}
if (uriList.size() > 0) {
etcd = new EtcdClient(username, clientId, uriList.toArray(new URI[uriList.size()]));
etcd.setRetryHandler(new RetryWithExponentialBackOff(20, maxRetryCount, 1000));
}
}
}
private EtcdKeysResponse put(final String key, final SchedulerStatus status) {
try {
String index;
EtcdKeysResponse response;
final String value = CryptUtil.encrypt(status.toString(), SYSTEM_ID);
if ((index = indexMap.get(status.getId())) != null) {
response = etcd.put(key + '/' + index, value).prevExist(true).send().get();
} else {
response = etcd.post(key, value).send().get();
if (response.node != null) {
if ((index = response.node.key.substring(response.node.key.lastIndexOf('/'))) != null) {
indexMap.put(status.getId(), index);
}
}
}
return response;
} catch (final Throwable e) {
LOGGER.error("Put to etcd error: " + e.getMessage());
}
return null;
}
private EtcdKeysResponse delete(final String key, final SchedulerStatus status) {
try {
String index;
EtcdKeysResponse response = null;
if ((index = indexMap.get(status.getId())) != null) {
response = etcd.delete(key + '/' + index).send().get();
indexMap.remove(status.getId());
}
return response;
} catch (final Throwable e) {
LOGGER.error("Delete etcd file error: " + e.getMessage());
}
return null;
}
@Override
public void start(final String group, final String id, final SchedulerAnalysis analysis) {
put(INSTANCE_KEY, new SchedulerStatus(group, id, Status.STARTED, analysis));
}
@Override
public void stopping(final String group, final String id, final SchedulerAnalysis analysis) {
put(INSTANCE_KEY, new SchedulerStatus(group, id, Status.STOPPING, analysis));
}
@Override
public void stopped(final String group, final String id, final boolean isRemove, final SchedulerAnalysis analysis) {
SchedulerStatus status = new SchedulerStatus(group, id, Status.STOPPED, analysis);
if (!isRemove) {
put(INSTANCE_KEY, status);
} else {
delete(INSTANCE_KEY, status);
}
}
public EtcdClient getEtcd() {
return etcd;
}
public static String getAppName() {
return APP_NAME;
}
}
|
package org.bnguyen.cc.graph;
/**
* Created by Binh Van Nguyen (binhnv80@gmail.com)
*/
public interface EdgeContainer<V, E> {
boolean addEdge(E e);
boolean containsEdge(E e);
E getEdge(V source, V target);
void removeEdge(E e);
int size();
}
|
public class SumOddRange {
public static boolean isOdd(int number){
if(number<0)
return false;
else return number % 2 != 0;
}
public static int sumOdd(int start,int end){
if(end<=0 || start <= 0) {
return -1;
}
if(end<start)
return -1;
int sum =0;
for (int i=start;i<=end;i++){
if(isOdd(i)){
sum +=i;
}
}
return sum;
}
}
|
/** #dynamic-programming */
import java.util.Scanner;
class IngenuousCubrency {
public static long calculate(int amounts, int[] elements) {
int len = elements.length;
long[] result = new long[amounts + 1];
result[0] = 1;
for (int i = 0; i < len; i++) {
for (int j = elements[i]; j <= amounts; j++) {
result[j] += result[j - elements[i]];
}
}
return result[amounts];
}
public static void main(String[] args) {
int[] arr = new int[21];
for (int i = 1; i <= arr.length; i++) {
arr[i - 1] = i * i * i;
}
Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()) {
int amounts = sc.nextInt();
long result = calculate(amounts, arr);
System.out.println(result);
}
}
}
|
package com.layduo.framework.config;
/**
* 日期时间格式化、适用于jdk1.8日期类型LocalDate 和 LocalDateTime
* @author layduo
* @createTime 2019年12月10日 下午5:25:00
* @learn to : https://blog.csdn.net/Linchack/article/details/88791785
*/
import java.time.format.DateTimeFormatter;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
@Configuration
public class DateTimeFormatConfig {
private static final String DATE_FORMAT = "yyyy-MM-dd";
private static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
return builder -> {
builder.simpleDateFormat(DATETIME_FORMAT);
builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(DATE_FORMAT)));
builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATETIME_FORMAT)));
};
}
}
|
package com.zyxo.hubformatapp.base.services;
import com.zyxo.hubformatapp.base.domain.Extent;
import com.zyxo.hubformatapp.base.domain.Hbdf;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
@Service
public class WriteInExcelService {
private static final String FILE_NAME_MATRIX = "src/main/resources/data/HBDF_matrix.xls";
private static final String FILE_NAME_COO = "src/main/resources/data/HBDF_coo.xls";
public XSSFWorkbook writeMatrix(Hbdf hbdf) {
List<Extent> torso = hbdf.getTypeOfMeasurement().getIso_7250().getTorso().getExtent();
List<Extent> head = hbdf.getTypeOfMeasurement().getIso_7250().getHead().getExtent();
List<Extent> arm = hbdf.getTypeOfMeasurement().getIso_7250().getArm().getExtent();
List<Extent> leg = hbdf.getTypeOfMeasurement().getIso_7250().getLeg().getExtent();
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("HBDF_matrix");
Object[][] datatypes = {
{"","sn","gn", "nk", "us", "ch", "an1","an2", "is1", "is2", "ew", "hd", "ke", "ta", "gd", "ft", "bk"},
{"sn",
getValue(head, "Sellion"),
calcWeight(head, "Sellion", head, "Gnathion"),
0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{"gn",
getValue(head, "Gnathion"), 0,
calcWeight(torso, "Neck", head, "Gnathion"),
0,0,0,0,0,0,0,0,0,0,0,0,0},
{"nk",0,
calcWeight(head, "Gnathion", torso, "Neck"),
getValue(torso, "Neck"),
0,calcWeight(torso, "Neck", torso, "Umbilicus"),
0, calcWeight(torso, "Neck", torso, "Acromion"),
0,0,0,0,0,0,0,0,0},
{"us",0,0,calcWeight(torso, "Umbilicus", torso, "Neck"),
getValue(torso, "Umbilicus"),
calcWeight(torso, "Umbilicus", torso, "Crotch"),
0,0,0,0,0,0,0,0,0,0,0},
{"ch",0,0,0,calcWeight(torso, "Crotch", torso, "Umbilicus"),
0,0,0, calcWeight(torso, "Crotch", torso, "Iliac spine"),
0,0,0,0,0,0,0,0},
{"an1",0,0,calcWeight(torso, "Acromion", torso, "Neck"),
0,0,0, calcWeight(torso, "Acromion", torso, "Acromion"),
0,0,calcWeight(torso, "Crotch", arm, "Elbow"),
0,0,0,0,0,0},
{"an2", 0,0,0,0,0, calcWeight(torso, "Acromion", torso, "Acromion"),
getValue(torso, "Acromion"),0,0,0,0,0,0,0,0,0},
{"is",0,0,0,0, calcWeight(torso, "Iliac spine", torso, "Crotch"),
0,0,0,calcWeight(torso, "Iliac spine", torso, "Iliac spine"),
0,0,calcWeight(torso, "Iliac spine", leg, "Knee"),0,0,0,0},
{"is",0,0,0,0,0,0,0, calcWeight(torso, "Iliac spine", torso, "Iliac spine"),
0,0,0,0,0,0,0,0},
{"ew",0,0,0,0,0,calcWeight(arm, "Elbow", torso, "Acromion"),
0,0,0,0,calcWeight(arm, "Elbow", arm, "Hand"),0,0,0,0,0},
{"hd",0,0,0,0,0,0,0,0,0,calcWeight(arm, "Hand", arm, "Elbow"),
getValue(arm, "Hand"),0,0,0,0,0},
{"ke",0,0,0,0,0,0,0,calcWeight(leg, "Knee", torso, "Iliac spine"),0,0,0,
getValue(leg, "Knee"),
calcWeight(torso, "Iliac spine", leg, "Tibia"),0,0,
calcWeight(torso, "Iliac spine", torso, "Buttlock")},
{"ta",0,0,0,0,0,0,0,0,0,0,0,0,
calcWeight(leg, "Tibia", leg, "Knee"),
getValue(leg, "Tibia"),0,0},
{"gd",0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{"ft",0,0,0,0,0,0,0,0,0,0,0,0,0,
getValue(leg, "Foot"),0,0},
{"bk",0,0,0,0,0,0,0,0,0,0,0,
calcWeight(torso, "Buttlock", leg, "Knee"),0,0,0,0}
};
int rowNum = 0;
System.out.println("Creating excel for matrix");
if (getPrintXlsx(workbook, sheet, datatypes, rowNum)) return workbook;
return null;
}
private boolean getPrintXlsx(XSSFWorkbook workbook, XSSFSheet sheet, Object[][] datatypes, int rowNum) {
for (Object[] datatype : datatypes) {
Row row = sheet.createRow(rowNum++);
int colNum = 0;
for (Object field : datatype) {
Cell cell = row.createCell(colNum++);
if (field instanceof String) {
cell.setCellValue((String) field);
} else if (field instanceof Integer) {
cell.setCellValue((Integer) field);
}
}
}
try {
FileOutputStream outputStream = new FileOutputStream(FILE_NAME_MATRIX);
workbook.write(outputStream);
workbook.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
public XSSFWorkbook writeCoo(Hbdf hbdf) {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("HBDF_coo");
Object[][] datatypes = {
{"val", "C11", "M11", "M12", "C12", "M21", "M24", "M21","C21","M22","M22","M26",
"M24","M23","M31","M23","C22","M26","M25","M41","M25","M31","M32","M32",
"C31","M41","C41","M42","M45","M42","C42","M43","M43","M44","M44","M45"},
{"row", 2,2,4,4,4,4,5,5,5,6,6,7,7,7,8,8,9,9,9,10,11,11,12,12,13,13,13,13,14,14,14,15,16,16,17},
{"col", 2,3,2,4,3,4,6,8,4,5,6,5,9,4,8,11,7,8,6,10,13,9,7,12,11,12,9,13,14,17,14,15,15,13,16}
};
int rowNum = 0;
System.out.println("Creating excel for COO");
for (Object[] datatype : datatypes) {
Row row = sheet.createRow(rowNum++);
int colNum = 0;
for (Object field : datatype) {
Cell cell = row.createCell(colNum++);
if (field instanceof String) {
cell.setCellValue((String) field);
} else if (field instanceof Integer) {
cell.setCellValue((Integer) field);
}
}
}
try {
FileOutputStream outputStream = new FileOutputStream(FILE_NAME_COO);
workbook.write(outputStream);
workbook.close();
return workbook;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private String calcWeight(List<Extent> firstEx, String firstType, List<Extent> secondEx, String SecondType){
Double firstMes = Double.parseDouble(getValue(firstEx, firstType));
Double secondMes = Double.parseDouble(getValue(secondEx, SecondType));
return String.valueOf(Math.sqrt((Math.pow(firstMes, 2)/4) + Math.pow(firstMes-secondMes, 2)));
}
private String getValue(List<Extent> typeOfBody, String type) {
return typeOfBody.stream().filter(p -> p.getType().equals(type)
&& p.getMeasurement().equals("height")).findAny().get().getValue();
}
}
|
package controller;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Rectangle;
import javafx.util.Callback;
import model.match.Match;
import model.match.MatchResult;
import model.team.Team;
import model.team.TeamTournamentDetails;
import util.MiscUtilities;
import engine.ai.MatchSimEngine;
import engine.util.Misc;
public class GamePortalController implements IController, Initializable {
private String screenName;
private MasterController masterController;
@Override
public void initialize(URL location, ResourceBundle resources)
{
}
@Override
public void setMasterController(MasterController masterController)
{
this.masterController = masterController;
}
@Override
public String getScreenName()
{
return this.screenName;
}
@Override
public void setScreenName(String name)
{
this.screenName = name;
}
@FXML
private TableColumn<TeamTournamentDetails, Number> rankColumn, playedColumn, tiedColumn,
wonColumn, nrrColumn, pointsColumn, lostColumn;
@FXML
private TableColumn<TeamTournamentDetails, TeamTournamentDetails> last5Column;
@FXML
private TableColumn<TeamTournamentDetails, String> teamColumn;
@FXML
private TableView<TeamTournamentDetails> pointsTableTableView;
@FXML
private Label leftStatusLabel, randomInfoLabel, rightStatusLabel;
@FXML
private ImageView homeTeamLogoImageView, matchInfoImageView, iplLogoImageView, awayTeamLogoImageView;
@FXML
private ListView<Match> matchListListView;
@FXML
private Button continueButton;
@FXML
private void handleContinueClick(ActionEvent event)
{
Button b = (Button)event.getSource();
if(b.getText().equals("Play Match"))
{
PlayingElevenSelectionController pesc = (PlayingElevenSelectionController)masterController.getController("PlayingElevenSelection");
pesc.setTeam(masterController.getTournament().getUserTeam());
this.masterController.changeScreenTo("PlayingElevenSelection");
}
else if(b.getText().equals("Sim Match"))
{
MatchSimEngine.simMatch(Misc.findActiveMatch(masterController.getTournament().getMatches()));
}
}
public void setupScreen()
{
ObservableList<Match> matches = FXCollections.observableArrayList(masterController.getTournament().getMatches());
matchListListView.setItems(matches);
matchListListView.setCellFactory(new Callback<ListView<Match>, ListCell<Match>>() {
@Override
public ListCell<Match> call(ListView<Match> list) {
return new ListCell<Match>(){
private Label l;
private HBox hbox;
private ImageView iv;
private Image cskImage;
{
hbox = new HBox();
hbox.setSpacing(10);
l = new Label();
cskImage = new Image("file:resources/images/teams/" + "CSK" + ".png");
iv = new ImageView();
iv.setFitHeight(50);
iv.setFitWidth(50);
}
@Override
protected void updateItem(Match item, boolean empty) {
super.updateItem(item, empty);
if(item==null||empty) {
setText(null);
}
else
{
try
{
//MiscUtilities.log("updating item");
hbox.getChildren().clear();
l.setText(item.getTeams().get(0).getShortName()+ " vs. " + item.getTeams().get(1).getShortName());
if(matchListListView.getSelectionModel().getSelectedItem()==item)
{
iv.setImage(cskImage);
hbox.getChildren().add(iv);
}
hbox.getChildren().add(l);
//setText("8:00pm - " + item.getStadium().getName());
setGraphic(hbox);
}
catch (Exception e)
{
MiscUtilities.log("Error encountered while updating items of the Matchlistlistview at GamePortalController.java: " + e.toString());
}
}
}
};
}
});
matchListListView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Match>() {
@Override
public void changed(ObservableValue<? extends Match> observable,
Match oldValue, Match newValue) {
matches.set(matchListListView.getSelectionModel().getSelectedIndex(), newValue);
}
});
ObservableList<TeamTournamentDetails> ttdl = FXCollections.observableArrayList();
for(Team t: masterController.getTournament().getTeams())
{
ttdl.add(t.getTeamTournamentDetails());
}
rankColumn.setCellValueFactory(cellData -> cellData.getValue().rankProperty());
teamColumn.setCellValueFactory(cellData -> cellData.getValue().getTeam().shortNameProperty());
playedColumn.setCellValueFactory(cellData -> cellData.getValue().matchesPlayedProperty());
wonColumn.setCellValueFactory(cellData -> cellData.getValue().matchesWonProperty());
lostColumn.setCellValueFactory(cellData -> cellData.getValue().matchesLostProperty());
tiedColumn.setCellValueFactory(cellData -> cellData.getValue().matchesTiedProperty());
nrrColumn.setCellValueFactory(cellData -> cellData.getValue().netRunRateProperty());
pointsColumn.setCellValueFactory(cellData -> cellData.getValue().pointsProperty());
last5Column.setCellValueFactory(cellData -> new SimpleObjectProperty<TeamTournamentDetails>(cellData.getValue()));
last5Column.setCellFactory(new Callback<TableColumn<TeamTournamentDetails,TeamTournamentDetails>, TableCell<TeamTournamentDetails,TeamTournamentDetails>>() {
@Override
public TableCell<TeamTournamentDetails, TeamTournamentDetails> call(
TableColumn<TeamTournamentDetails, TeamTournamentDetails> param) {
return new TableCell<TeamTournamentDetails, TeamTournamentDetails>(){
private HBox hbox;
{
hbox = new HBox(5);
}
@Override
protected void updateItem(TeamTournamentDetails item, boolean empty)
{
if(item==null&&!empty)
{
for(int i =0;i<5;i++)
{
Paint p = Paint.valueOf("Gray");
Rectangle r = new Rectangle(10, 10, p);
hbox.getChildren().add(r);
}
}
else if(item!=null)
{
for(int i=0; i<5;i++)
{
Paint p;
try
{
if(item.getMatchResults().get(item.getMatchResults().size()-1-i) == MatchResult.Won) p=Paint.valueOf("Green");
else if(item.getMatchResults().get(item.getMatchResults().size()-1-i) == MatchResult.Lost) p=Paint.valueOf("Red");
else { p =Paint.valueOf("Gray"); }
}
catch (Exception e)
{
p =Paint.valueOf("Gray");
}
hbox.getChildren().add(new Rectangle(10, 10, p));
}
}
setGraphic(hbox);
};
};
}
});
pointsTableTableView.setItems(ttdl);
masterController.getTournament().setUserTeam(matches.get(0).getTeams().get(0));
if(Misc.findActiveMatch(masterController.getTournament().getMatches()).getTeams().contains(masterController.getTournament().getUserTeam()))
{
continueButton.setText("Play Match");
}
else
{
continueButton.setText("Sim Match");
}
}
@FXML
private void handleSaveAndBackClick(ActionEvent e)
{
masterController.changeScreenTo("StartMenu");
}
}
|
package com.alibaba.druid.bvt.sql;
import junit.framework.TestCase;
import org.junit.Assert;
import com.alibaba.druid.sql.ast.SQLDataTypeImpl;
import com.alibaba.druid.sql.ast.expr.SQLCastExpr;
import com.alibaba.druid.sql.dialect.oracle.parser.OracleExprParser;
public class EqualTest_cast extends TestCase {
public void test_exits() throws Exception {
String sql = "cast(a as varchar(50))";
String sql_c = "cast(b as varchar(50))";
SQLCastExpr exprA, exprB, exprC;
{
OracleExprParser parser = new OracleExprParser(sql);
exprA = (SQLCastExpr) parser.expr();
}
{
OracleExprParser parser = new OracleExprParser(sql);
exprB = (SQLCastExpr) parser.expr();
}
{
OracleExprParser parser = new OracleExprParser(sql_c);
exprC = (SQLCastExpr) parser.expr();
}
Assert.assertEquals(exprA, exprB);
Assert.assertNotEquals(exprA, exprC);
Assert.assertTrue(exprA.equals(exprA));
Assert.assertFalse(exprA.equals(new Object()));
Assert.assertEquals(exprA.hashCode(), exprB.hashCode());
Assert.assertEquals(new SQLCastExpr(), new SQLCastExpr());
Assert.assertEquals(new SQLCastExpr().hashCode(), new SQLCastExpr().hashCode());
Assert.assertEquals(new SQLDataTypeImpl(), new SQLDataTypeImpl());
Assert.assertEquals(new SQLDataTypeImpl().hashCode(), new SQLDataTypeImpl().hashCode());
}
}
|
package com.codetop.dp;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Test;
@Slf4j
public class MaxProfit {
/**
* j->0,表示当前不持股
* j->1,表示当前持股
* dp[i][j] 表示i这一天结束的时候,手上持股状态为j时,我们持有的现金数
* basecase:
* dp[i][0] i这天,不持股
* 1.昨天不持股,今天什么都不做
* 2.昨天持股,今天卖出股票(现金增加)
* dp[i][1] i这天,持股
* 1.昨天持股,今天什么都不做(现金不变)
* 2.昨天不持股,今天买入股票
*
* @param prices
* @return
*/
public int maxProfit(int[] prices) {
int[][][] dp = new int[prices.length][2][2];
dp[0][1][0] = 0;
//basecase定义错误,导致最终一直没有解出来
dp[0][1][1] = -prices[0];
for (int i = 1; i < prices.length; i++) {
dp[i][1][0] = Math.max(dp[i - 1][1][0], dp[i - 1][1][1] + prices[i]);
dp[i][1][1] = Math.max(dp[i - 1][1][1], -prices[i]);
}
return dp[prices.length - 1][1][0];
}
/**
* 买卖股票的最佳时机||
*
* @param prices
* @return
*/
public int maxProfit2(int[] prices) {
int[][] dp = new int[prices.length][2];
dp[0][0] = 0;
dp[0][1] = -prices[0];
for (int i = 1; i < prices.length; i++) {
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
}
return dp[prices.length - 1][0];
}
/**
* 买卖股票的最佳时机|||
*
* @param prices
* @return
*/
public int maxProfit3(int[] prices) {
int[][][] dp = new int[prices.length][3][2];
dp[0][0][0] = 0;
dp[0][0][1] = 0;
//缺少次数的basecase,导致结果一直有问题
for (int i = 1; i < 3; i++) {
dp[0][i][0] = 0;
dp[0][i][1] = -prices[0];
}
for (int i = 1; i < prices.length; i++) {
for (int k = 1; k < 3; k++) {
dp[i][k][0] = Math.max(dp[i - 1][k][0], dp[i - 1][k][1] + prices[i]);
dp[i][k][1] = Math.max(dp[i - 1][k][1], dp[i - 1][k - 1][0] - prices[i]);
}
}
return dp[prices.length - 1][2][0];
}
/**
* 188. 买卖股票的最佳时机 IV
* @param prices
* @return
*/
public int maxProfit4(int k,int[] prices) {
int[][][] dp = new int[prices.length][k+1][2];
dp[0][0][0] = 0;
dp[0][0][1] = 0;
//缺少次数的basecase,导致结果一直有问题
for (int i = 1; i < k+1; i++) {
dp[0][i][0] = 0;
dp[0][i][1] = -prices[0];
}
for (int i = 1; i < prices.length; i++) {
for (int j = 1; j < k+1; j++) {
dp[i][j][0] = Math.max(dp[i - 1][j][0], dp[i - 1][j][1] + prices[i]);
dp[i][j][1] = Math.max(dp[i - 1][j][1], dp[i - 1][j - 1][0] - prices[i]);
}
}
return dp[prices.length - 1][k][0];
}
/**
*
* @param prices
* @return
*/
public int maxProfit1(int[] prices) {
int[][] dp = new int[prices.length][2];
dp[0][0] = 0;
dp[0][1] = -prices[0];
for (int i = 1; i < prices.length; i++) {
dp[i][0] = Math.max(dp[i-1][0],dp[i-1][1]+prices[i]);
log.info("dp[{}][0]={}",i,dp[i][0]);
//因为dp[i][0]已经使用了一次交易了,所以dp[i-1][0]的值肯定为0
dp[i][1] = Math.max(dp[i-1][1],-prices[i]);
log.info("dp[{}][1]={}",i,dp[i][1]);
}
return dp[prices.length-1][0];
}
@Test
public void test() {
/**
* 输入:[7,1,5,3,6,4]
* 输出:5
*
*/
int[] nums = new int[]{7, 1, 5, 3, 6, 4};
Assert.assertEquals(5, maxProfit1(nums));
int[] nums2 = new int[]{1,2,3,4,5};
Assert.assertEquals(4, maxProfit3(nums2));
}
}
|
package Repository;
import Model.ProgramState.ProgramState;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.List;
public class Repository implements IRepository {
private String logFilePath;
private List<ProgramState> programStateList;
public Repository(String filePath) {
programStateList = new LinkedList<>();
logFilePath = filePath;
}
@Override
public List<ProgramState> getProgramList() {
return programStateList;
}
@Override
public void setProgramList(List<ProgramState> programList) {
programStateList = programList;
}
@Override
public void addProgramState(ProgramState program) {
programStateList.add(program);
}
@Override
public void logProgramStateExecution(ProgramState state) {
try {
PrintWriter logFile = new PrintWriter(new BufferedWriter(new FileWriter(logFilePath, true)));
logFile.print(state.toString());
logFile.close();
}
catch (IOException io){
System.out.println(io.getMessage());
}
}
}
|
package com.jgw.supercodeplatform.project.zaoyangpeach.service;
public class DataSyncService {
}
|
package com.cpro.rxjavaretrofit.entity;
/**
* Created by lx on 2016/5/23.
*/
public class FilterEntity {
private int id;
private String name;
public FilterEntity(int id, String name){
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
public class Chocolate{
public static int breakChocolate(int n, int m) {
int breaks=0;
if(n<=0&&m<=0){
return breaks;
}else{
int chocolates=n*m;
while(chocolates%2==0){
breaks++;
}
return breaks;
}
}
|
package swsk.cn.rgyxtq.subs.user.V;
/**
* Created by apple on 16/3/11.
*/
public interface MultiItemTypeSupport<T>{
int getLayoutId(int position,T t);
int getViewTypeCount();
int getItemViewType(int position,T t);
}
|
package com.core;
public class MovementSystem {
private boolean canMove;
private float moveSpeed;
private boolean left;
private boolean right;
private boolean up;
private boolean down;
private GameObject go;
public MovementSystem(GameObject go) {
this.go = go;
moveSpeed = 3;
}
public boolean canMove() {
return canMove;
}
public void setCanMove(boolean canMove) {
this.canMove = canMove;
}
public float getMoveSpeed() {
return moveSpeed;
}
public void setMoveSpeed(float moveSpeed) {
this.moveSpeed = moveSpeed;
}
public boolean isLeft() {
return left;
}
public void setLeft() {
clearMovements();
this.left = true;
}
public boolean isRight() {
return right;
}
public void setRight() {
clearMovements();
this.right = true;
}
public boolean isUp() {
return up;
}
public void setUp() {
clearMovements();
go.isJumping = true;
this.up = true;
}
public boolean isDown() {
return down;
}
public void setDown() {
clearMovements();
this.down = true;
}
public void move() {
if (right) {
go.getPosition().x += moveSpeed;
}
if (left) {
go.getPosition().x -= moveSpeed;
}
if (up) {
go.getPosition().y -= moveSpeed;
}
if (down) {
go.getPosition().y += moveSpeed;
}
}
public boolean isStopped() {
return go.getPosition().equals(go.getPositionDest());
}
public void clearMovements() {
up = false;
down = false;
right = false;
left = false;
canMove = false;
}
}
|
package ch.ethz.geco.t4j.internal;
import ch.ethz.geco.t4j.obj.ITournament;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
public class FeaturedTournamentFilter {
private String name;
private List<String> disciplines = new ArrayList<>();
private List<ITournament.Status> statuses = new ArrayList<>();
private LocalDate scheduledBefore;
private LocalDate scheduledAfter;
private List<String> countries = new ArrayList<>();
private List<String> platforms = new ArrayList<>();
private Boolean isOnline;
private Sorting sort;
/**
* Partially filters by name. It will match with tournaments containing the given string as substring.
*
* @param name The name to filter by.
*/
public FeaturedTournamentFilter withName(String name) {
this.name = name;
return this;
}
/**
* Adds a discipline to filter by.
*
* @param discipline A discipline to filter by.
*/
public FeaturedTournamentFilter addDiscipline(String discipline) {
this.disciplines.add(discipline);
return this;
}
/**
* Adds a status to filter by.
*
* @param status A status to filter by.
*/
public FeaturedTournamentFilter addStatus(ITournament.Status status) {
this.statuses.add(status);
return this;
}
/**
* Show only tournaments before or at the given date.
*
* @param date The date after which tournaments get filtered out.
*/
public FeaturedTournamentFilter beforeDate(LocalDate date) {
this.scheduledBefore = date;
return this;
}
/**
* Show only tournaments after or at the given date
*
* @param date The date before which tournaments get filtered out.
*/
public FeaturedTournamentFilter afterDate(LocalDate date) {
this.scheduledAfter = date;
return this;
}
/**
* Adds a country to filter by.
*
* @param country A country to filter by.
*/
public FeaturedTournamentFilter addCountry(String country) {
this.countries.add(country);
return this;
}
/**
* Adds a platform to filter by.
*
* @param platform A platform to filter by.
*/
public FeaturedTournamentFilter addPlatform(String platform) {
this.platforms.add(platform);
return this;
}
/**
* Filter by tournaments that are specifically only online or local.
*
* @param isOnline If the tournaments should be filtered by only online or only.
*/
public FeaturedTournamentFilter isOnline(Boolean isOnline) {
this.isOnline = isOnline;
return this;
}
/**
* Sort the result either ascending or descending by their scheduled date.
*
* @param sort How to sort the tournaments.
*/
public FeaturedTournamentFilter sort(Sorting sort) {
this.sort = sort;
return this;
}
/**
* Gets the query string to filter by the properties currently set.
*
* @return The query string to filter by the currently properties.
*/
public String getQueryString() {
List<NameValuePair> queryParameters = new ArrayList<>();
if (name != null) {
queryParameters.add(new BasicNameValuePair("name", name));
}
if (disciplines.size() > 0) {
StringBuilder disciplinesString = new StringBuilder();
for (int i = 0; i < disciplines.size(); i++) {
if (i == 0)
disciplinesString.append(disciplines.get(i));
else
disciplinesString.append(",").append(disciplines.get(i));
}
queryParameters.add(new BasicNameValuePair("disciplines", disciplinesString.toString()));
}
if (statuses.size() > 0) {
StringBuilder statusString = new StringBuilder();
for (int i = 0; i < statuses.size(); i++) {
if (i == 0)
statusString.append(statuses.get(i));
else
statusString.append(",").append(statuses.get(i));
}
queryParameters.add(new BasicNameValuePair("statuses", statusString.toString()));
}
if (scheduledBefore != null) {
queryParameters.add(new BasicNameValuePair("scheduled_before", scheduledBefore.toString()));
}
if (scheduledAfter != null) {
queryParameters.add(new BasicNameValuePair("scheduled_after", scheduledAfter.toString()));
}
if (countries.size() > 0) {
StringBuilder countriesString = new StringBuilder();
for (int i = 0; i < countries.size(); i++) {
if (i == 0)
countriesString.append(countries.get(i));
else
countriesString.append(",").append(countries.get(i));
}
queryParameters.add(new BasicNameValuePair("countries", countriesString.toString()));
}
if (platforms.size() > 0) {
StringBuilder platformsString = new StringBuilder();
for (int i = 0; i < platforms.size(); i++) {
if (i == 0)
platformsString.append(platforms.get(i));
else
platformsString.append(",").append(platforms.get(i));
}
queryParameters.add(new BasicNameValuePair("platforms", platformsString.toString()));
}
if (isOnline != null) {
queryParameters.add(new BasicNameValuePair("is_online", isOnline ? "1" : "0"));
}
if (sort != null) {
if (sort == Sorting.SCHEDULED_ASCENDING)
queryParameters.add(new BasicNameValuePair("sort", "scheduled_asc"));
else if (sort == Sorting.SCHEDULED_DESCENDING)
queryParameters.add(new BasicNameValuePair("sort", "scheduled_desc"));
}
return "?" + URLEncodedUtils.format(queryParameters, "UTF-8");
}
public enum Sorting {
SCHEDULED_ASCENDING, SCHEDULED_DESCENDING
}
}
|
package pl.globallogic.qaa_academy.coreclasses;
public class StringBuildersExamples {
public static void main(String[] args) {
//StringBuffer for multi thread environment object
//StringBuilder One object to work on
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder(100);
StringBuilder sb3 = new StringBuilder("This can be a long long text");
sb3.append(" and we can change the content of this object");
// sb3.insert(0," and we can change the content of this object");
// System.out.println(sb3.toString());
// sb3.setCharAt(2,'t');
// sb3.reverse();
int lastInedxOfObject = sb3.lastIndexOf("object");
sb3.substring(0);
System.out.println(lastInedxOfObject);
System.out.println(sb3);
}
}
|
package org.aksw.autosparql.client;
import com.extjs.gxt.ui.client.event.EventType;
public class AppEvents {
public static final EventType NavHome = new EventType();
public static final EventType NavQuery = new EventType();
public static final EventType NavLoadedQuery = new EventType();
public static final EventType EditQuery = new EventType();
public static final EventType Init = new EventType();
public static final EventType ShowInteractiveMode = new EventType();
public static final EventType Error = new EventType();
public static final EventType AddPosExample = new EventType();
public static final EventType AddNegExample = new EventType();
public static final EventType AddExample = new EventType();
public static final EventType RemoveExample = new EventType();
public static final EventType UpdateResultTable = new EventType();
}
|
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class oos {
public static void main(String[] args) {
FileInputStream fis;//=new FileInputStream("data.txt");
FileOutputStream fos;//=new FileOutputStream("data1.txt");
ObjectInputStream ois ;//=new ObjectInputStream(fis);
ObjectOutputStream oos;//=new ObjectOutputStream(fos);
try {
File f1=new File("data.txt");
f1.createNewFile();
fis=new FileInputStream(f1);
fos=new FileOutputStream("data1.txt");
oos=new ObjectOutputStream(fos);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.test.linklist;
import static org.junit.Assert.assertArrayEquals;
import java.util.Arrays;
import com.test.base.LinkGraph;
import junit.framework.TestCase;
/**
* .链表实现的图
* @author YLine
*
* 2019年3月22日 下午4:23:46
*/
public class LinkSample extends TestCase
{
private LinkSolution solution;
@Override
protected void setUp()
throws Exception
{
super.setUp();
}
// 广度优先,遍历算法
public void testBFS()
{
solution = new SolutionLinkBFS();
LinkGraph graph = LinkGraph.createGraph();
Object[] actualArray = solution.traverse(graph);
assertSolution("BFS", actualArray, "A", "B", "C", "D", "E", "F");
}
// 深度优先,遍历算法
public void testDFS()
{
solution = new SolutionLinkDFS();
LinkGraph graph = LinkGraph.createGraph();
Object[] actualArray = solution.traverse(graph);
assertSolution("DFS", actualArray, "A", "B", "D", "F", "E", "C");
}
private void assertSolution(String tag, Object[] actualArray, Object... expected)
{
System.out.println("--------------------------" + tag + "-----------------------");
System.out.println(Arrays.toString(actualArray));
assertArrayEquals(expected, actualArray);
}
@Override
protected void tearDown()
throws Exception
{
super.tearDown();
}
}
|
package com.example.dictionary.web.controller;
import com.example.dictionary.web.YandexTranslate.Languages;
import com.example.dictionary.web.YandexTranslate.YandexTranslateApi;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/**
* Класс-spring controller для обработки запросов
*/
@Controller
@Api(description = "api list")//описание api для сваггера
public class TranslateController {
private static final Logger logger = LoggerFactory.getLogger(TranslateController.class);
//ключ-пароль(для яндекс api)
@Value("${yakey}")
String key;
/**
* Обработчик /translate валидирует входные параметры, отправляет запрас к апи и возвращает его ответ
* если какой то из параметров пустой - обработчик вернет текст из входныхх данных
* @param text текст для перевода
* @param from язык, с которого необходимо перевести текст, в скоращенном виде из 2 символом (см. описание апи)
* @param to язык, на который необходимо перевести текст, в скоращенном виде из 2 символом (см. описание апи)
* @return http ответ после обработки, http header + http статус, в body переведенный текст/описание ошибки запроса
*/
@ApiOperation(value = "yandex translate")
@RequestMapping(value = "/translate", method = RequestMethod.GET)
public ResponseEntity<String> getYandexTranslaltion(@RequestParam("text") String text, @RequestParam("from") String from, @RequestParam("to") String to) {
logger.info("call YandexTranslaltion : text=" + text + " from=" + from + " to=" + to);
ResponseEntity<String> response = null;
StringBuilder text2 = new StringBuilder();
//если не все необходмиые параметры заполнены - api не вызывается
if (StringUtils.isNotBlank(text) && StringUtils.isNotBlank(to) && StringUtils.isNotBlank(from)) {
//проверка входных данных
from = from.trim();
to = to.trim();
boolean validation = isValid(from, to);
if (validation) {
//требование отправлять запросы к апи только по 1 слову
List<String> words = Arrays.asList(text.trim().split(" "));
YandexTranslateApi api = new YandexTranslateApi();
for (String word : words) {
try {
//ответ от api помещается в объект из "key": "value"
JSONObject obj = new JSONObject(api.translate(key, word, from, to));
//перведенный текст апи помещает с ключем "text"
JSONArray translation = obj.getJSONArray("text");
//перевод складывается в 1 строку через пробел
if (translation != null) {
text2.append(translation.getString(0));
text2.append(" ");
}
}
//при ошибке возвращаем не переведенный текст и логируем причину
catch (IOException e) {
text2 = new StringBuilder(text);
logger.error("getYandexTranslaltiaon problem: " + e);
}
}
} else {
//перевод на не поддерживаемые языки не осуществляется
text2 = new StringBuilder(text);
}
//возвращается успешная обработка запроса
response = new ResponseEntity<>(text2.toString().trim(), HttpStatus.OK);
} else {
//возвращается успешная обработка запроса без переведенного текста
response = new ResponseEntity<>(text, HttpStatus.OK);
}
return response;
}
/**
* Метод для проверки корректности языков для перевода (см. описание api)
* @param from язык, с которого необходимо перевести текст, в скоращенном виде из 2 символом (см. описание апи)
* @param to язык, на который необходимо перевести текст, в скоращенном виде из 2 символом (см. описание апи)
* @return true/false в зависимости от корректности сокращений языка
*/
private boolean isValid(@RequestParam("from") String from, @RequestParam("to") String to) {
boolean validation = false;
boolean checkFrom = false;
boolean checkTo = false;
for (Languages c : Languages.values()) {
if (c.toString().equalsIgnoreCase(from)) {
checkFrom = true;
}
if (c.toString().equalsIgnoreCase(to)) {
checkTo = true;
}
}
if (checkTo && checkFrom){
validation = true;
}
return validation;
}
}
|
package tech.liujin.wuxio.animatedrawable;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import com.threekilogram.wuxio.animatedrawable.R;
import tech.liujin.drawable.widget.ProgressAlphaDrawable;
import tech.liujin.drawable.widget.TabItemBuilder;
/**
* @author wuxio
*/
public class WeChatBottomActivity extends AppCompatActivity {
private static final String TAG = WeChatBottomActivity.class.getSimpleName();
protected ViewPager mPager;
private TabLayout mTabLayout;
private String[] mTitles = { "微信", "通信录", "发现", "我" };
public static void start ( Context context ) {
Intent starter = new Intent( context, WeChatBottomActivity.class );
context.startActivity( starter );
}
@Override
protected void onCreate ( Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
super.setContentView( R.layout.activity_wechat_bottom );
initView();
}
private void initView ( ) {
mPager = findViewById( R.id.pager );
mTabLayout = findViewById( R.id.tabLayout );
PagerAdapter adapter = new PagerAdapter( getSupportFragmentManager() );
mPager.setAdapter( adapter );
// 辅助关联ViewPager和TabLayout
TabItemBuilder builder = new ItemBuilder( mTabLayout, mPager );
builder.setTitles( mTitles );
// 设置textView文字颜色变化
builder.setTextColorRes( R.color.textColorNormal, R.color.textColorSelected );
// 配置每个图标资源
builder.setDrawable( 0, R.drawable.home_normal, R.drawable.home_selected );
builder.setDrawable( 1, R.drawable.category_normal, R.drawable.category_selected );
builder.setDrawable( 2, R.drawable.find_normal, R.drawable.find_selected );
builder.setDrawable( 3, R.drawable.mine_normal, R.drawable.mine_selected );
// 创建
builder.build( 0 );
}
private class PagerAdapter extends FragmentStatePagerAdapter {
private TextFragment[] mFragments = {
TextFragment.newInstance( mTitles[ 0 ] ),
TextFragment.newInstance( mTitles[ 1 ] ),
TextFragment.newInstance( mTitles[ 2 ] ),
TextFragment.newInstance( mTitles[ 3 ] )
};
public PagerAdapter ( FragmentManager fm ) {
super( fm );
}
@Override
public Fragment getItem ( int position ) {
return mFragments[ position ];
}
@Override
public int getCount ( ) {
return mFragments.length;
}
@Nullable
@Override
public CharSequence getPageTitle ( int position ) {
return mTitles[ position ];
}
}
private class ItemBuilder extends TabItemBuilder {
public ItemBuilder ( TabLayout tabLayout, ViewPager viewPager ) {
super( tabLayout, viewPager );
}
@Override
public TabItemBuilder setDrawable (
int position, int normalDrawable, int selectDrawable ) {
return super.setDrawable( position, normalDrawable, selectDrawable );
}
@Override
public TabItemBuilder setDrawable (
int position, ProgressAlphaDrawable drawable ) {
return super.setDrawable( position, drawable );
}
}
}
|
package CookieDemo;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
/**
* Created by dell on 2016-12-25.
* 用cookie 保存用户上次访问时间
*
*/
@WebServlet(name = "ServletCookieDemo1",urlPatterns = "/ServletCookieDemo1")
public class ServletCookieDemo1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("上次访问时间 " );
// 获得用户的时间cookie
Cookie[] cookies = request.getCookies();
for(int i=0;cookies != null && i<cookies.length;i++){
if(cookies[i].getName().equals("lastAccessTime")){
long timevalue = Long.parseLong(cookies[i].getValue());
Date date = new Date(timevalue);
out.print(date.toLocaleString());
}
}
// 给用户最新时间cookie
Cookie coo = new Cookie("lastAccessTime", System.currentTimeMillis()+"");
coo.setMaxAge(7*24*3600); //浏览器保存7天
coo.setPath("/ServletCookieDemo1");
response.addCookie(coo);
}
/**
* Created by dell on 2016-12-23.
* 设置编码,防止出现乱码,
*/
@WebServlet(name = "ServletChineseDemo",urlPatterns = "/ServletChineseDemo")
public static class ServletChineseDemo extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String str = "中国";
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
response.getOutputStream().write(str.getBytes());
}
}
}
|
/*******************************************************************************
* Copyright (c) 2021 Composent Inc., and others.
*
* 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.
*
* Contributors: Composent, Inc. - initial API and implementation
******************************************************************************/
package org.eclipse.ecf.provider.grpc.host;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import org.eclipse.ecf.core.identity.URIID;
import org.eclipse.ecf.provider.grpc.GRPCConstants;
import org.eclipse.ecf.provider.grpc.identity.GRPCNamespace;
import org.eclipse.ecf.remoteservice.AbstractRSAContainer;
import org.eclipse.ecf.remoteservice.RSARemoteServiceContainerAdapter.RSARemoteServiceRegistration;
import io.grpc.BindableService;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.ServerServiceDefinition;
import io.grpc.protobuf.services.ProtoReflectionService;
import io.grpc.util.MutableHandlerRegistry;
public class GRPCHostContainer extends AbstractRSAContainer {
protected final Server server;
protected final long stopTimeout;
protected final Map<RSARemoteServiceRegistration, ServerServiceDefinition> registrationToDefinitionMap;
protected final MutableHandlerRegistry serviceHandlerRegistry;
protected ServerServiceDefinition protoReflectionServiceDef;
public GRPCHostContainer(URI uri, long stopTimeout, boolean serverReflection) {
super(GRPCNamespace.INSTANCE.createInstance(new Object[] { uri }));
ServerBuilder<?> serverBuilder = ServerBuilder.forPort(((URIID) getID()).toURI().getPort());
this.serviceHandlerRegistry = new MutableHandlerRegistry();
serverBuilder.fallbackHandlerRegistry(serviceHandlerRegistry);
this.registrationToDefinitionMap = new ConcurrentHashMap<RSARemoteServiceRegistration, ServerServiceDefinition>();
this.stopTimeout = stopTimeout;
this.server = initialize(serverBuilder);
if (serverReflection) {
this.protoReflectionServiceDef = ProtoReflectionService.newInstance().bindService();
}
}
protected Server initialize(ServerBuilder<?> serverBuilder) {
return serverBuilder.build();
}
public boolean isServerShutdown() {
synchronized (this.server) {
return this.server.isShutdown();
}
}
public boolean isServerTerminated() {
synchronized (this.server) {
return this.server.isTerminated();
}
}
public boolean addProtoReflectionServiceDef() {
synchronized (this.server) {
if (!isServerShutdown()) {
if (this.protoReflectionServiceDef == null) {
this.protoReflectionServiceDef = ProtoReflectionService.newInstance().bindService();
}
this.serviceHandlerRegistry.addService(this.protoReflectionServiceDef);
return true;
}
}
return false;
}
public boolean removeProtoReflectionServiceDef() {
synchronized (this.server) {
if (!isServerShutdown()) {
ServerServiceDefinition serviceDefinition = this.protoReflectionServiceDef;
if (serviceDefinition != null) {
boolean success = this.serviceHandlerRegistry.removeService(serviceDefinition);
if (success) {
this.protoReflectionServiceDef = null;
}
return success;
}
}
}
return false;
}
public boolean isProtoReflectionServiceDef() {
synchronized (this.server) {
return this.protoReflectionServiceDef != null;
}
}
public boolean toggleProtoReflectionServiceDef() {
synchronized (this.server) {
return (!isProtoReflectionServiceDef()) ? addProtoReflectionServiceDef()
: removeProtoReflectionServiceDef();
}
}
public void startGrpcServer() throws IOException {
synchronized (this.server) {
if (!isServerShutdown()) {
this.server.start();
if (this.protoReflectionServiceDef != null) {
this.serviceHandlerRegistry.addService(this.protoReflectionServiceDef);
}
}
}
}
protected void shutdownGrpcServer() {
synchronized (this.server) {
if (!isServerShutdown()) {
server.shutdown();
try {
server.awaitTermination(stopTimeout, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
}
if (!isServerTerminated()) {
server.shutdownNow();
}
}
}
}
protected boolean addMutableService(RSARemoteServiceRegistration registration) {
synchronized (this.server) {
if (!isServerShutdown()) {
Object service = registration.getService();
if (service instanceof BindableService) {
BindableService bs = (BindableService) service;
ServerServiceDefinition serviceDef = bs.bindService();
this.serviceHandlerRegistry.addService(serviceDef);
this.registrationToDefinitionMap.put(registration, serviceDef);
return true;
}
}
}
return false;
}
protected boolean removeMutableService(RSARemoteServiceRegistration registration) {
synchronized (this.server) {
if (!isServerShutdown()) {
ServerServiceDefinition serviceDefinition = this.registrationToDefinitionMap.remove(registration);
if (serviceDefinition != null) {
return this.serviceHandlerRegistry.removeService(serviceDefinition);
}
}
}
return false;
}
private String getGrpcStubClassname(RSARemoteServiceRegistration registration) {
String stubClassNameFromRegistration = (String) registration.getProperty(GRPCConstants.GRPC_STUB_CLASS_PROP);
if (stubClassNameFromRegistration != null) {
return stubClassNameFromRegistration;// If not then get the service super class and use that
}
Object service = registration.getService();
@SuppressWarnings("rawtypes")
Class clazz = service.getClass();
while (!Object.class.equals(clazz.getSuperclass()))
clazz = clazz.getSuperclass();
// This is the Grpc stub factory class class
@SuppressWarnings("rawtypes")
Class enclosingClass = clazz.getEnclosingClass();
return (enclosingClass != null) ? enclosingClass.getName() : clazz.getName();
}
@Override
protected Map<String, Object> exportRemoteService(RSARemoteServiceRegistration registration) {
if (!addMutableService(registration)) {
throw new RuntimeException("Failed to add remote service with registration=" + registration
+ " to grpc server=" + this.server);
}
Map<String, Object> newProps = new HashMap<String, Object>();
// Put the grpc stub classname into the properties
newProps.put(GRPCConstants.GRPC_STUB_CLASS_PROP, getGrpcStubClassname(registration));
return newProps;
}
@Override
protected void unexportRemoteService(RSARemoteServiceRegistration registration) {
removeMutableService(registration);
}
@Override
public void dispose() {
super.dispose();
shutdownGrpcServer();
}
}
|
package org.example.data.service.department;
import org.example.data.model.department.Department;
import org.example.data.repository.department.DepartmentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class DepartmentDataServiceImpl implements DepartmentDataService {
@Autowired
private DepartmentRepository departmentRepository;
@Override
public Department save(Department department) {
return departmentRepository.save(department);
}
@Override
public List<Department> saveAll(List<Department> list) {
return departmentRepository.saveAll(list);
}
@Override
public List<Department> findAll() {
return departmentRepository.findAll();
}
@Override
public Page<Department> findAll(Example<Department> example, Pageable pageable) {
return departmentRepository.findAll(example, pageable);
}
@Override
public Optional<Department> findById(Long id) {
return departmentRepository.findById(id);
}
@Override
public void deleteById(Long id) {
departmentRepository.deleteById(id);
}
}
|
package exercicio01;
public class Aluno extends Pessoa {
public Double bolsa;
public String serie;
public Aluno(String id, String nome, Double bolsa, String serie) {
super(id, nome);
this.bolsa = bolsa;
this.serie = serie;
}
@Override
public String toString() {
return "Aluno: " + "\nid: " + super.id + "\nNome: " + super.nome + "\nBolsa: " + bolsa + "\nSerie: " + serie
+ "\n\n";
}
}
|
package com.asky.backend.entity;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import javax.persistence.*;
import java.io.Serializable;
import java.util.List;
@Table(name="tbl_course")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
@Entity
public class Course implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="course_id")
private int courseId;
@Column(name="course_name")
private String courseName;
@Column(name="description")
private String description;
@Column(name="status")
private boolean status;
@OneToOne(mappedBy="course",cascade = CascadeType.ALL)
@JsonManagedReference
private Lesson lesson;
@OneToMany(mappedBy="course",cascade = CascadeType.ALL)
@JsonBackReference
private List<UserHasCourse> userHasCourseList;
@OneToMany(mappedBy="course" ,cascade = CascadeType.ALL)
@JsonManagedReference
private List<Content> contentList;
public List<Content> getContentList() {
return contentList;
}
public void setContentList(List<Content> contentList) {
this.contentList = contentList;
}
public Lesson getLesson() {
return lesson;
}
public void setLesson(Lesson lesson) {
this.lesson = lesson;
}
public List<UserHasCourse> getUserHasCourseList() {
return userHasCourseList;
}
public void setUserHasCourseList(List<UserHasCourse> userHasCourseList) {
this.userHasCourseList = userHasCourseList;
}
public int getCourseId() {
return courseId;
}
public void setCourseId(int courseId) {
this.courseId = courseId;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
}
|
package vision.model;
import java.util.List;
import vision.model.xml.Hole;
import vision.model.xml.Wall;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
public class WallAdapter {
private final Wall wall;
/**
* Contructs a WallAdapter.
* @param wall
*/
public WallAdapter(Wall wall) {
this.wall = wall;
}
/**
* gets the position.
* @return
*/
public Position getPosition() {
return new Position((wall.getPositionX1() + wall.getPositionX2()) / 2,
(wall.getPositionY1() + wall.getPositionY2()) / 2, 0);
}
/**
* gets the startposition.
* @return
*/
public Position getStart() {
return new Position(wall.getPositionX1(), wall.getPositionY1(), 0);
}
/**
* gets the endposition.
* @return
*/
public Position getEnd() {
return new Position(wall.getPositionX2(), wall.getPositionY2(), 0);
}
/**
* gets the size.
* @return
*/
public Size3D getSize() {
return new Size3D(getWidth(), getHeight(), getDepth());
}
/**
* gets a list of holes.
* @return
*/
public List<Hole> getHoles() {
return wall.getHole();
}
/**
* gets the width
* @return
*/
public float getWidth() {
Vector3f d = new Vector3f(wall.getPositionX2() - wall.getPositionX1(),
wall.getPositionY2() - wall.getPositionY1(), 0);
return d.length();
}
/**
* gets the height.
* @return
*/
public float getHeight() {
return wall.getHeight();
}
/**
* gets the depth.
* @return
*/
public float getDepth() {
return wall.getWide();
}
/**
* gets the rotation.
* @return
*/
public float getRotation() {
final Vector2f wallDir = new Vector2f(getStart().getX()
- getEnd().getX(), getStart().getY()
- getEnd().getY());
return wallDir.angleBetween(new Vector2f(1f, 0f));
}
}
|
package com.example.seanreddy.movieinfo.network;
import com.example.seanreddy.movieinfo.models.MovieDataBase;
import retrofit2.Call;
import retrofit2.http.GET;
/* Retrofit interface to get calls */
public interface MovieDataBaseService {
String SERVICE_ENDPOINT = "https://api.themoviedb.org";
@GET("3/search/movie")
Call<MovieDataBase> getMovieList();
}
|
package com.citibank.ods.modules.product.prodsubfamlprvt.form;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import com.citibank.ods.common.dataset.DataSet;
import com.citibank.ods.common.form.BaseForm;
import com.citibank.ods.common.util.ODSValidator;
import com.citibank.ods.entity.pl.BaseTplProdSubFamlPrvtEntity;
import com.citibank.ods.modules.product.prodsubfamlprvt.functionality.valueobject.BaseProdSubFamlPrvtDetailFncVO;
/**
* @author fernando.salgado
*
*/
public class BaseProdSubFamlPrvtDetailForm extends BaseForm implements
ProdSubFamlPrvtDetailable
{
public static final String C_PROD_SUB_FAML_CODE_DESCRIPTION = "Código da Sub-Família";
public static final String C_PROD_SUB_FAML_NAME_DESCRIPTION = "Nome da Sub-Família";
public static final String C_PROD_SUB_FAML_TEXT_DESCRIPTION = "Desc. da Sub-Família";
public static final String C_PROD_FAML_CODE_DESCRIPTION = "Codigo da Familia";
// Data e hora da ultima atualizaca efetuada pelo usuario.
private String m_lastUpdDate = "";
// Codigo do usuario que efetuou a ultima atualizacao no registro.
private String m_lastUpdUserId = "";
// Codigo da Familia de Produtos
private String m_prodFamlCode = "";
// Codigo da Sub-Familia de Produtos.
private String m_prodSubFamlCode = "";
// Nome da Sub-Familia de Produtos.
private String m_prodSubFamlName = "";
// Descricao da Sub-Familia de Produtos.
private String m_prodSubFamlText = "";
// Domain da Familia de Produtos
private DataSet m_prodFamlCodeDomain = null;
/**
* @return Returns m_lastUpdDate.
*/
public String getLastUpdDate()
{
return m_lastUpdDate;
}
/**
* @param lastUpdDate_ Field m_lastUpdDate to be setted.
*/
public void setLastUpdDate( String lastUpdDate_ )
{
m_lastUpdDate = lastUpdDate_;
}
/**
* @return Returns m_lastUpdUserId.
*/
public String getLastUpdUserId()
{
return m_lastUpdUserId;
}
/**
* @param lastUpdUserId_ Field m_lastUpdUserId to be setted.
*/
public void setLastUpdUserId( String lastUpdUserId_ )
{
m_lastUpdUserId = lastUpdUserId_;
}
/**
* @return Returns m_prodFamlCode.
*/
public String getProdFamlCode()
{
return m_prodFamlCode;
}
/**
* @param prodFamlCode_ Field m_prodFamlCode to be setted.
*/
public void setProdFamlCode( String prodFamlCode_ )
{
m_prodFamlCode = prodFamlCode_;
}
/**
* @return Returns m_prodSubFamlCode.
*/
public String getProdSubFamlCode()
{
return m_prodSubFamlCode;
}
/**
* @param prodSubFamlCode_ Field m_prodSubFamlCode to be setted.
*/
public void setProdSubFamlCode( String prodSubFamlCode_ )
{
m_prodSubFamlCode = prodSubFamlCode_;
}
/**
* @return Returns m_prodSubFamlName.
*/
public String getProdSubFamlName()
{
return m_prodSubFamlName;
}
/**
* @param prodSubFamlName_ Field m_prodSubFamlName to be setted.
*/
public void setProdSubFamlName( String prodSubFamlName_ )
{
m_prodSubFamlName = prodSubFamlName_;
}
/**
* @return Returns m_prodSubFamlText.
*/
public String getProdSubFamlText()
{
return m_prodSubFamlText;
}
/**
* @param prodSubFamlText_ Field m_prodSubFamlText to be setted.
*/
public void setProdSubFamlText( String prodSubFamlText_ )
{
m_prodSubFamlText = prodSubFamlText_;
}
/**
* @return Returns the prodFamlCodeDomain.
*/
public DataSet getProdFamlCodeDomain()
{
return m_prodFamlCodeDomain;
}
/**
* @param prodFamlCodeDomain_ The prodFamlCodeDomain to set.
*/
public void setProdFamlCodeDomain( DataSet prodFamlCodeDomain_ )
{
m_prodFamlCodeDomain = prodFamlCodeDomain_;
}
/* (non-Javadoc)
* @see com.citibank.ods.modules.product.prodsubfamlprvt.form.ProdSubFamlPrvtDetailable#getSelectedProdSubFamlCode()
*/
public String getSelectedProdSubFamlCode()
{
return null;
}
/* (non-Javadoc)
* @see com.citibank.ods.modules.product.prodsubfamlprvt.form.ProdSubFamlPrvtDetailable#setSelectedProdSubFamlCode(java.lang.String)
*/
public void setSelectedProdSubFamlCode( String selectedProdFamlCode_ )
{
this.m_prodSubFamlCode = selectedProdFamlCode_;
}
/*
* Realiza as validações de tipos e tamanhos
*/
public ActionErrors validate( ActionMapping actionMapping_,
HttpServletRequest request_ )
{
ActionErrors errors = new ActionErrors();
ODSValidator.validateBigInteger(
BaseProdSubFamlPrvtDetailFncVO.C_PROD_SUB_FAML_CODE_DESCRIPTION,
m_prodSubFamlCode,
BaseTplProdSubFamlPrvtEntity.C_PROD_SUB_FAML_CODE_SIZE,
errors );
ODSValidator.validateMaxLength(
BaseProdSubFamlPrvtDetailFncVO.C_PROD_SUB_FAML_NAME_DESCRIPTION,
m_prodSubFamlName,
BaseTplProdSubFamlPrvtEntity.C_PROD_SUB_FAML_NAME_SIZE,
errors );
ODSValidator.validateMaxLength(
BaseProdSubFamlPrvtDetailFncVO.C_PROD_SUB_FAML_TEXT_DESCRIPTION,
m_prodSubFamlText,
BaseTplProdSubFamlPrvtEntity.C_PROD_SUB_FAML_TEXT_SIZE,
errors );
ODSValidator.validateBigInteger(
BaseProdSubFamlPrvtDetailFncVO.C_PROD_FAML_CODE_DESCRIPTION,
m_prodFamlCode,
BaseTplProdSubFamlPrvtEntity.C_PROD_FAML_CODE_SIZE,
errors );
return errors;
}
}
|
package com.example.demo.processor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.item.ItemWriter;
import java.util.List;
@Slf4j
public class DemoWriter implements ItemWriter<String> {
@Override
public void write(List<? extends String> items) {
items.forEach(this::write);
}
private void write(String item) {
log.info("Writing item: '{}'", item);
}
}
|
package com.example.vplayer.fragment.event;
public class UpdateAdapterEvent {
}
|
public class Productoscongelados extends Productos{
private String tc;
public Productoscongelados(String fc,String nl,String tc){
this.fc=fc;
this.nl=nl;
this.tc=tc;
}
public void muestracongelados(){
System.out.println("La fecha de caducidad es: "+fc);
System.out.println("El numero del lote es: "+nl);
System.out.println("La temperatura de congelacion recomendada: "+tc);
}
}
|
package net.tecgurus.exception;
import java.util.Date;
import java.util.List;
public class ExceptionRespuesta {
private Date timestamp;
private List<MensajeError> mensajesError;
private String MensajeGeneral;
private String detallesGenerales;
public ExceptionRespuesta() {
super();
}
public ExceptionRespuesta(Date timestamp, List<MensajeError> mensajesError, String mensajeGeneral,
String detallesGenerales) {
super();
this.timestamp = timestamp;
this.mensajesError = mensajesError;
MensajeGeneral = mensajeGeneral;
this.detallesGenerales = detallesGenerales;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public List<MensajeError> getMensajesError() {
return mensajesError;
}
public void setMensajesError(List<MensajeError> mensajesError) {
this.mensajesError = mensajesError;
}
public String getMensajeGeneral() {
return MensajeGeneral;
}
public void setMensajeGeneral(String mensajeGeneral) {
MensajeGeneral = mensajeGeneral;
}
public String getDetallesGenerales() {
return detallesGenerales;
}
public void setDetallesGenerales(String detallesGenerales) {
this.detallesGenerales = detallesGenerales;
}
}
|
import sun.audio.*;
import java.io.*;
public class PoskanzerAudioClip { // implements AudioClip
AudioData data;
InputStream stream;
public PoskanzerAudioClip(byte[] ssamps) {
data = new AudioData( ssamps );
}
private static final int[] expLut = {
0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7
};
private static final int CLIP = 32635;
private static final int BIAS = 0x84;
public static byte toUlaw( int linear ) {
int sign, exponent, mantissa;
byte ulaw;
// Get the sample into sign-magnitude.
if ( linear >= 0 )
sign = 0;
else {
sign = 0x80;
linear = -linear;
}
if ( linear > CLIP )
linear = CLIP; // clip the magnitude
// Convert from 16 bit linear to ulaw.
linear = linear + BIAS;
exponent = expLut[( linear >> 7 ) & 0xFF];
mantissa = ( linear >> ( exponent + 3 ) ) & 0x0F;
ulaw = (byte) ( ~ ( sign | ( exponent << 4 ) | mantissa ) );
return ulaw;
}
public synchronized void play() {
stop();
if ( data != null ) {
stream = new AudioDataStream( data );
AudioPlayer.player.start( stream );
}
}
public synchronized void loop() {
stop();
if ( data != null ) {
stream = new ContinuousAudioDataStream( data );
AudioPlayer.player.start( stream );
}
}
public synchronized void stop() {
if ( stream != null ) {
AudioPlayer.player.stop( stream );
try {
stream.close();
}
catch ( IOException iignore ) {}
stream = null;
}
}
}
|
package StackAndQueue;
import StackAndQueue.dog_and_cat_Queue.Cat;
import StackAndQueue.dog_and_cat_Queue.Dog;
import StackAndQueue.dog_and_cat_Queue.DogAndCatQueue;
import org.junit.Test;
/**
* Created by zjbao on 2018/11/22.
*/
public class DogAndCatQueueTest {
@Test
public void add() throws Exception {
Cat cat =new Cat();
Dog dog =new Dog();
DogAndCatQueue queue = new DogAndCatQueue();
queue.add(cat);
queue.add(dog);
}
@Test
public void pollall() throws Exception {
Cat cat =new Cat();
Dog dog =new Dog();
DogAndCatQueue queue = new DogAndCatQueue();
queue.add(cat);
queue.add(dog);
System.out.println(queue.pollall());
System.out.println(queue.pollall());
}
@Test
public void pollDog() throws Exception {
Cat cat =new Cat();
Dog dog =new Dog();
DogAndCatQueue queue = new DogAndCatQueue();
queue.add(cat);
queue.add(dog);
System.out.println(queue.pollDog());
}
@Test
public void pollCat() throws Exception {
Cat cat =new Cat();
Dog dog =new Dog();
DogAndCatQueue queue = new DogAndCatQueue();
queue.add(cat);
queue.add(dog);
System.out.println(queue.pollCat());
}
@Test
public void isempty() throws Exception {
Cat cat =new Cat();
Dog dog =new Dog();
DogAndCatQueue queue = new DogAndCatQueue();
queue.add(cat);
queue.add(dog);
System.out.println(queue.isempty());
}
@Test
public void isDogempty() throws Exception {
Cat cat =new Cat();
Dog dog =new Dog();
DogAndCatQueue queue = new DogAndCatQueue();
queue.add(cat);
queue.add(dog);
System.out.println(queue.isDogempty());
}
@Test
public void isCatempty() throws Exception {
Cat cat =new Cat();
Dog dog =new Dog();
DogAndCatQueue queue = new DogAndCatQueue();
queue.add(cat);
queue.add(dog);
System.out.println(queue.isCatempty());
}
}
|
import java.io.*;
import java.util.*;
public class Main {
static class Edge {
int src;
int nbr;
int wt;
Edge(int src, int nbr, int wt) {
this.src = src;
this.nbr = nbr;
this.wt = wt;
}
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int vtces = Integer.parseInt(br.readLine());
ArrayList<Edge>[] graph = new ArrayList[vtces];
for (int i = 0; i < vtces; i++) {
graph[i] = new ArrayList<>();
}
int edges = Integer.parseInt(br.readLine());
for (int i = 0; i < edges; i++) {
String[] parts = br.readLine().split(" ");
int v1 = Integer.parseInt(parts[0]);
int v2 = Integer.parseInt(parts[1]);
int wt = Integer.parseInt(parts[2]);
graph[v1].add(new Edge(v1, v2, wt));
graph[v2].add(new Edge(v2, v1, wt));
}
int src = Integer.parseInt(br.readLine());
hamiltonian(graph, src, src, "" , new HashSet<Integer>());
}
public static void hamiltonian(ArrayList<Edge>[] graph, int osrc, int vtx, String psf, HashSet<Integer> visited){
//last vtx will not be marked true .
if(visited.size() == graph.length-1){
//add last vtx in path so far
psf = psf + vtx;
//boolean variable to check if cycle exists
boolean cycle = false;
for(Edge e : graph[vtx]){
if( e.nbr == osrc){
cycle = true;
}
}
if(cycle){ System.out.println(psf + "*"); }
else{ System.out.println(psf + "."); }
}
//mark visited
visited.add(vtx);
for(Edge e: graph[vtx]){
if( !visited.contains(e.nbr) ){
hamiltonian(graph, osrc, e.nbr, psf + vtx, visited);
}
}
// mark unvisited because we need to find all paths
visited.remove(vtx);
}
}
|
package com.fm.scheduling.ui.appointment;
import com.fm.scheduling.domain.Appointment;
import com.fm.scheduling.exception.SchedulingException;
import com.fm.scheduling.service.SchedulingService;
import com.fm.scheduling.ui.util.UtilUI;
import com.fm.scheduling.util.UtilMessages;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javax.rmi.CORBA.Util;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.TextStyle;
import java.util.List;
import java.util.Locale;
public abstract class AppointmentCalendarHelper {
protected LocalDate dateTime;
private final static String STYLE_TITLE = "secundary-title";
private SchedulingService schedulingService;
private UtilUI utilUI;
private UtilMessages utilMessages;
protected List<Appointment> appointmentList;
public AppointmentCalendarHelper(){
this.utilMessages = UtilMessages.getInstance();
this.utilUI = UtilUI.getInstance();
this.schedulingService = SchedulingService.getInstance();
this.dateTime = LocalDate.now();
}
public Label getTitleLabel(){
String labelTxt = dateTime.getMonth().getDisplayName(TextStyle.FULL, SchedulingService.LocalesSupported.getLocaleSupported(Locale.getDefault()).getLocale());
labelTxt = labelTxt + " " + dateTime.getYear();
Label titleLabel = new Label(labelTxt);
titleLabel.getStyleClass().add(STYLE_TITLE);
return titleLabel;
}
public void fillAppointmentList(){
try {
this.appointmentList = schedulingService.getAppointmentList();
} catch (SchedulingException e){
utilUI.openInformationDialog(utilMessages.getMessageBySchedulingException(e));
}
}
public abstract GridPane getCalendarPanel();
public abstract void nextPeriod();
public abstract void previousPeriod();
public ContextMenu getContextMenu(Appointment appointment,final Label label){
final ContextMenu contextMenu = new ContextMenu();
MenuItem edit = new MenuItem("Edit");
MenuItem delete = new MenuItem("Delete");
contextMenu.getItems().addAll(edit, delete);
edit.setOnAction(actionEvent -> {
AppointmentCalendarHelper.this.schedulingService.setAppointmentSelected(appointment);
try {
utilUI.openUI(actionEvent, UtilUI.UIEnum.APPOINTMENTS_EDIT_UI, label.getScene());
} catch (IOException e) {
e.printStackTrace();
}
});
delete.setOnAction(actionEvent ->{
try {
AppointmentCalendarHelper.this.schedulingService.deleteAppointment(appointment);
utilUI.openUI(actionEvent, UtilUI.UIEnum.APPOINTMENTS_TABLE_UI, label.getScene());
} catch (SchedulingException e) {
List<String> messages = utilMessages.getMessageListBySchedulingException(e);
utilUI.openWarningDialog(messages);
} catch (IOException e) {
e.printStackTrace();
}
});
return contextMenu;
}
}
|
package com.bcreagh.data;
public class BinaryNode implements BdbNode {
private String key;
private String value;
private NodeInfo leftNodeInfo;
private NodeInfo rightNodeInfo;
@Override
public String getKey() {
return key;
}
@Override
public String getValue() {
return value;
}
}
|
package com.nevin.coffeeMachine.dunzo.assigment;
import org.springframework.boot.SpringApplication;
public class NevinDunzoCoffeeMachineApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(NevinDunzoCoffeeMachineApplication.class, args);
}
}
|
package org.peterkwan.udacity.mysupermarket.ui;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import org.peterkwan.udacity.mysupermarket.R;
import org.peterkwan.udacity.mysupermarket.data.pojo.ShoppingHistory;
import org.peterkwan.udacity.mysupermarket.util.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import lombok.AllArgsConstructor;
import static org.peterkwan.udacity.mysupermarket.util.AppConstants.STORE_COLLECTION;
@AllArgsConstructor
public class ShoppingHistoryListAdapter extends RecyclerView.Adapter<ShoppingHistoryListAdapter.ShoppingHistoryViewHolder> {
private static final String LOG_TAG = ShoppingHistoryListAdapter.class.getSimpleName();
private Context mContext;
private String languagePreference;
private FirebaseDatabase mFireDatabase;
private final List<ShoppingHistory> shoppingHistoryList = new ArrayList<>();
@NonNull
@Override
public ShoppingHistoryViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
return new ShoppingHistoryViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.shopping_history_item, parent, false));
}
@Override
public void onBindViewHolder(@NonNull final ShoppingHistoryViewHolder holder, int i) {
final ShoppingHistory history = shoppingHistoryList.get(i);
holder.purchaseDateView.setText(DateTimeFormatter.formatDateTime(history.getPurchaseDate()));
holder.totalPriceView.setText(String.format(Locale.getDefault(), "$%.2f", history.getTotalPrice()));
ShoppingHistoryItemListAdapter mListAdapter = new ShoppingHistoryItemListAdapter(mContext, languagePreference, history.getItemList());
holder.itemListView.setAdapter(mListAdapter);
holder.itemListView.setHasFixedSize(true);
holder.itemListView.setVisibility(View.GONE);
holder.moreLessButton.setImageResource(R.drawable.ic_arrow_drop_down_black_24dp);
holder.moreLessButton.setContentDescription(mContext.getString(R.string.show_more));
mFireDatabase.getReference(STORE_COLLECTION)
.orderByChild("name_en")
.equalTo(history.getStore())
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
if (mContext.getResources().getString(R.string.lang_en_value).equals(languagePreference)) {
holder.shopNameView.setText(snapshot.child("name_en").getValue(String.class));
}
else if (mContext.getResources().getString(R.string.lang_zh_value).equals(languagePreference)) {
holder.shopNameView.setText(snapshot.child("name_zh").getValue(String.class));
}
else if (mContext.getResources().getString(R.string.lang_cn_value).equals(languagePreference)) {
holder.shopNameView.setText(snapshot.child("name_cn").getValue(String.class));
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.e(LOG_TAG, "Error", databaseError.toException());
}
});
}
@Override
public int getItemCount() {
return shoppingHistoryList.size();
}
public void setHistoryList(List<ShoppingHistory> historyList) {
this.shoppingHistoryList.clear();
this.shoppingHistoryList.addAll(historyList);
notifyDataSetChanged();
}
class ShoppingHistoryViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.purchase_date_view)
TextView purchaseDateView;
@BindView(R.id.shop_name_view)
TextView shopNameView;
@BindView(R.id.total_price_view)
TextView totalPriceView;
@BindView(R.id.shopping_history_item_detail_list_view)
RecyclerView itemListView;
@BindView(R.id.more_less_button)
ImageView moreLessButton;
ShoppingHistoryViewHolder(View rootView) {
super(rootView);
ButterKnife.bind(this, rootView);
}
@OnClick(R.id.more_less_button)
public void showHideDetails() {
if (itemListView.getVisibility() == View.GONE) {
itemListView.setVisibility(View.VISIBLE);
moreLessButton.setImageResource(R.drawable.ic_arrow_drop_up_black_24dp);
moreLessButton.setContentDescription(mContext.getString(R.string.show_less));
}
else {
itemListView.setVisibility(View.GONE);
moreLessButton.setImageResource(R.drawable.ic_arrow_drop_down_black_24dp);
moreLessButton.setContentDescription(mContext.getString(R.string.show_more));
}
}
}
}
|
package com.corejava.basic;
import com.corejava.basic.Outer.Inner;
public class NestedInnerClassTest {
public static void main(String[] args) {
//invoke Inner class method
Outer.Inner inner=new Outer().new Inner();
inner.show();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package josteo.infrastructure.RepositoryFramework;
import josteo.infrastructure.DomainBase.IEntity;
/**
*
* @author cristiano
*/
public interface IUnitOfWorkRepository {
void PersistNewItem(IEntity item);
void PersistUpdatedItem(IEntity item);
void PersistDeletedItem(IEntity item);
}
|
package edu.upenn.cis350.androidapp.DataInteraction.Management.MessageManagement;
import android.util.Log;
import java.net.URL;
import java.text.ParseException;
import java.util.*;
import java.text.SimpleDateFormat;
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import edu.upenn.cis350.androidapp.AccessWebTask;
import edu.upenn.cis350.androidapp.DataInteraction.Data.Message;
public class MessageJSONReader {
private final String BASE_URL = "http://10.0.2.2:3000/message/";
private MessageJSONReader() { }
private static MessageJSONReader instance = new MessageJSONReader();
public static MessageJSONReader getInstance() { return instance; }
public Map<Long, Message> getAllMessages() {
Map<Long, Message> idToMessages = new HashMap<Long, Message>();
JSONParser parser = new JSONParser();
try {
URL url = new URL(BASE_URL+"/get-all");
AccessWebTask task = new AccessWebTask();
task.execute(url);
JSONObject allMessagesJSON = (JSONObject) parser.parse(task.get());
JSONArray messagesArr = (JSONArray) allMessagesJSON.get("messages");
Iterator iter = messagesArr.iterator();
while(iter.hasNext()) {
JSONObject messageJSON = (JSONObject) iter.next();
Log.d("MessageReader", "messageJSON" + messageJSON.toString());
//extract fields from JSON
long id = (long)messageJSON.get("id");
long senderId = (long)messageJSON.get("senderId");
long receiverId = (long)messageJSON.get("receiverId");
String text = (String) messageJSON.get("text");
long chatId = (long)messageJSON.get("chatId");
Log.d("MessageReader", "Got messageid:" + id +
"senderId: " + senderId + " receiverId: " + receiverId +
" chatId: " + chatId + " text: " + text);
String rawTime = (String) messageJSON.get("time");
Log.d("MessageReader", "rawTime is " + rawTime);
Date time = null;
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSSZ");
try {
time = dateFormat.parse(rawTime.replaceAll("Z$", "+0000"));
} catch (ParseException e) {
Log.d("MessageReader", "time parse error " + e);
}
//create Message object and add to map
Message newMessage = new Message(id, senderId, receiverId, time, text, chatId);
idToMessages.put(id, newMessage);
Log.d("MessageReader", "Added messageid:" + id +
"from time: " + time + " to map");
}
} catch (Exception e) {
Log.d("MessageReader", "json parse error " + e);
}
return idToMessages;
}
}
|
package ee.eerikmagi.testtasks.arvato.invoice_system.rest.json;
import javax.validation.constraints.NotNull;
/**
* Request object for the Add Parking REST API request.
*/
public class AddParkingRequest {
@NotNull
private Long customerID;
@NotNull
private Long parkingHouseID;
@NotNull
private DateObj start;
@NotNull
private DateObj end;
public Long getCustomerID() {
return customerID;
}
public void setCustomerID(Long customerID) {
this.customerID = customerID;
}
public Long getParkingHouseID() {
return parkingHouseID;
}
public void setParkingHouseID(Long parkingHouseID) {
this.parkingHouseID = parkingHouseID;
}
public DateObj getStart() {
return start;
}
public void setStart(DateObj start) {
this.start = start;
}
public DateObj getEnd() {
return end;
}
public void setEnd(DateObj end) {
this.end = end;
}
}
|
/*******************************************************************************
* Copyright (c) 2011 The University of York.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Louis Rose - initial API and implementation
******************************************************************************/
package simulator.execution.model.state;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.verify;
import org.junit.Test;
import org.mockito.Mockito;
import simulator.execution.model.Time;
import simulator.scl.ConfigFactory;
import simulator.scl.Variable;
public class StateTests {
private final Variable variable = createVariable("time");
@Test
public void nextModeNotifiesObservers() throws Exception {
final ModeObserver observer = Mockito.mock(ModeObserver.class);
final State state = new State(2);
state.addModeObserver(observer);
state.nextMode();
verify(observer).modeChanged(state);
}
@Test
public void variableShouldBeSharedBetweenModes() throws Exception {
final State state = new State(2);
final Time value = Time.now();
state.setValueOf(variable, value);
state.nextMode();
assertEquals(value, state.getValueOf(variable));
}
@Test
public void intialiseVariableShouldUseCurrentTime() throws Exception {
final State state = new State();
state.initialiseValueOf(variable);
assertEquals(Time.now(), state.getValueOf(variable));
}
@Test
public void intialiseVariableShouldNotOverwriteExistingValue() throws Exception {
final State state = new State();
final Time yesterday = Time.hoursAgo(24);
state.setValueOf(variable, yesterday);
state.initialiseValueOf(variable);
assertEquals(yesterday, state.getValueOf(variable));
}
private static Variable createVariable(String variableName) {
final Variable variable = ConfigFactory.eINSTANCE.createVariable();
variable.setName(variableName);
return variable;
}
}
|
package br.com.clean.arch.controller.rest;
import br.com.clean.arch.domain.dto.GivenParamDTO;
import br.com.clean.arch.domain.entity.ResultHistoryEntity;
import io.micronaut.http.HttpResponse;
public interface SumController {
HttpResponse<ResultHistoryEntity> calculateSum(
GivenParamDTO firstParam, GivenParamDTO secondParam, GivenParamDTO... otherParam);
}
|
package dfs;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class C40 {
public static void main(String[] args) {
int[] candidates = { 10, 1, 2, 7, 6, 1, 1, 5 };
int target = 8;
Solution_1 solution = new Solution_1();
List<List<Integer>> res = solution.combinationSum2(candidates, target);
System.out.println(res.toString());
}
/**
* 40. ×éºÏ×ܺÍII
*
*
*/
static class Solution_1 {
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> tmp = new ArrayList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
backTracing(candidates, target, 0);
return res;
}
public void backTracing(int[] candidates, int target, int begin) {
if (target < 0) {
return;
}
if (target == 0) {
res.add(new ArrayList<>(tmp));
return;
}
for (int i = begin; i < candidates.length; i++) {
if (i > begin && candidates[i] == candidates[i - 1]) {
continue;
}
tmp.add(candidates[i]);
backTracing(candidates, target - candidates[i], i + 1);
tmp.remove(tmp.size() - 1);
}
}
}
}
|
package com.infoworks.lab.rest.breaker;
import com.infoworks.lab.exceptions.HttpInvocationException;
import com.infoworks.lab.rest.template.Invocation;
import com.it.soul.lab.sql.entity.EntityInterface;
import java.net.HttpURLConnection;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
public abstract class AbstractCircuitBreaker<T extends AutoCloseable> implements CircuitBreaker<T> {
/**
* Let’s face it, all services will fail or falter at some point in time.
* Circuit breakers allow your system to handle these failures gracefully.
* The circuit breaker concept is straightforward.
* It wraps a function with a monitor that tracks failures.
* The circuit breaker has 3 distinct states, Closed, Open, and Half-Open:
*
* Closed – When everything is normal, the circuit breaker remains in the closed state and all calls pass through to the services.
* When the number of failures exceeds a predetermined threshold the breaker trips, and it goes into the Open state.
*
* Open – The circuit breaker returns an error for calls without executing the function.
*
* Half-Open – After a timeout period, the circuit switches to a half-open state to test if the underlying problem still exists.
* If a single call fails in this half-open state, the breaker is once again tripped.
* If it succeeds, the circuit breaker resets back to the normal closed state.
*
*/
private Logger logger = Logger.getLogger(this.getClass().getName());
private Status _status = Status.CLOSED;
private final Integer failureThreshold; //Minimum n times (0...n); After this amount of try circuit trips to OPEN state.
private final Long timeout; //Http request timeout limit.
private final Long retryTimePeriod; //After this time period, the circuit switches to a half-open state to test if the underlying problem still exists.
private Long lastFailureTime = null; //
private Integer failureCount = 0;
protected final ReentrantLock reLock = new ReentrantLock(true);
/**
*
* @param timeout in milli-second
* @param failureThreshold in integer count
* @param retryTimePeriod in milli-second
*/
public AbstractCircuitBreaker(long timeout, Integer failureThreshold, long retryTimePeriod) {
this.failureThreshold = failureThreshold;
this.timeout = timeout;
this.retryTimePeriod = retryTimePeriod;
}
private Invocation _invocation;
private Invocation.Method _method = Invocation.Method.GET;
protected abstract Invocation createInvocation(Invocation invocation, Invocation.Method method, EntityInterface data);
@Override
public T call(Invocation invocation, Invocation.Method method, EntityInterface data) {
if (invocation == null && _invocation == null) return null;
if (invocation != null && invocation.getClass().isAssignableFrom(SimpleWebInvocation.class)){
((SimpleWebInvocation)invocation).setTimeout(timeout.intValue());
}
//FIXME: Need to test: Will Effective when same circuit breaker would call fromm different thread
/*if (_invocation != null && _invocation.equals(invocation)){
invocation = null; //So that, we can use existing invocation repeatedly.
}*/
if (invocation != null) _invocation = invocation;
if (method != null) _method = method;
T response = null;
switch (_status){
case OPEN:
startObserving(_invocation, _method, data);
break;
case HALF_OPEN:
startMonitoring(_invocation, _method, data);
break;
case CLOSED:
response = circuitTrips(_invocation, _method, data);
break;
}
return response;
}
@Override
public Status online(Invocation invocation, Invocation.Method method, EntityInterface data) {
if (invocation == null && _invocation == null) return Status.OPEN;
if (invocation != null && invocation.getClass().isAssignableFrom(SimpleWebInvocation.class)){
((SimpleWebInvocation)invocation).setTimeout(timeout.intValue());
}
/*if (_invocation != null && _invocation.equals(invocation)){
return _status;
}*/
if (invocation != null) _invocation = invocation;
if (method != null) _method = method;
switch (_status){
case OPEN:
startObserving(_invocation, _method, data);
break;
case HALF_OPEN:
startMonitoring(_invocation, _method, data);
break;
case CLOSED:
circuitTrips(_invocation, _method, data);
break;
}
return _status;
}
protected Integer parseCode(T response){
return HttpURLConnection.HTTP_NOT_FOUND;
}
protected final T circuitTrips(Invocation invocation, Invocation.Method method, EntityInterface data) {
//
T response = null;
do{
try{
response = circuitTest(invocation, method, data);
//
if (!isAcceptedResponse(response)){
recordFailure();
}
}catch (HttpInvocationException e) {
logger.log(Level.INFO, e.getMessage());//REMOVE
recordFailure();
}finally {
updateStatus();
invocation = createInvocation(invocation, method, data);
if (_status == Status.OPEN) startObserving(invocation, method, data);
}
if (failureCount > failureThreshold) break;
}while (!isAcceptedResponse(response));
return response;
}
protected abstract boolean isAcceptedResponse(T response);
protected abstract T circuitTest(Invocation invocation, Invocation.Method method, EntityInterface data) throws HttpInvocationException;
protected final void updateStatus(){
reLock.lock();
try {
if (failureCount > failureThreshold){
long nowEpocTime = new Date().getTime();
long timeElapsed = (nowEpocTime - lastFailureTime);
boolean isPassedRetryPeriod = timeElapsed > retryTimePeriod;
if (isPassedRetryPeriod){
_status = Status.HALF_OPEN;
}else{
_status = Status.OPEN;
}
}else {
_status = Status.CLOSED;
}
} finally {
reLock.unlock();
}
logger.log(Level.INFO, "Circuit Breaker is " + _status.name());//REMOVED
}
protected final void reset(){
reLock.lock();
try {
_status = Status.CLOSED;
failureCount = 0;
lastFailureTime = null;
} finally {
reLock.unlock();
}
}
protected final void recordFailure(){
reLock.lock();
try {
failureCount += 1;
lastFailureTime = (new Date()).getTime();
} finally {
reLock.unlock();
}
}
private ExecutorService _executor = Executors.newSingleThreadExecutor();
@Override
public void close() {
reLock.lock();
try {
if (_futureOfObserving != null && _futureOfObserving.isCancelled() == false){
_futureOfObserving.cancel(true);
}
if (_futureOfMonitoring != null && _futureOfMonitoring.isCancelled() == false){
_futureOfMonitoring.cancel(true);
}
if (_executor.isShutdown() == false) {
_executor.shutdownNow();
}
}finally {
reLock.unlock();
}
}
private Future _futureOfObserving = null;
protected final void startObserving(Invocation invocation, Invocation.Method method, EntityInterface data){
if (_futureOfObserving != null && _futureOfObserving.isDone() == false)
return;
_futureOfObserving = _executor.submit(() -> {
logger.log(Level.INFO, "Start...Observing");//REMOVED
while (true){
try {
Thread.sleep(this.retryTimePeriod.intValue());
} catch (InterruptedException e) {}
//
updateStatus();
if (_status == Status.HALF_OPEN) {
startMonitoring(invocation, method, data);
break;
}
}
logger.log(Level.INFO, "End...Observing");//REMOVED
});
}
private Future _futureOfMonitoring = null;
protected final void startMonitoring(Invocation invocation, Invocation.Method method, EntityInterface data) {
if (_futureOfMonitoring != null && _futureOfMonitoring.isDone() == false)
return;
_futureOfMonitoring = _executor.submit(() -> {
logger.log(Level.INFO, "Start...Monitoring");//REMOVED
try{
T response = circuitTest(invocation, method, data);
//
if (isAcceptedResponse(response)){
reset();
}else {
recordFailure();
}
}catch (HttpInvocationException e) {
logger.log(Level.INFO, e.getMessage());
recordFailure();
}finally {
updateStatus();
Invocation newInvo = createInvocation(invocation, method, data);
if (_status == Status.OPEN) startObserving(newInvo, method, data);
}
logger.log(Level.INFO, "End...Monitoring");//REMOVED
});
}
public Date getLastFailureTime(){
if (lastFailureTime == null) return null;
return new Date(lastFailureTime);
}
}
|
package DAO;
import model.Card;
import java.util.List;
public interface CardDao {
public boolean addCard(Card card);
public boolean deleteCard(Card card);
public boolean updateCard(Card card);
public List<Card> getAllCard();
public Card getCardById(Long id);
}
|
package com.sample_mod.sample_package;
import java.util.HashMap;
import com.zhekasmirnov.horizon.runtime.logger.Logger;
public class Boot {
public static void boot(HashMap<String, String> sources) {
Logger.debug("TEST_MOD", "Hello from Java");
}
}
|
package Entyties.Responses;
import Entyties.Entity;
import Entyties.Project.Project;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
public class OpenProjectResponse extends Entity {
@JsonProperty("Project")
private Project project;
public OpenProjectResponse() {
}
public OpenProjectResponse(Project project) {
this.project = project;
System.out.println("HEllo");
}
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
@Override
public String toString() {
return "OpenProjectResponse{" +
"project=" + project +
'}';
}
}
|
package com.cheese.radio.ui.home.page;
import com.cheese.radio.base.cycle.BaseFragment;
/**
* Created by 29283 on 2018/3/3.
*/
public class HomePageFragment extends BaseFragment<HomePageModel> {
}
|
package view;
import app.DSManager;
import app.Node;
import app.UDPDSManager;
import app.WebServiceDSManager;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.util.*;
/**
* Created by udith on 3/4/15.
*/
public class FSViewController implements Initializable {
@FXML
AnchorPane mainPane;
@FXML
AnchorPane searchPane;
@FXML
AnchorPane filePane;
@FXML
AnchorPane routingPane;
@FXML
Button connectBtn, executeBtn, printBtn;
@FXML
TextField serverIPTF;
@FXML
TextField serverPortTF;
@FXML
ComboBox<String> nodeIPCB;
@FXML
TextField nodePortTF;
@FXML
TextField searchTF;
@FXML
Button searchBtn;
@FXML
VBox fileList;
@FXML
Button logBtn;
@FXML
ToggleGroup comRBGroup;
@FXML
TableView<Node> routingTable;
@FXML
TableColumn<Node, String> nameColumn;
@FXML
TableColumn<Node, String> ipColumn;
@FXML
TableColumn<Node, String> portColumn;
private PopupCreator popupCreator;
private boolean connected;
private Stage logStage;
private LogWindowController logCtrl;
private ObservableList<Node> neighbours;
private DSManager dsManager;
private String lastQuery = "";
private int queryCounter = 0;
private boolean executing = false;
private String csvString = "";
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
popupCreator = new PopupCreator();
neighbours = FXCollections.observableArrayList();
try {
Enumeration e1 = NetworkInterface.getNetworkInterfaces();
ObservableList<String> ips = FXCollections.observableArrayList();
while (e1.hasMoreElements()) {
NetworkInterface n = (NetworkInterface) e1.nextElement();
Enumeration e2 = n.getInetAddresses();
while (e2.hasMoreElements()) {
InetAddress iNetAdd = (InetAddress) e2.nextElement();
if (iNetAdd instanceof Inet4Address) {
ips.add(iNetAdd.getHostAddress());
}
}
}
nodeIPCB.setItems(ips);
} catch (SocketException e) {
e.printStackTrace();
}
nodeIPCB.valueProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
//serverIPTF.setText(newValue);
}
});
serverIPTF.setText("10.8.98.13");
nodeIPCB.getSelectionModel().selectFirst();
serverPortTF.setText("5001");
nodePortTF.setText("5100");
connected = false;
searchPane.setDisable(true);
filePane.setDisable(true);
routingPane.setDisable(true);
nameColumn.setCellValueFactory(cellData -> cellData.getValue().userNameProperty());
ipColumn.setCellValueFactory(cellData -> cellData.getValue().ipProperty());
portColumn.setCellValueFactory(cellData -> cellData.getValue().portProperty());
routingTable.setItems(neighbours);
initLogWindow();
setHandlers();
}
public void addNeighbour(Node node) {
this.neighbours.add(node);
}
public void removeNeighbour(Node node) {
this.neighbours.remove(node);
}
private void initLogWindow() {
AnchorPane logWindow = null;
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(FSViewController.class.getResource("LogWindow.fxml"));
logWindow = fxmlLoader.load();
logCtrl = fxmlLoader.getController();
} catch (IOException e) {
e.printStackTrace();
}
logStage = new Stage(StageStyle.UTILITY);
Scene logScene = new Scene(logWindow);
logStage.setTitle("Log Window");
logStage.setScene(logScene);
}
private void setHandlers() {
executeBtn.setOnAction((event) -> {
queryCounter = 0;
executing = true;
csvString = "query,time to first,time to total,hops\n";
Platform.runLater(new Runnable() {
@Override
public void run() {
executeSearchQueries();
}
});
});
mainPane.setOnKeyPressed((event)->{
if(event.isControlDown() && event.isAltDown() && (event.getCode()==KeyCode.E)){
queryCounter = 0;
executing = true;
csvString = "query,time to first,time to total,hops\n";
Platform.runLater(new Runnable() {
@Override
public void run() {
executeSearchQueries();
}
});
}
});
printBtn.setOnAction((event) -> {
dsManager.printQueryValues();
});
connectBtn.setOnAction((event) -> {
connectBtn.setDisable(true);
if (!connected) {
connectBtn.setText("Connecting...");
boolean conStatus = connectToNetwork();
if (conStatus) {
serverIPTF.setDisable(true);
serverPortTF.setDisable(true);
nodeIPCB.setDisable(true);
nodePortTF.setDisable(true);
populateFileList(dsManager.getNodeFileList());
searchPane.setDisable(false);
filePane.setDisable(false);
routingPane.setDisable(false);
connectBtn.getStyleClass().remove(connectBtn.getStyleClass().size() - 1);
connectBtn.getStyleClass().add("red-button");
connectBtn.setText("Disconnect");
} else {
connectBtn.setText("Connect");
}
} else {
connectBtn.setText("Disconnecting...");
boolean conStatus = disconnectFromNetwork();
if (conStatus) {
serverIPTF.setDisable(false);
serverPortTF.setDisable(false);
nodeIPCB.setDisable(false);
nodePortTF.setDisable(false);
searchPane.setDisable(true);
filePane.setDisable(true);
routingPane.setDisable(true);
searchTF.clear();
fileList.getChildren().clear();
neighbours.clear();
connectBtn.getStyleClass().remove(connectBtn.getStyleClass().size() - 1);
connectBtn.getStyleClass().add("green-button");
connectBtn.setText("Connect");
} else {
connectBtn.setText("Disconnect");
}
}
connectBtn.setDisable(false);
});
searchBtn.setOnAction((event) -> {
searchBtn.setText("Searching...");
searchBtn.setDisable(true);
searchTF.setDisable(true);
String fileName = searchTF.getText();
lastQuery = fileName;
showSearchResults(new HashMap<String, String[]>(),1);
dsManager.getQueryResults(fileName);
});
searchTF.setOnKeyPressed((event)->{
if(event.getCode()== KeyCode.ENTER){
searchBtn.setText("Searching...");
searchBtn.setDisable(true);
searchTF.setDisable(true);
String fileName = searchTF.getText();
lastQuery = fileName;
showSearchResults(new HashMap<String, String[]>(),1);
dsManager.getQueryResults(fileName);
}
});
logBtn.setOnAction((event) -> {
logStage.show();
});
}
public void appendCsvStr(String str){
csvString = csvString.concat(str);
}
public void writeToCsvFile(String fileName) {
PrintWriter writer = null;
try {
writer = new PrintWriter(fileName+".csv", "UTF-8");
writer.println(csvString);
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private void executeSearchQueries() {
String[] queries = new String[]{"Twilight", "Jack", "American Idol", "Happy Feet", "Twilight saga", "Happy Feet", "Happy Feet", "Feet", "Happy Feet", "Twilight", "Windows", "Happy Feet", "Mission Impossible", "Twilight", "Windows 8", "The", "Happy", "Windows 8", "Happy Feet", "Super Mario", "Jack and Jill", "Happy Feet", "Impossible", "Happy Feet", "Turn Up The Music", "Adventures of Tintin", "Twilight saga", "Happy Feet", "Super Mario", "American Pickers", "Microsoft Office 2010", "Twilight", "Modern Family", "Jack and Jill", "Jill", "Glee", "The Vampire Diarie", "King Arthur", "Jack and Jill", "King Arthur", "Windows XP", "Harry Potter", "Feet", "Kung Fu Panda", "Lady Gaga", "Gaga", "Happy Feet", "Twilight", "Hacking", "King"};
int qLimit = queries.length;
if (qLimit == queryCounter) {
executing = false;
}
if (qLimit > queryCounter) {
System.out.println("Sent - (" + (queryCounter + 1) + "/" + qLimit + ") " + queries[queryCounter]);
lastQuery = queries[queryCounter++];
dsManager.getQueryResults(lastQuery);
}
}
private boolean connectToNetwork() {
try {
String serverIP = serverIPTF.getText();
int serverPort = Integer.parseInt(serverPortTF.getText());
String nodeIP = nodeIPCB.getValue();
int nodePort = Integer.parseInt(nodePortTF.getText());
RadioButton selectedRB = (RadioButton) comRBGroup.getSelectedToggle();
if (selectedRB.getId().equals("udpRB")) {
//if udp
dsManager = new UDPDSManager(serverIP, serverPort, nodeIP, nodePort, this);
} else {
//if web service
dsManager = new WebServiceDSManager(serverIP, serverPort, nodeIP, nodePort, this);
}
String status = dsManager.start();
if (status.equals("Successful")) {
connected = true;
return true;
} else {
popupCreator.showErrorDialog("Connection Failed", status);
}
} catch (NumberFormatException e) {
popupCreator.showErrorDialog("Input Error", "Some port numbers are invalid");
}
return false;
}
public boolean disconnectFromNetwork() {
if (connected) {
dsManager.sendLeaveMessages();
connected = false;
}
return true;
}
public void populateFileList(ArrayList<String> fileNames) {
for (String f : fileNames) {
Label l = new Label(f);
l.setTooltip(new Tooltip(f));
fileList.getChildren().add(l);
}
}
public void writeToLog(String str) {
this.logCtrl.appendLog(str); }
/*
status = 1 -> initial result
status = 2 -> any other result
status = 3 -> end of search
*/
public void showSearchResults(HashMap<String, String[]> results, int status) {
if (!executing) {
popupCreator.showSearchResults(lastQuery, results, status);
}
if (status == 3) {
searchBtn.setText("Search File");
searchTF.setDisable(false);
searchBtn.setDisable(false);
if (executing) {
executeSearchQueries();
}
}
// if(results.isEmpty()){
// popupCreator.showInfoDialog("No files found", "No files matching \'"+lastQuery+"\' found!");
// }
// else {
// popupCreator.showSearchResults(lastQuery, results);
// }
}
public void writeToFile(String nodeName) {
logCtrl.writeToFile(nodeName);
}
}
class SearchResult {
private StringProperty ip;
private StringProperty fileName;
public SearchResult(String ip, String fileName) {
this.ip = new SimpleStringProperty(ip);
this.fileName = new SimpleStringProperty(fileName);
}
public String getIp() {
return ip.get();
}
public StringProperty ipProperty() {
return ip;
}
public String getFileName() {
return fileName.get();
}
public StringProperty fileNameProperty() {
return fileName;
}
}
|
package com.dirmod.cotizacionrestapi.service.impl;
import com.dirmod.cotizacionrestapi.domain.Cotizador;
import com.dirmod.cotizacionrestapi.service.CotizadorService;
import org.springframework.stereotype.Service;
@Service
public class CotizadorServiceImpl implements CotizadorService
{
@Override
public Cotizador getCotizacion( Double price )
{
return null;
}
}
|
package com.hardcoded.plugin.json;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class JsonParser {
public static JsonObject parseFromFile(File file) throws IOException {
FileInputStream stream = new FileInputStream(file);
byte[] bytes = stream.readAllBytes();
stream.close();
return parse(bytes);
}
public static JsonObject parse(byte[] bytes) {
return parse(new String(bytes));
}
public static JsonObject parse(String content) {
Object object = parse(content.toCharArray(), new int[] { 0 });
return (JsonObject)object;
}
private static Object parse(char[] ch, int[] idx) {
if(!hasNext(ch, idx)) return null;
eat_spaces(ch, idx);
switch(ch[idx[0]]) {
case '{': return parseMap(ch, idx);
case '[': return parseArray(ch, idx);
case '"': return parseString(ch, idx);
case 'n': {
idx[0] += 4;
eat_spaces(ch, idx);
return null;
}
case 't': {
idx[0] += 4;
eat_spaces(ch, idx);
return Boolean.TRUE;
}
case 'f': {
idx[0] += 5;
eat_spaces(ch, idx);
return Boolean.FALSE;
}
default: return parseLong(ch, idx);
}
}
private static JsonMap parseMap(char[] ch, int[] idx) {
JsonMap map = new JsonMap();
idx[0]++;
eat_spaces(ch, idx);
if(!hasNext(ch, idx)) return null;
if(ch[idx[0]] == '}') {
idx[0]++;
eat_spaces(ch, idx);
return map;
}
while(hasNext(ch, idx)) {
eat_spaces(ch, idx);
String key = parseString(ch, idx);
if(!hasNext(ch, idx)) break;
if(ch[idx[0]] != ':') break;
idx[0]++;
eat_spaces(ch, idx);
Object object = parse(ch, idx);
map.put(key, object);
if(!hasNext(ch, idx)) break;
char c = ch[idx[0]];
if(c == '}') {
idx[0]++;
break;
}
if(c == ',') {
idx[0]++;
eat_spaces(ch, idx);
continue;
}
}
eat_spaces(ch, idx);
return map;
}
private static JsonArray parseArray(char[] ch, int[] idx) {
JsonArray array = new JsonArray();
idx[0]++;
eat_spaces(ch, idx);
if(!hasNext(ch, idx)) return null;
if(ch[idx[0]] == ']') {
idx[0]++;
eat_spaces(ch, idx);
return array;
}
eat_spaces(ch, idx);
while(hasNext(ch, idx)) {
Object obj = parse(ch, idx);
array.add(obj);
// Bad should throw exception
if(!hasNext(ch, idx)) break;
char c = ch[idx[0]];
if(c == ']') {
idx[0]++;
break;
}
if(c == ',') {
idx[0]++;
eat_spaces(ch, idx);
continue;
}
}
eat_spaces(ch, idx);
return array;
}
private static String parseString(char[] ch, int[] idx) {
idx[0]++;
StringBuilder sb = new StringBuilder();
while(hasNext(ch, idx)) {
char c = ch[idx[0]++];
if(c == '"') break;
sb.append(c);
}
eat_spaces(ch, idx);
return sb.toString();
}
private static Long parseLong(char[] ch, int[] idx) {
StringBuilder sb = new StringBuilder();
if(hasNext(ch, idx)) {
if(ch[idx[0]] == '-') {
sb.append("-");
idx[0]++;
}
}
while(hasNext(ch, idx)) {
char c = ch[idx[0]];
if(!Character.isDigit(c)) break;
idx[0]++;
sb.append(c);
}
eat_spaces(ch, idx);
try {
return Long.parseLong(sb.toString());
} catch(NumberFormatException e) {
return null;
}
}
private static boolean hasNext(char[] ch, int[] idx) {
if(idx[0] >= ch.length) return false;
return true;
}
private static void eat_spaces(char[] ch, int[] idx) {
while(hasNext(ch, idx)) {
if(Character.isWhitespace(ch[idx[0]])) {
idx[0]++;
} else break;
}
}
}
|
package com.cinema.biz.model.base;
import java.util.Date;
import javax.persistence.Id;
import javax.persistence.Table;
@Table(name="sim_dependency")
public class TSimDependency {
@Id
private String dependencyId;
private String name;
private Integer runOrder;
private Date createTime;
private String creator;
private Date updateTime;
private String updator;
public String getDependencyId() {
return dependencyId;
}
public void setDependencyId(String dependencyId) {
this.dependencyId = dependencyId == null ? null : dependencyId.trim();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public Integer getRunOrder() {
return runOrder;
}
public void setRunOrder(Integer runOrder) {
this.runOrder = runOrder;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator == null ? null : creator.trim();
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getUpdator() {
return updator;
}
public void setUpdator(String updator) {
this.updator = updator == null ? null : updator.trim();
}
}
|
/*
* Copyright 2018-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 dev.miku.r2dbc.mysql.message.server;
import dev.miku.r2dbc.mysql.collation.CharCollation;
import dev.miku.r2dbc.mysql.constant.ColumnDefinitions;
import dev.miku.r2dbc.mysql.constant.DataTypes;
import dev.miku.r2dbc.mysql.util.CodecUtils;
import io.netty.buffer.ByteBuf;
import java.nio.charset.Charset;
import java.util.Objects;
import static dev.miku.r2dbc.mysql.util.AssertUtils.require;
import static dev.miku.r2dbc.mysql.util.AssertUtils.requireNonNull;
/**
* Column or parameter definition metadata message.
*/
public final class DefinitionMetadataMessage implements ServerMessage {
private static final int MIN_SIZE = 20;
private final String database;
private final String tableName;
private final String originTableName;
private final String name;
private final String originName;
private final int collationId;
private final long size;
private final short type;
private final short definitions;
private final short decimals;
private DefinitionMetadataMessage(
String database, String tableName, String originTableName, String name, String originName,
int collationId, long size, short type, short definitions, short decimals
) {
require(size >= 0, "size must not be a negative integer");
require(collationId > 0, "collationId must be a positive integer");
this.database = requireNonNull(database, "database must not be null");
this.tableName = requireNonNull(tableName, "tableName must not be null");
this.originTableName = requireNonNull(originTableName, "originTableName must not be null");
this.name = requireNonNull(name, "name must not be null");
this.originName = requireNonNull(originName, "originName must not be null");
this.collationId = collationId;
this.size = size;
this.type = type;
this.definitions = definitions;
this.decimals = decimals;
}
public String getDatabase() {
return database;
}
public String getName() {
return name;
}
public int getCollationId() {
return collationId;
}
public long getSize() {
return size;
}
public short getType() {
return type;
}
public short getDefinitions() {
return definitions;
}
public short getDecimals() {
return decimals;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof DefinitionMetadataMessage)) {
return false;
}
DefinitionMetadataMessage that = (DefinitionMetadataMessage) o;
return collationId == that.collationId &&
size == that.size &&
type == that.type &&
definitions == that.definitions &&
decimals == that.decimals &&
database.equals(that.database) &&
tableName.equals(that.tableName) &&
originTableName.equals(that.originTableName) &&
name.equals(that.name) &&
originName.equals(that.originName);
}
@Override
public int hashCode() {
return Objects.hash(database, tableName, originTableName, name, originName, collationId, size, type, definitions, decimals);
}
@Override
public String toString() {
return String.format("DefinitionMetadataMessage{database='%s', tableName='%s' (origin:'%s'), name='%s' (origin:'%s'), collationId=%d, size=%d, type=%d, definitions=%x, decimals=%d}",
database, tableName, originTableName, name, originName, collationId, size, type, definitions, decimals);
}
static boolean isLooksLike(ByteBuf buf) {
int bufSize = buf.readableBytes();
if (bufSize < MIN_SIZE) {
return false;
}
int readerIndex = buf.readerIndex();
byte first = buf.getByte(readerIndex);
if (first != 3) {
return false;
}
// "def".equals(buf.toString(readerIndex + 1, 3, StandardCharsets.US_ASCII))
return 'd' == buf.getByte(readerIndex + 1) &&
'e' == buf.getByte(readerIndex + 2) &&
'f' == buf.getByte(readerIndex + 3);
}
static DefinitionMetadataMessage decode(ByteBuf buf, Charset charset) {
buf.skipBytes(4); // "def" which sized by var integer
String database = CodecUtils.readVarIntSizedString(buf, charset);
String tableName = CodecUtils.readVarIntSizedString(buf, charset);
String originTableName = CodecUtils.readVarIntSizedString(buf, charset);
String name = CodecUtils.readVarIntSizedString(buf, charset);
String originName = CodecUtils.readVarIntSizedString(buf, charset);
CodecUtils.readVarInt(buf); // skip constant 0x0c encoded by var integer
int collationId = buf.readUnsignedShortLE();
long size = buf.readUnsignedIntLE();
short type = buf.readUnsignedByte();
short definitions = buf.readShortLE();
if (DataTypes.JSON == type && collationId == CharCollation.BINARY_ID) {
collationId = CharCollation.clientCharCollation().getId();
}
if ((definitions & ColumnDefinitions.SET) != 0) {
// Maybe need to check if it is a string-like type?
type = DataTypes.SET;
} else if ((definitions & ColumnDefinitions.ENUMERABLE) != 0) {
// Maybe need to check if it is a string-like type?
type = DataTypes.ENUMERABLE;
}
return new DefinitionMetadataMessage(
database,
tableName,
originTableName,
name,
originName,
collationId,
size,
type,
definitions,
buf.readUnsignedByte()
);
}
}
|
package com.example.htw.currencyconverter.network.ConnectivityCheckerUtil;
import com.example.htw.currencyconverter.callback.OnlineChecker;
import java.io.IOException;
public class ExperimentalOnlineChecker implements OnlineChecker {
private final Runtime runtime;
public ExperimentalOnlineChecker(Runtime runtime) {
this.runtime = runtime;
}
@Override
public boolean isOnline() {
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
}
catch (IOException e) { e.printStackTrace(); }
catch (InterruptedException e) { e.printStackTrace(); }
return false;
}
}
|
package sr.hakrinbank.intranet.api.service.bean;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import sr.hakrinbank.intranet.api.model.ListedPersonGrey;
import sr.hakrinbank.intranet.api.repository.ListedPersonGreyRepository;
import sr.hakrinbank.intranet.api.service.ListedPersonGreyService;
import sr.hakrinbank.intranet.api.util.Constant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class ListedPersonGreyServiceBean implements ListedPersonGreyService {
@Autowired
private ListedPersonGreyRepository listedPersonGreyRepository;
@Override
@PostFilter("filterObject.deleted() == false")
public List<ListedPersonGrey> findAllListedPersonGrey() {
return listedPersonGreyRepository.findAll();
}
@Override
public ListedPersonGrey findById(long id) {
return listedPersonGreyRepository.findOne(id);
}
@Override
public void updateListedPersonGrey(ListedPersonGrey ListedPersonGrey) {
if(ListedPersonGrey.getDate() == null){
ListedPersonGrey.setDate(new Date());
listedPersonGreyRepository.save(ListedPersonGrey);
}else{
listedPersonGreyRepository.save(ListedPersonGrey);
}
}
@Override
public List<ListedPersonGrey> findAllActiveListedPersonGreyOrderedByDate() {
return listedPersonGreyRepository.findActiveListedPersonGreyOrderedByDate();
}
@Override
public List<ListedPersonGrey> findAllActiveListedPersonGreyByDate(String byDate) {
if(byDate != null && !byDate.isEmpty() && byDate != "" && !byDate.contentEquals(Constant.UNDEFINED_VALUE) && !byDate.contentEquals(Constant.NULL_VALUE) && !byDate.contentEquals(Constant.INVALID_DATE)){
LocalDate localDate = LocalDate.parse(byDate, DateTimeFormatter.ofPattern(Constant.DATE_FIELD_FORMAT));
LocalDateTime todayStartOfDay = localDate.atStartOfDay();
Date startOfDay = Date.from(todayStartOfDay.atZone(ZoneId.systemDefault()).toInstant());
LocalDateTime todayEndOfDay = localDate.atTime(LocalTime.MAX);
Date endOfDay = Date.from(todayEndOfDay.atZone(ZoneId.systemDefault()).toInstant());
return listedPersonGreyRepository.findAllActiveListedPersonGreyByDate(startOfDay, endOfDay);
}
return findAllActiveListedPersonGreyOrderedByDate();
}
@Override
public List<ListedPersonGrey> findAllActiveListedPersonGreyBySearchQueryOrDate(String byTitle, String byDate) {
if(byDate != null && !byDate.isEmpty() && byDate != "" && !byDate.contentEquals(Constant.UNDEFINED_VALUE) && !byDate.contentEquals(Constant.INVALID_DATE)){
LocalDate localDate = LocalDate.parse(byDate, DateTimeFormatter.ofPattern(Constant.DATE_FIELD_FORMAT));
LocalDateTime todayStartOfDay = localDate.atStartOfDay();
Date startOfDay = Date.from(todayStartOfDay.atZone(ZoneId.systemDefault()).toInstant());
LocalDateTime todayEndOfDay = localDate.atTime(LocalTime.MAX);
Date endOfDay = Date.from(todayEndOfDay.atZone(ZoneId.systemDefault()).toInstant());
if(byTitle != null && byTitle != "" && !byTitle.contentEquals(Constant.UNDEFINED_VALUE)){
return listedPersonGreyRepository.findAllActiveListedPersonGreyBySearchQueryAndDate(byTitle, startOfDay, endOfDay);
}else{
return listedPersonGreyRepository.findAllActiveListedPersonGreyByDate(startOfDay, endOfDay);
}
}else {
return listedPersonGreyRepository.findAllActiveListedPersonGreyBySearchQuery(byTitle);
}
}
@Override
public int countListedPersonGreyOfTheWeek() {
List<ListedPersonGrey> ListedPersonGreyList = listedPersonGreyRepository.findActiveListedPersonGrey();
DateTime currentDate = new DateTime();
int weekOfCurrentDate = currentDate.getWeekOfWeekyear();
int yearOfCurrentDate = currentDate.getYear();
List<ListedPersonGrey> countList = new ArrayList<>();
DateTime specificDate;
int weekOfSpecificDate;
int yearOfSpecificDate;
for(ListedPersonGrey ListedPersonGrey: ListedPersonGreyList){
specificDate = new DateTime(ListedPersonGrey.getDate());
weekOfSpecificDate = specificDate.getWeekOfWeekyear();
yearOfSpecificDate = specificDate.getYear();
if( (yearOfCurrentDate == yearOfSpecificDate) && (weekOfCurrentDate == weekOfSpecificDate) ){
countList.add(ListedPersonGrey);
}
}
return countList.size();
}
@Override
public List<ListedPersonGrey> findAllActiveListedPersonGrey() {
return listedPersonGreyRepository.findActiveListedPersonGrey();
}
@Override
public ListedPersonGrey findByName(String name) {
return listedPersonGreyRepository.findByName(name);
}
@Override
public List<ListedPersonGrey> findAllActiveListedPersonGreyBySearchQuery(String qry) {
return listedPersonGreyRepository.findAllActiveListedPersonGreyBySearchQuery(qry);
}
}
|
package org.vpontus.vuejs.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
/**
* @author vpontus
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Entity
@Table(name = "task_status")
public class TaskStatus implements Serializable {
private static final long serialVersionUID = 6123416937953611776L;
@NotNull
@Size(max = 30)
@Id
@Column(name = "code",length = 30)
private String code;
@Column(name = "name",length = 50)
private String name;
}
|
// import java.io.*;
// import java.util.*;
// class Pair {
// int i;
// int j;
// int val;
// Pair(int i, int j, int val) {
// this.i = i;
// this.j = j;
// this.val = val;
// }
// }
// class baek__2470 {
// public static void main(String[] args) throws IOException {
// BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// int n = Integer.parseInt(br.readLine());
// int[] arr = new int[n];
// String[] temp = br.readLine().split(" ");
// for (int i = 0; i < n; i++) {
// arr[i] = Integer.parseInt(temp[i]);
// }
// Arrays.sort(arr);
// int p1 = 0;
// int p2 = arr.length - 1;
// Pair pair = new Pair(-1, -1, -1);
// int sum = arr[p1] + arr[p2];
// pair.i = p1;
// pair.j = p2;
// pair.val = sum;
// while (p1 < p2) {
// if (Math.abs(sum) < Math.abs(pair.val)) {
// pair.i = p1;
// pair.j = p2;
// pair.val = sum;
// }
// if (sum > 0) {
// sum -= arr[p2];
// p2--;
// sum += arr[p2];
// } else if (sum == 0) {
// break;
// } else {
// sum -= arr[p1];
// p1++;
// sum += arr[p1];
// }
// }
// System.out.print(arr[pair.i] + " " + arr[pair.j]);
// }
// }
|
package com.hello.suripu.service.resources;
import com.google.common.base.Optional;
import com.google.protobuf.InvalidProtocolBufferException;
import com.hello.suripu.api.ble.SenseCommandProtos;
import com.hello.suripu.core.configuration.QueueName;
import com.hello.suripu.core.db.KeyStoreDynamoDB;
import com.hello.suripu.core.oauth.ClientCredentials;
import com.hello.suripu.core.oauth.ClientDetails;
import com.hello.suripu.core.oauth.MissingRequiredScopeException;
import com.hello.suripu.core.oauth.OAuthScope;
import com.hello.suripu.core.oauth.stores.OAuthTokenStore;
import com.hello.suripu.core.swap.Swapper;
import com.hello.suripu.core.util.HelloHttpHeader;
import com.hello.suripu.core.util.PairAction;
import com.hello.suripu.coredropwizard.oauth.AccessToken;
import com.hello.suripu.service.SignedMessage;
import com.hello.suripu.service.pairing.NoOpRegistrationLogger;
import com.hello.suripu.service.pairing.PairingAttempt;
import com.hello.suripu.service.pairing.PairingManager;
import com.hello.suripu.service.pairing.PairingResult;
import com.hello.suripu.service.utils.RegistrationLogger;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import java.util.Arrays;
import java.util.UUID;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
/**
* Created by pangwu on 5/5/15.
*/
public class RegisterResourceIntegrationTest extends ResourceTest {
private static final String SENSE_ID = "test sense";
private static final String ACCESS_TOKEN = "test access token";
private static final byte[] KEY = "1234567891234567".getBytes();
private RegisterResource registerResource;
private PairingManager pairingManager;
private RegistrationLogger registrationLogger;
private Swapper swapper;
private Optional<AccessToken> stubGetClientDetailsByToken(final OAuthTokenStore<AccessToken, ClientDetails, ClientCredentials> tokenStore) {
try {
return tokenStore.getTokenByClientCredentials(any(ClientCredentials.class), any(DateTime.class));
} catch (MissingRequiredScopeException e) {
return Optional.absent();
}
}
private void stubGetClientDetailsByTokenThatReturnsNoAccessToken(final OAuthTokenStore<AccessToken, ClientDetails, ClientCredentials> tokenStore){
when(stubGetClientDetailsByToken(tokenStore)).thenReturn(Optional.<AccessToken>absent());
}
private void stubGetClientDetails(final OAuthTokenStore<AccessToken, ClientDetails, ClientCredentials> tokenStore,
final Optional<AccessToken> returnValue){
when(stubGetClientDetailsByToken(tokenStore)).thenReturn(returnValue);
}
private AccessToken getAccessToken(){
return new AccessToken(UUID.randomUUID(), UUID.randomUUID(), 0L, 0L, DateTime.now(), 1L, 1L, new OAuthScope[]{ OAuthScope.AUTH });
}
private byte[] generateInvalidEncryptedMessage(){
final byte[] raw = new byte[10];
return raw;
}
private byte[] generateValidProtobufWithSignature(final byte[] key){
final SenseCommandProtos.MorpheusCommand command = SenseCommandProtos.MorpheusCommand.newBuilder()
.setType(SenseCommandProtos.MorpheusCommand.CommandType.MORPHEUS_COMMAND_PAIR_SENSE)
.setAccountId(ACCESS_TOKEN)
.setVersion(1)
.setDeviceId(SENSE_ID)
.build();
final byte[] body = command.toByteArray();
final Optional<byte[]> signedOptional = SignedMessage.sign(body, key);
assertThat(signedOptional.isPresent(), is(true));
final byte[] signed = signedOptional.get();
final byte[] iv = Arrays.copyOfRange(signed, 0, 16);
final byte[] sig = Arrays.copyOfRange(signed, 16, 16 + 32);
final byte[] message = new byte[signed.length];
copyTo(message, body, 0, body.length);
copyTo(message, iv, body.length, body.length + iv.length);
copyTo(message, sig, body.length + iv.length, message.length);
return message;
}
private byte[] generateValidProtobufWithInvalidSignature(final byte[] key){
final SenseCommandProtos.MorpheusCommand command = SenseCommandProtos.MorpheusCommand.newBuilder()
.setType(SenseCommandProtos.MorpheusCommand.CommandType.MORPHEUS_COMMAND_PAIR_SENSE)
.setAccountId(ACCESS_TOKEN)
.setVersion(1)
.setDeviceId(SENSE_ID)
.build();
final byte[] body = command.toByteArray();
final Optional<byte[]> signedOptional = SignedMessage.sign(body, key);
assertThat(signedOptional.isPresent(), is(true));
final byte[] signed = signedOptional.get();
final byte[] iv = Arrays.copyOfRange(signed, 0, 16);
final byte[] message = new byte[signed.length];
copyTo(message, body, 0, body.length);
copyTo(message, iv, body.length, body.length + iv.length);
copyTo(message, new byte[32], body.length + iv.length, message.length);
return message;
}
private byte[] generateInvalidProtobuf(final byte[] key){
final SenseCommandProtos.MorpheusCommand command = SenseCommandProtos.MorpheusCommand.newBuilder()
.setType(SenseCommandProtos.MorpheusCommand.CommandType.MORPHEUS_COMMAND_PAIR_SENSE)
.setAccountId(ACCESS_TOKEN)
.setVersion(1)
.setDeviceId(SENSE_ID)
.build();
final byte[] body = command.toByteArray();
final Optional<byte[]> signedOptional = SignedMessage.sign(body, key);
assertThat(signedOptional.isPresent(), is(true));
return signedOptional.get();
}
private void copyTo(final byte[] dest, final byte[] src, final int start, final int end){
for(int i = start; i < end; i++){
dest[i] = src[i-start];
}
}
@Before
public void setUp(){
super.setUp();
BaseResourceTestHelper.kinesisLoggerFactoryStubGet(this.kinesisLoggerFactory, QueueName.LOGS, this.dataLogger);
BaseResourceTestHelper.kinesisLoggerFactoryStubGet(this.kinesisLoggerFactory, QueueName.REGISTRATIONS, this.dataLogger);
pairingManager = mock(PairingManager.class);
registrationLogger = mock(RegistrationLogger.class);
swapper = mock(Swapper.class);
when(pairingManager.withLogger(any(RegistrationLogger.class))).thenReturn(pairingManager);
when(pairingManager.logger()).thenReturn(new NoOpRegistrationLogger());
when(keyStore.get(any(String.class))).thenReturn(Optional.of(KeyStoreDynamoDB.DEFAULT_AES_KEY));
final RegisterResource registerResource = new RegisterResource(deviceDAO,
oAuthTokenStore,
kinesisLoggerFactory,
keyStore,
groupFlipper,
pairingManager);
registerResource.request = httpServletRequest;
this.registerResource = spy(registerResource); // the registerResource is a real object, we need to spy it.
BaseResourceTestHelper.stubGetHeader(this.registerResource.request, "X-Forwarded-For", "127.0.0.1");
}
@Test(expected = WebApplicationException.class)
public void testPairingCannotDecryptMessage(){
this.registerResource.pair(SENSE_ID,
generateInvalidEncryptedMessage(),
this.keyStore,
PairAction.PAIR_MORPHEUS, "127.0.0.1");
verify(this.registerResource).throwPlainTextError(Response.Status.BAD_REQUEST, "");
}
@Test(expected = WebApplicationException.class)
public void testPairingCannotParseProtobuf(){
this.registerResource.pair(SENSE_ID,
generateInvalidProtobuf(KEY),
this.keyStore,
PairAction.PAIR_MORPHEUS,"127.0.0.1");
verify(this.registerResource).throwPlainTextError(Response.Status.BAD_REQUEST, "");
}
/*
* simulate scenario that no account can be found with the token provided
*/
@Test
public void testPairingCannotFindToken(){
// simulate scenario that no account can be found with the token provided
stubGetClientDetailsByTokenThatReturnsNoAccessToken(this.oAuthTokenStore);
final SenseCommandProtos.MorpheusCommand.Builder builder = this.registerResource.pair(SENSE_ID,
generateValidProtobufWithSignature(KEY),
this.keyStore,
PairAction.PAIR_MORPHEUS, "127.0.0.1");
assertThat(builder.getType(), is(SenseCommandProtos.MorpheusCommand.CommandType.MORPHEUS_COMMAND_ERROR));
assertThat(builder.getError(), is(SenseCommandProtos.ErrorType.INTERNAL_OPERATION_FAILED));
}
@Test(expected = WebApplicationException.class)
public void testPairingInvalidSignature(){
stubGetClientDetails(this.oAuthTokenStore, Optional.of(getAccessToken()));
BaseResourceTestHelper.stubKeyFromKeyStore(this.keyStore, SENSE_ID, Optional.of(KEY));
this.registerResource.pair(SENSE_ID,
generateValidProtobufWithInvalidSignature(KEY),
this.keyStore,
PairAction.PAIR_MORPHEUS, "127.0.0.1");
verify(this.registerResource).throwPlainTextError(Response.Status.UNAUTHORIZED, "invalid signature");
}
@Test(expected = WebApplicationException.class)
public void testPairingNoKey(){
stubGetClientDetails(this.oAuthTokenStore, Optional.of(getAccessToken()));
BaseResourceTestHelper.stubKeyFromKeyStore(this.keyStore, SENSE_ID, Optional.<byte[]>absent());
this.registerResource.pair(SENSE_ID,
generateValidProtobufWithInvalidSignature(KEY),
this.keyStore,
PairAction.PAIR_MORPHEUS, "127.0.0.1");
verify(this.registerResource).throwPlainTextError(Response.Status.UNAUTHORIZED, "no key");
verify(this.deviceDAO, times(0)).registerSense(1L, SENSE_ID);
}
/*
* Happy pass for pairing
*/
@Test
public void testPairSense(){
stubGetClientDetails(this.oAuthTokenStore, Optional.of(getAccessToken()));
BaseResourceTestHelper.stubKeyFromKeyStore(this.keyStore, SENSE_ID, Optional.of(KEY));
final SenseCommandProtos.MorpheusCommand.Builder builder = SenseCommandProtos.MorpheusCommand.newBuilder()
.setType(SenseCommandProtos.MorpheusCommand.CommandType.MORPHEUS_COMMAND_PAIR_SENSE)
.setVersion(0);
when(pairingManager.pairSense(any(PairingAttempt.class))).thenReturn(new PairingResult(builder, registrationLogger));
final SenseCommandProtos.MorpheusCommand command = this.registerResource.pair(SENSE_ID,
generateValidProtobufWithSignature(KEY),
this.keyStore,
PairAction.PAIR_MORPHEUS, "127.0.0.1").build();
assertEquals(SenseCommandProtos.MorpheusCommand.CommandType.MORPHEUS_COMMAND_PAIR_SENSE, command.getType());
}
/*
* Happy pass for testing the endpoint function
*/
@Test
public void testRegisterSense() throws InvalidProtocolBufferException {
stubGetClientDetails(this.oAuthTokenStore, Optional.of(getAccessToken()));
BaseResourceTestHelper.stubKeyFromKeyStore(this.keyStore, SENSE_ID, Optional.of(KEY));
final SenseCommandProtos.MorpheusCommand.Builder builder = SenseCommandProtos.MorpheusCommand.newBuilder()
.setType(SenseCommandProtos.MorpheusCommand.CommandType.MORPHEUS_COMMAND_PAIR_SENSE)
.setVersion(0);
when(pairingManager.pairSense(any(PairingAttempt.class))).thenReturn(new PairingResult(builder, registrationLogger)); BaseResourceTestHelper.stubGetHeader(this.httpServletRequest, HelloHttpHeader.SENSE_ID, SENSE_ID);
final byte[] data = this.registerResource.registerMorpheus(generateValidProtobufWithSignature(KEY));
final byte[] protobufBytes = Arrays.copyOfRange(data, 16 + 32, data.length);
final SenseCommandProtos.MorpheusCommand command = SenseCommandProtos.MorpheusCommand.parseFrom(protobufBytes);
assertFalse("should not have accountId", command.hasAccountId());
assertEquals(SenseCommandProtos.MorpheusCommand.CommandType.MORPHEUS_COMMAND_PAIR_SENSE, command.getType());
}
/*
* Test when the sam account tries to pair twice
*/
@Test
public void testPairAlreadyPairedSense(){
stubGetClientDetails(this.oAuthTokenStore, Optional.of(getAccessToken()));
BaseResourceTestHelper.stubKeyFromKeyStore(this.keyStore, SENSE_ID, Optional.of(KEY));
final SenseCommandProtos.MorpheusCommand.Builder builder = SenseCommandProtos.MorpheusCommand.newBuilder()
.setType(SenseCommandProtos.MorpheusCommand.CommandType.MORPHEUS_COMMAND_PAIR_SENSE)
.setVersion(0);
when(pairingManager.pairSense(any(PairingAttempt.class))).thenReturn(new PairingResult(builder, registrationLogger));
final SenseCommandProtos.MorpheusCommand command = this.registerResource.pair(SENSE_ID,
generateValidProtobufWithSignature(KEY),
this.keyStore,
PairAction.PAIR_MORPHEUS, "127.0.0.1").build();
verify(this.deviceDAO, times(0)).registerSense(1L, SENSE_ID);
assertThat(command.getType(), is(SenseCommandProtos.MorpheusCommand.CommandType.MORPHEUS_COMMAND_PAIR_SENSE));
}
/*
* Test one account tries to pair to two different Senses.
*/
@Test
public void testPairAlreadyPairedSenseToDifferentAccount(){
stubGetClientDetails(this.oAuthTokenStore, Optional.of(getAccessToken()));
BaseResourceTestHelper.stubKeyFromKeyStore(this.keyStore, SENSE_ID, Optional.of(KEY));
final SenseCommandProtos.MorpheusCommand.Builder builder = SenseCommandProtos.MorpheusCommand.newBuilder()
.setType(SenseCommandProtos.MorpheusCommand.CommandType.MORPHEUS_COMMAND_PAIR_SENSE)
.setVersion(0);
when(pairingManager.pairSense(any(PairingAttempt.class))).thenReturn(new PairingResult(builder, registrationLogger));
final SenseCommandProtos.MorpheusCommand command = this.registerResource.pair(SENSE_ID,
generateValidProtobufWithSignature(KEY),
this.keyStore,
PairAction.PAIR_MORPHEUS, "127.0.0.1").build();
assertEquals(SenseCommandProtos.MorpheusCommand.CommandType.MORPHEUS_COMMAND_PAIR_SENSE, command.getType());
assertFalse(command.hasError());
}
}
|
package slimeknights.tconstruct.shared.block;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IStringSerializable;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.Locale;
import slimeknights.mantle.block.EnumBlock;
import slimeknights.tconstruct.TinkerIntegration;
import slimeknights.tconstruct.library.TinkerRegistry;
import slimeknights.tconstruct.shared.TinkerFluids;
public class BlockMetal extends EnumBlock<BlockMetal.MetalTypes> {
public static final PropertyEnum<MetalTypes> TYPE = PropertyEnum.create("type", MetalTypes.class);
public BlockMetal() {
super(Material.IRON, TYPE, MetalTypes.class);
setHardness(5f);
setHarvestLevel("pickaxe", -1); // we're generous. no harvest level required
setCreativeTab(TinkerRegistry.tabGeneral);
}
@SideOnly(Side.CLIENT)
@Override
public void getSubBlocks(CreativeTabs tab, NonNullList<ItemStack> list) {
for(MetalTypes type : MetalTypes.values()) {
if(type == MetalTypes.ALUBRASS && !TinkerIntegration.isIntegrated(TinkerFluids.alubrass)) {
continue;
}
list.add(new ItemStack(this, 1, type.getMeta()));
}
}
@Override
public boolean isBeaconBase(IBlockAccess worldObj, BlockPos pos, BlockPos beacon) {
return true;
}
public enum MetalTypes implements IStringSerializable, EnumBlock.IEnumMeta {
COBALT,
ARDITE,
MANYULLYN,
KNIGHTSLIME,
PIGIRON,
ALUBRASS,
SILKY_JEWEL;
public final int meta;
MetalTypes() {
meta = ordinal();
}
@Override
public String getName() {
return this.toString().toLowerCase(Locale.US);
}
@Override
public int getMeta() {
return meta;
}
}
}
|
package com.esum.router.logger;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
import com.esum.framework.common.util.DateUtil;
import com.esum.framework.common.util.FileUtil;
import com.esum.framework.core.event.log.AttachmentLog;
import com.esum.framework.core.event.log.DocumentLog;
import com.esum.framework.core.event.log.LoggingEvent;
import com.esum.framework.core.logger.LoggerConfig;
import com.esum.framework.jdbc.MapResultSetExtractor;
import com.esum.framework.jdbc.PreparedStatementCallback;
import com.esum.framework.jdbc.RecordMap;
import com.esum.framework.jdbc.SqlTemplate;
import com.esum.framework.jdbc.support.JdbcUtils;
import com.esum.router.logger.cache.ErrorSeqCache;
import com.esum.router.logger.cache.LoggerCache;
public class LoggerUtil
{
public static org.slf4j.Logger log = LoggerFactory.getLogger(LoggerUtil.class);
private static String latestLoggingTime = DateUtil.format("yyyyMMddHHmmssSSS");
public static boolean isEmpty(String str){
if(str==null || str.equals("null") || str.equals(""))
return true;
return false;
}
public static boolean isEmpty(long val){
if(val == 0)
return true;
return false;
}
/**
* MESSAGE_LOG 의 LOG_TIME(로그 이벤트 생성시간)을 가져오도록 수정. (로그 순서 꼬이는 문제 해결을 위해)
*/
public static String getMessageLogTimeById(final String msgCtrlId, Connection connection) throws SQLException
{
String logTime = LoggerCache.getInstance().getCache(msgCtrlId);
if(StringUtils.isNotEmpty(logTime)) {
if(log.isDebugEnabled())
log.debug("["+msgCtrlId+"] Returns the LoggerCache. log time : "+logTime);
return logTime;
}
if(log.isDebugEnabled())
log.debug("["+msgCtrlId+"] Finding log time about messageCtrlId : "+msgCtrlId);
StringBuffer buffer = new StringBuffer();
buffer.append("SELECT /*+INDEX(MESSAGE_LOG MESSAGE_LOG_PK) */ LOG_TIME FROM MESSAGE_LOG ");
buffer.append("WHERE MESSAGE_CTRL_ID = ?");
SqlTemplate sqlTemplate = new SqlTemplate();
RecordMap map = sqlTemplate.execute(connection, buffer.toString(), new PreparedStatementCallback<RecordMap>() {
@Override
public RecordMap doInPreparedStatement(PreparedStatement ps) throws SQLException {
ps.setString(1, msgCtrlId);
ResultSet rs = null;
try {
rs = ps.executeQuery();
return new MapResultSetExtractor().extractData(rs);
} finally {
JdbcUtils.closeQuietly(rs);
}
}
});
if(map!=null){
logTime = map.getString("LOG_TIME", null);
if(StringUtils.isNotEmpty(logTime)){
LoggerCache.getInstance().putCache(msgCtrlId, logTime);
return logTime;
}
}
return null;
}
public static String getErrorSeqNo(final String msgCtrlId, Connection connection) throws SQLException {
String errorSeq = ErrorSeqCache.getInstance().getCache(msgCtrlId);
if(StringUtils.isNotEmpty(errorSeq)) {
if(log.isDebugEnabled())
log.debug("["+msgCtrlId+"] returns the cache. error seq : "+errorSeq);
return errorSeq;
}
StringBuffer buffer = new StringBuffer();
buffer.append("SELECT COUNT(*) AS ERRSEQNO FROM ERROR_SUMMARY ");
buffer.append("WHERE MESSAGE_CTRL_ID = ?");
SqlTemplate sqlTemplate = new SqlTemplate();
RecordMap map = sqlTemplate.execute(connection, buffer.toString(), new PreparedStatementCallback<RecordMap>() {
@Override
public RecordMap doInPreparedStatement(PreparedStatement ps) throws SQLException {
ps.setString(1, msgCtrlId);
ResultSet rs = null;
try {
rs = ps.executeQuery();
return new MapResultSetExtractor().extractData(rs);
} finally {
JdbcUtils.closeQuietly(rs);
}
}
});
int errorSeqNo = map.getInt("ERRSEQNO");
if(log.isDebugEnabled())
log.debug("["+msgCtrlId+"] getErrorSeqNo : "+ errorSeqNo);
ErrorSeqCache.getInstance().putCache(msgCtrlId, ""+errorSeqNo);
return ""+errorSeqNo;
}
public static String newLoggingTime(String curProcTime) {
if(StringUtils.isEmpty(curProcTime))
return DateUtil.format("yyyyMMddHHmmssSSS");
String newTime = DateUtil.format("yyyyMMddHHmmssSSS");
if(newTime.equals(curProcTime)) {
do {
try {Thread.sleep(1);} catch (InterruptedException e) {break;}
newTime = DateUtil.format("yyyyMMddHHmmssSSS");
} while(newTime.equals(curProcTime));
}
return newTime;
}
/**
* DocumentLog의 Document를 Messagebox에 저장하기 위한 절대 경로를 구한다.
* <p>
* 형식 : Messagebox home/ccyymmdd/수신자의 User Id/recv/control id/seq no/module name.doc
*/
public static File saveDocumentFile(LoggingEvent logEvent, DocumentLog docLog)
{
String controlID = logEvent.getMessageCtrlId();
String traceID = "[" + controlID + "] ";
String cymd = DateUtil.getCYMD();
if(log.isDebugEnabled())
log.debug(traceID+"Save Document File. Receiver User ID: " + docLog.getRecverInfo().getSvcId()
+ ", TP ID: " + docLog.getRecverInfo().getTPId());
String recverTpId = docLog.getRecverInfo().getTPId();
if(StringUtils.isEmpty(recverTpId))
recverTpId = "unknown";
String docName = docLog.getDocName();
if(StringUtils.isEmpty(docName))
docName = "unknown";
StringBuffer mboxDirectory = new StringBuffer(LoggerConfig.MBOX_DIR);
/**
* MBOX_DIR/일자/수신자TP/문서명/recv/
*/
mboxDirectory.append('/').append(cymd);
mboxDirectory.append('/').append(recverTpId);
mboxDirectory.append('/').append(docName);
String directory = null;
if (docLog.getErrorInfo() == null || (LoggerUtil.isEmpty(docLog.getErrorInfo().getErrorCode())))
directory = mboxDirectory.toString() + File.separator + "recv";
else
directory = mboxDirectory.toString() + File.separator + "error";
File dir = new File(directory);
if (!dir.exists()) {
dir.setWritable(true, false);
dir.mkdirs();
}
StringBuffer filename = new StringBuffer(controlID);
filename.append('_').append(logEvent.getModuleName());
filename.append('_').append(logEvent.getProcessingStatus());
filename.append('_').append(docLog.getDocSeqno());
filename.append("_").append(logEvent.getLoggingInfo().getMessageLog().getRetryCount()+"_1");
filename.append(".doc");
File docFile = new File(dir, filename.toString());
if (docFile.exists()) {
filename.insert(filename.lastIndexOf("_"), "_RETRY" + logEvent.getLoggingInfo().getMessageLog().getRetryCount());
docFile = new File(dir, filename.toString());
}
if(log.isDebugEnabled())
log.debug(traceID + docFile.getPath() + " Saving..");
try {
String reservedDir = mboxDirectory.toString() + File.separator + "ioerror" + File.separator + DateUtil.format("HH") + "H";
docFile = FileUtil.writeToFileWithResevedDir(directory, filename.toString(), docLog.getData(),
reservedDir);
} catch (Exception e) {
log.error(traceID + "Fail to saving file.." + docFile.getPath(), e);
}
return docFile;
}
/**
* Save a attached files.
*/
public static File saveAttachmentFile(LoggingEvent logEvent, AttachmentLog attachLog, String receiverTp, String docName) {
String controlID = logEvent.getMessageCtrlId();
String traceID = "[" + controlID + "] ";
String cymd = DateUtil.getCYMD();
StringBuffer mboxDirectory = new StringBuffer(LoggerConfig.MBOX_DIR);
mboxDirectory.append('/').append(cymd);
mboxDirectory.append('/').append(receiverTp);
mboxDirectory.append('/').append(docName);
String directory = mboxDirectory.toString() + File.separator + "recv_attach";
File dir = new File(directory);
if (!dir.exists()) {
dir.setWritable(true, false);
dir.mkdirs();
}
StringBuffer filename = new StringBuffer(controlID);
filename.append('_').append(logEvent.getModuleName());
filename.append('_').append(logEvent.getProcessingStatus());
filename.append('_').append("ATTACH");
filename.append('_').append(attachLog.getAttachSeqNo());
filename.append("_").append(logEvent.getLoggingInfo().getMessageLog().getRetryCount()+"_1");
filename.append(".attach");
File attachFile = new File(dir, filename.toString());
if (attachFile.exists()) {
filename.insert(filename.lastIndexOf("_"), "_RETRY" + logEvent.getLoggingInfo().getMessageLog().getRetryCount());
attachFile = new File(dir, filename.toString());
}
if(log.isDebugEnabled())
log.debug(traceID + attachFile.getPath() + " Saving..");
try {
String reservedDir = mboxDirectory.toString() + File.separator + "ioerror" + File.separator + DateUtil.format("HH") + "H";
attachFile = FileUtil.writeToFileWithResevedDir(directory, filename.toString(), attachLog.getAttachmentData(),
reservedDir);
} catch (Exception e) {
log.error(traceID + "Fail to saving attachment file.." + attachFile.getPath(), e);
}
return attachFile;
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cache.interceptor;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.cache.annotation.AnnotationCacheOperationSource;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.context.expression.AnnotatedElementKey;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Costin Leau
* @author Phillip Webb
* @author Sam Brannen
* @author Stephane Nicoll
*/
public class ExpressionEvaluatorTests {
private final CacheOperationExpressionEvaluator eval = new CacheOperationExpressionEvaluator();
private final AnnotationCacheOperationSource source = new AnnotationCacheOperationSource();
private Collection<CacheOperation> getOps(String name) {
Method method = ReflectionUtils.findMethod(AnnotatedClass.class, name, Object.class, Object.class);
return this.source.getCacheOperations(method, AnnotatedClass.class);
}
@Test
public void testMultipleCachingSource() {
Collection<CacheOperation> ops = getOps("multipleCaching");
assertThat(ops).hasSize(2);
Iterator<CacheOperation> it = ops.iterator();
CacheOperation next = it.next();
assertThat(next).isInstanceOf(CacheableOperation.class);
assertThat(next.getCacheNames().contains("test")).isTrue();
assertThat(next.getKey()).isEqualTo("#a");
next = it.next();
assertThat(next).isInstanceOf(CacheableOperation.class);
assertThat(next.getCacheNames().contains("test")).isTrue();
assertThat(next.getKey()).isEqualTo("#b");
}
@Test
public void testMultipleCachingEval() {
AnnotatedClass target = new AnnotatedClass();
Method method = ReflectionUtils.findMethod(
AnnotatedClass.class, "multipleCaching", Object.class, Object.class);
Object[] args = new Object[] {new Object(), new Object()};
Collection<ConcurrentMapCache> caches = Collections.singleton(new ConcurrentMapCache("test"));
EvaluationContext evalCtx = this.eval.createEvaluationContext(caches, method, args,
target, target.getClass(), method, CacheOperationExpressionEvaluator.NO_RESULT, null);
Collection<CacheOperation> ops = getOps("multipleCaching");
Iterator<CacheOperation> it = ops.iterator();
AnnotatedElementKey key = new AnnotatedElementKey(method, AnnotatedClass.class);
Object keyA = this.eval.key(it.next().getKey(), key, evalCtx);
Object keyB = this.eval.key(it.next().getKey(), key, evalCtx);
assertThat(keyA).isEqualTo(args[0]);
assertThat(keyB).isEqualTo(args[1]);
}
@Test
public void withReturnValue() {
EvaluationContext context = createEvaluationContext("theResult");
Object value = new SpelExpressionParser().parseExpression("#result").getValue(context);
assertThat(value).isEqualTo("theResult");
}
@Test
public void withNullReturn() {
EvaluationContext context = createEvaluationContext(null);
Object value = new SpelExpressionParser().parseExpression("#result").getValue(context);
assertThat(value).isNull();
}
@Test
public void withoutReturnValue() {
EvaluationContext context = createEvaluationContext(CacheOperationExpressionEvaluator.NO_RESULT);
Object value = new SpelExpressionParser().parseExpression("#result").getValue(context);
assertThat(value).isNull();
}
@Test
public void unavailableReturnValue() {
EvaluationContext context = createEvaluationContext(CacheOperationExpressionEvaluator.RESULT_UNAVAILABLE);
assertThatExceptionOfType(VariableNotAvailableException.class).isThrownBy(() ->
new SpelExpressionParser().parseExpression("#result").getValue(context))
.satisfies(ex -> assertThat(ex.getName()).isEqualTo("result"));
}
@Test
public void resolveBeanReference() {
StaticApplicationContext applicationContext = new StaticApplicationContext();
BeanDefinition beanDefinition = new RootBeanDefinition(String.class);
applicationContext.registerBeanDefinition("myBean", beanDefinition);
applicationContext.refresh();
EvaluationContext context = createEvaluationContext(CacheOperationExpressionEvaluator.NO_RESULT, applicationContext);
Object value = new SpelExpressionParser().parseExpression("@myBean.class.getName()").getValue(context);
assertThat(value).isEqualTo(String.class.getName());
}
private EvaluationContext createEvaluationContext(Object result) {
return createEvaluationContext(result, null);
}
private EvaluationContext createEvaluationContext(Object result, BeanFactory beanFactory) {
AnnotatedClass target = new AnnotatedClass();
Method method = ReflectionUtils.findMethod(
AnnotatedClass.class, "multipleCaching", Object.class, Object.class);
Object[] args = new Object[] {new Object(), new Object()};
Collection<ConcurrentMapCache> caches = Collections.singleton(new ConcurrentMapCache("test"));
return this.eval.createEvaluationContext(
caches, method, args, target, target.getClass(), method, result, beanFactory);
}
private static class AnnotatedClass {
@Caching(cacheable = { @Cacheable(value = "test", key = "#a"), @Cacheable(value = "test", key = "#b") })
public void multipleCaching(Object a, Object b) {
}
}
}
|
package algo3.fiuba.modelo.cartas.moldes_cartas.cartas_magicas;
import algo3.fiuba.modelo.jugador.Jugador;
import algo3.fiuba.modelo.cartas.Magica;
import algo3.fiuba.modelo.cartas.efectos.EfectoAgujeroNegro;
import algo3.fiuba.modelo.cartas.efectos.EfectoNulo;
public class AgujeroNegro extends Magica {
public AgujeroNegro(Jugador jugador) {
super("Agujero Oscuro", new EfectoNulo());
setJugador(jugador);
this.setEfecto(new EfectoAgujeroNegro(jugador, jugador.getOponente()));
}
}
|
package com.wirelesscar.dynafleet.api;
/**
* Please modify this class to meet your needs
* This class is not complete
*/
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
/**
* This class was generated by Apache CXF 2.7.18
* 2017-06-30T14:30:13.446-05:00
* Generated source version: 2.7.18
*
*/
public final class ServicePlanService_ServicePlanServicePort_Client {
private static final QName SERVICE_NAME = new QName("http://wirelesscar.com/dynafleet/api", "DynafleetAPI");
private ServicePlanService_ServicePlanServicePort_Client() {
}
public static void main(String args[]) throws java.lang.Exception {
URL wsdlURL = DynafleetAPI.WSDL_LOCATION;
if (args.length > 0 && args[0] != null && !"".equals(args[0])) {
File wsdlFile = new File(args[0]);
try {
if (wsdlFile.exists()) {
wsdlURL = wsdlFile.toURI().toURL();
} else {
wsdlURL = new URL(args[0]);
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
DynafleetAPI ss = new DynafleetAPI(wsdlURL, SERVICE_NAME);
ServicePlanService port = ss.getServicePlanServicePort();
{
System.out.println("Invoking getServicePlan...");
com.wirelesscar.dynafleet.api.types.ApiServicePlanGetServicePlanTO _getServicePlan_apiServicePlanGetServicePlanTO1 = new com.wirelesscar.dynafleet.api.types.ApiServicePlanGetServicePlanTO();
com.wirelesscar.dynafleet.api.types.ApiDate _getServicePlan_apiServicePlanGetServicePlanTO1From = new com.wirelesscar.dynafleet.api.types.ApiDate();
_getServicePlan_apiServicePlanGetServicePlanTO1From.setValue(javax.xml.datatype.DatatypeFactory.newInstance().newXMLGregorianCalendar("2017-06-30T14:30:13.454-05:00"));
_getServicePlan_apiServicePlanGetServicePlanTO1.setFrom(_getServicePlan_apiServicePlanGetServicePlanTO1From);
com.wirelesscar.dynafleet.api.types.ApiSessionId _getServicePlan_apiServicePlanGetServicePlanTO1SessionId = new com.wirelesscar.dynafleet.api.types.ApiSessionId();
_getServicePlan_apiServicePlanGetServicePlanTO1SessionId.setId("Id2075347054");
_getServicePlan_apiServicePlanGetServicePlanTO1.setSessionId(_getServicePlan_apiServicePlanGetServicePlanTO1SessionId);
com.wirelesscar.dynafleet.api.types.ApiDate _getServicePlan_apiServicePlanGetServicePlanTO1To = new com.wirelesscar.dynafleet.api.types.ApiDate();
_getServicePlan_apiServicePlanGetServicePlanTO1To.setValue(javax.xml.datatype.DatatypeFactory.newInstance().newXMLGregorianCalendar("2017-06-30T14:30:13.454-05:00"));
_getServicePlan_apiServicePlanGetServicePlanTO1.setTo(_getServicePlan_apiServicePlanGetServicePlanTO1To);
com.wirelesscar.dynafleet.api.types.ApiVehicleId _getServicePlan_apiServicePlanGetServicePlanTO1VehicleId = new com.wirelesscar.dynafleet.api.types.ApiVehicleId();
_getServicePlan_apiServicePlanGetServicePlanTO1VehicleId.setId(-7319970165600925970l);
_getServicePlan_apiServicePlanGetServicePlanTO1.setVehicleId(_getServicePlan_apiServicePlanGetServicePlanTO1VehicleId);
try {
com.wirelesscar.dynafleet.api.types.ApiServicePlanEntryArrayTO _getServicePlan__return = port.getServicePlan(_getServicePlan_apiServicePlanGetServicePlanTO1);
System.out.println("getServicePlan.result=" + _getServicePlan__return);
} catch (DynafleetAPIException e) {
System.out.println("Expected exception: DynafleetAPIException has occurred.");
System.out.println(e.toString());
}
}
{
System.out.println("Invoking getDeletedServicePlans...");
com.wirelesscar.dynafleet.api.types.ApiSessionId _getDeletedServicePlans_apiSessionId1 = new com.wirelesscar.dynafleet.api.types.ApiSessionId();
_getDeletedServicePlans_apiSessionId1.setId("Id-990049732");
try {
com.wirelesscar.dynafleet.api.types.ApiLongArrayTO _getDeletedServicePlans__return = port.getDeletedServicePlans(_getDeletedServicePlans_apiSessionId1);
System.out.println("getDeletedServicePlans.result=" + _getDeletedServicePlans__return);
} catch (DynafleetAPIException e) {
System.out.println("Expected exception: DynafleetAPIException has occurred.");
System.out.println(e.toString());
}
}
{
System.out.println("Invoking getModifiedServicePlans...");
com.wirelesscar.dynafleet.api.types.ApiSessionId _getModifiedServicePlans_apiSessionId1 = new com.wirelesscar.dynafleet.api.types.ApiSessionId();
_getModifiedServicePlans_apiSessionId1.setId("Id-171169084");
try {
com.wirelesscar.dynafleet.api.types.ApiServicePlanEntryArrayTO _getModifiedServicePlans__return = port.getModifiedServicePlans(_getModifiedServicePlans_apiSessionId1);
System.out.println("getModifiedServicePlans.result=" + _getModifiedServicePlans__return);
} catch (DynafleetAPIException e) {
System.out.println("Expected exception: DynafleetAPIException has occurred.");
System.out.println(e.toString());
}
}
System.exit(0);
}
}
|
package com.snowinpluto.tools.analysis;
import com.google.inject.Singleton;
import java.lang.reflect.Field;
import static com.google.common.base.Preconditions.checkNotNull;
@Singleton
public class FieldAnalyst {
public ColumnType analyst(Field f) {
checkNotNull(f);
Class typeClass = f.getType();
String typeName = typeClass.getSimpleName();
if ("short".equals(typeName) || "Short".equals(typeName) ||
"int".equals(typeName) || "Integer".equals(typeName) ||
"long".equals(typeName) || "Long".equals(typeName) ||
"float".equals(typeName) || "Float".equals(typeName) ||
"double".equals(typeName) || "Double".equals(typeName)) {
return ColumnType.NUMERIC;
}
else if ("String".equals(typeName) || typeClass.isEnum()) {
return ColumnType.VARCHAR;
}
else if ("Date".equals(typeName)) {
return ColumnType.TIMESTAMP;
}
return null;
}
}
|
package by.belotserkovsky.pojos.constants;
/**
* Created by K.Belotserkovsky
*/
public enum Role {
USER("USER"),
ADMIN("ADMIN");
private final String type;
Role(String type){
this.type = type;
}
public String getType(){
return type;
}
}
|
package cn.rongcapital.mc2.me.ewq.app;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import cn.rongcapital.mc2.me.commons.infrastructure.ignite.IgniteServiceDeployment;
import cn.rongcapital.mc2.me.ewq.api.CampaignQueueApi;
@Component
public class Launch implements ApplicationListener<ApplicationReadyEvent> {
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
IgniteServiceDeployment.deploy(CampaignQueueApi.class);
}
}
|
package com.davivienda.utilidades.ws.cliente.consultaTotalesMultifuncional;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for consultaTotalesMultifuncionalDto complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="consultaTotalesMultifuncionalDto">
* <complexContent>
* <extension base="{http://ConsultaTotalesMultifuncional.servicios.procesadortransacciones.davivienda.com/}parametrosDeTransaccionBaseDTO">
* <sequence>
* <element name="indicadorTotales" type="{http://www.w3.org/2001/XMLSchema}short" minOccurs="0"/>
* <element name="tipoConsulta" type="{http://www.w3.org/2001/XMLSchema}short" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "consultaTotalesMultifuncionalDto", propOrder = {
"indicadorTotales",
"tipoConsulta"
})
public class ConsultaTotalesMultifuncionalDto
extends ParametrosDeTransaccionBaseDTO
{
protected Short indicadorTotales;
protected Short tipoConsulta;
/**
* Gets the value of the indicadorTotales property.
*
* @return
* possible object is
* {@link Short }
*
*/
public Short getIndicadorTotales() {
return indicadorTotales;
}
/**
* Sets the value of the indicadorTotales property.
*
* @param value
* allowed object is
* {@link Short }
*
*/
public void setIndicadorTotales(Short value) {
this.indicadorTotales = value;
}
/**
* Gets the value of the tipoConsulta property.
*
* @return
* possible object is
* {@link Short }
*
*/
public Short getTipoConsulta() {
return tipoConsulta;
}
/**
* Sets the value of the tipoConsulta property.
*
* @param value
* allowed object is
* {@link Short }
*
*/
public void setTipoConsulta(Short value) {
this.tipoConsulta = value;
}
}
|
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
/*
* 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.
*/
/**
*
* @author brunosousa
*/
public class fillSESSION implements Runnable {
Connection sys, work;
public fillSESSION(Connection sys, Connection work) {
this.sys = sys;
this.work = work;
}
@Override
public void run() {
System.out.println("SESSIONS :: START");
try {Statement stmt1 = sys.createStatement();
Statement stmt2 = work.createStatement();
ResultSet rs1= stmt1.executeQuery("SELECT V.SESSION_ID, V.SAMPLE_TIME_UTC, V.SQL_PLAN_OPERATION, V.SESSION_TYPE, V.SESSION_STATE, V.USER_ID, V.SQL_ID, V.WAIT_TIME, V.TIME_WAITED "
+ "FROM V_$ACTIVE_SESSION_HISTORY V");
System.out.println("SESSIONS :: FILLING");
int i=0;
while(rs1.next()) {
stmt2.executeUpdate("INSERT INTO SESSIONS "
+ "VALUES ("+(i++)+", "+rs1.getInt(1)+", "+(rs1.getDate(2)!=null ? ("'"+rs1.getDate(2)+"'") : null)+", '"+rs1.getString(3)+"', '"+rs1.getString(4)+"', '"+rs1.getString(5)+"', "+rs1.getInt(6)+", '"+rs1.getString(7)+"', "+rs1.getInt(8)+", "+rs1.getInt(9)+")");
}
System.out.println("SESSIONS :: COMPLETED");
}catch(Exception e){
System.out.println(e);
}
}
}
|
package com.test;
/**
*
* For strings S and T, we say "T divides S" if and only
* if S = T + ... + T (T concatenated with itself 1 or more times)
*
* S/T = 某个整数
*
* Return the largest string X such that X divides str1 and X divides str2.
* 求X1、X2的共同值
*
* 可以直接由长度,求的最大公约数,若最大公约数,不满足,则直接返回0
*
* 方案:逐个遍历
*
* 时间复杂度:
* n*m
*
* @author YLine
*
* 2018年8月30日 上午9:27:48
*/
public class SolutionA
{
public String gcdOfStrings(String str1, String str2)
{
int a = str1.length();
int b = str2.length();
// a > b【求最大公约数】
int diff;
if (a == b)
{
diff = a;
}
else
{
if (a < b)
{
int temp = a;
a = b;
b = temp;
}
diff = a - b;
while (diff > 0)
{
if (a % diff == 0 && b % diff == 0)
{
break;
}
else
{
if (diff > b)
{
a = diff;
diff = a - b;
}
else
{
a = b;
b = diff;
diff = a - b;
}
}
}
}
String common = str1.substring(0, diff);
// 如果,最大公约数,不满足,则最大公约数对应的所有子集都不满足,表示,所有都不满足
// 第一串
if (!assertCommon(str1, common))
{
return "";
}
// 第二串
if (!assertCommon(str2, common))
{
return "";
}
return common;
}
private boolean assertCommon(String main, String pattern)
{
if (main.length() % pattern.length() != 0)
{
return false;
}
else
{
int mainIndex = 0;
int patternIndex = 0;
while (mainIndex < main.length())
{
patternIndex = mainIndex % pattern.length();
if (main.charAt(mainIndex) != pattern.charAt(patternIndex))
{
return false;
}
mainIndex++;
}
}
return true;
}
}
|
package com.example.bottomnavigationtest.ui;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.bottomnavigationtest.R;
public class TestFragment extends Fragment {
protected View mRootView;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.fragment_test, container,false);
return mRootView;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
TextView textView = mRootView.findViewById(R.id.tv_text);
textView.setText(getText());
}
protected String getText(){
return getClass().getSimpleName();
}
}
|
package dao;
import models.User;
import java.util.List;
public interface UserDAO {
User getByLogin(String login);
User getByAuth(String password, String login);
void save(User user);
void update(User user);
void delete(User user);
}
|
package com.stackroute.pe2;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import java.io.File;
import java.io.IOException;
public class FrequencyOfWordsCheckerTest {
FrequencyOfWordsChecker frequencyOfWordsChecker;
@Before
public void setUp() throws Exception {
frequencyOfWordsChecker = new FrequencyOfWordsChecker();
}
@After
public void tearDown() throws Exception {
}
@Test
public void checkWordFrequency() throws IOException {
File file = new File("/home/pallavi/IdeaProjects/PE2/src/main/imp.txt");
assertEquals(21,(long)frequencyOfWordsChecker.checkWordFrequency(file.getAbsolutePath()));
assertNull("null is expected",frequencyOfWordsChecker.checkWordFrequency(""));
}
}
|
package com.flyingh.moguard.service;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.IBinder;
import android.text.format.Formatter;
import android.widget.RemoteViews;
import com.flyingh.moguard.R;
import com.flyingh.moguard.receiver.TaskManagerWidgetProvider;
public class TaskManagerService extends Service {
private ActivityManager am;
private ScheduledExecutorService executorService;
@Override
public void onCreate() {
super.onCreate();
am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
executorService = Executors.newScheduledThreadPool(1);
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
RemoteViews views = new RemoteViews(getPackageName(), R.layout.layout_task_manager_widget);
views.setTextViewText(R.id.processCountTextView, getProcessCount());
views.setTextViewText(R.id.memoryTextView, getAvailableMemory());
views.setOnClickPendingIntent(R.id.cleanButton, PendingIntent.getService(TaskManagerService.this, 0, new Intent(
TaskManagerService.this, KillBackgroundProcessesService.class), PendingIntent.FLAG_UPDATE_CURRENT));
AppWidgetManager.getInstance(TaskManagerService.this).updateAppWidget(
new ComponentName(TaskManagerService.this, TaskManagerWidgetProvider.class), views);
}
}, 0, 1, TimeUnit.SECONDS);
}
protected CharSequence getAvailableMemory() {
MemoryInfo outInfo = new MemoryInfo();
am.getMemoryInfo(outInfo);
return Formatter.formatFileSize(this, outInfo.availMem);
}
protected CharSequence getProcessCount() {
return String.valueOf(am.getRunningAppProcesses().size());
}
@Override
public void onDestroy() {
super.onDestroy();
executorService.shutdown();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
|
package com.sample.web.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class HealthInfoDTO {
private Long height;
private Long weight;
}
|
package com.galaksiya.education.rss.common;
public class Info {
public static final String RSS_FILE = "/home/galaksiya/Desktop/RSSfile.csv";
public static final String SERVLET_URL = "http://localhost:8080/feeds";
}
|
package sample;
import javafx.scene.image.Image;
import javafx.scene.paint.ImagePattern;
import javafx.scene.shape.Rectangle;
import java.io.Serializable;
import java.util.Random;
public class Choco implements Serializable {
public Rectangle choco;
public double x;
public double y;
public long timeCreated;
public boolean taken = false;
public Choco(int row, int column) {
x = (column * (Block.getWidth())) + Block.getPaddingH() + (Block.getWidth() / 2) - 15;
y = (row * (Block.getHeight())) + Block.getPaddingTop() + (Block.getHeight() / 2) - 15;
draw();
}
private void draw() {
choco = new Rectangle();
choco.setWidth(30);
choco.setHeight(30);
choco.setX(x);
choco.setY(y);
String url;
if (new Random().nextInt(20) % 2 == 0) {
url = "sample/assets/c1.png";
} else {
url = "sample/assets/c2.png";
}
choco.setFill(new ImagePattern(new Image(url)));
}
}
|
package com.online.model;
public class EmpAndAddr {
int eno;
String ename;
String edesignation;
String egender;
double esalary;
String eusername;
String epassword;
int eaid;
int aid;
String street;
String city;
String state;
int pincode;
String contact;
String email;
public EmpAndAddr() {
}
public EmpAndAddr(int eno, String ename, String edesignation, String egender, double esalary,
String eusername, String epassword, int eaid, int aid, String street, String city, String state,
int pincode, String contact, String email) {
this.eno = eno;
this.ename = ename;
this.edesignation = edesignation;
this.egender = egender;
this.esalary = esalary;
this.eusername = eusername;
this.epassword = epassword;
this.eaid = eaid;
this.aid = aid;
this.street = street;
this.city = city;
this.state = state;
this.pincode = pincode;
this.contact = contact;
this.email = email;
}
public int getEno() { // to pull data
return eno;
}
public void setEno(int eno) { // to store data
this.eno = eno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getEdesignation() {
return edesignation;
}
public void setEdesignation(String edesignation) {
this.edesignation = edesignation;
}
public String getEgender() {
return egender;
}
public void setEgender(String gender) {
this.egender = gender;
}
public double getEsalary() {
return esalary;
}
public void setEsalary(double esal) {
this.esalary = esal;
}
public String getEusername() {
return eusername;
}
public void setEusername(String username) {
this.eusername = username;
}
public String getEpassword() {
return epassword;
}
public void setEpassword(String password) {
this.epassword = password;
}
public void getEpassword(String password) {
this.epassword = password;
}
public int getEaid() {
return eaid;
}
public void setEaid(int eaid) {
this.eaid = eaid;
}
public int getAid() {
return aid;
}
public void setAid(int aid) {
this.aid = aid;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getPincode() {
return pincode;
}
public void setPincode(int pincode) {
this.pincode = pincode;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
|
// Copyright (C) 2016 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.reviewit.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import com.google.gerrit.extensions.common.ChangeInfo;
import com.google.reviewit.R;
import com.google.reviewit.app.Change;
import com.google.reviewit.app.ReviewItApp;
import com.google.reviewit.util.WidgetUtil;
public class ChangeEntry extends LinearLayout {
public ChangeEntry(Context context) {
this(context, null, 0);
}
public ChangeEntry(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ChangeEntry(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
inflate(context, R.layout.change_entry, this);
}
public void init(ReviewItApp app, Change change) {
((ProjectBranchTopicAgeView)findViewById(R.id.projectBranchTopicAge))
.init(change);
((UserView)findViewById(R.id.owner)).init(app, change.info.owner);
ChangeInfo info = change.info;
WidgetUtil.setText(findViewById(R.id.subject), info.subject);
((CodeReviewVotes)findViewById(R.id.codeReviewVotes)).init(change);
((VerifiedVotes)findViewById(R.id.verifiedVotes)).init(change);
}
}
|
package com.jeeconf.kafka.sample.configs;
public class QueueTestConfiguration implements RouteConfiguration {
@Override
public String helloTopicEndpoint() {
return "seda:helloTopic";
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author JenoVa
*/
public class AnswerQuestion {
private int st_am_id;
private int q_id;
private int q_order;
private int acc_id;
private int g_id;
private String answer;
private double score;
private String hilightKeyword;
public int getSt_am_id() {
return st_am_id;
}
public void setSt_am_id(int st_am_id) {
this.st_am_id = st_am_id;
}
public int getQ_id() {
return q_id;
}
public void setQ_id(int q_id) {
this.q_id = q_id;
}
public int getQ_order() {
return q_order;
}
public void setQ_order(int q_order) {
this.q_order = q_order;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public String getHilightKeyword() {
return hilightKeyword;
}
public void setHilightKeyword(String hilightKeyword) {
this.hilightKeyword = hilightKeyword;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public int getAcc_id() {
return acc_id;
}
public void setAcc_id(int acc_id) {
this.acc_id = acc_id;
}
public int getG_id() {
return g_id;
}
public void setG_id(int g_id) {
this.g_id = g_id;
}
//getStAMQuestion
public static List<AnswerQuestion> getStAMQuestion(int st_am_id) {
Connection conn = ConnectionBuilder.getConnection();
String sql = "select * from student_answer_question where st_ass_id = ?";
PreparedStatement pstm;
List<AnswerQuestion> ans = new ArrayList<AnswerQuestion>();
AnswerQuestion a = null;
try {
pstm = conn.prepareStatement(sql);
pstm.setInt(1, st_am_id);
ResultSet rs = pstm.executeQuery();
while (rs.next()) {
a = new AnswerQuestion();
a.setSt_am_id(rs.getInt("st_ass_id"));
a.setQ_id(rs.getInt("q_id"));
a.setQ_order(rs.getInt("q_order"));
a.setAnswer(rs.getString("answer"));
a.setScore(rs.getDouble("score"));
ans.add(a);
}
conn.close();
} catch (SQLException ex) {
Logger.getLogger(Account.class.getName()).log(Level.SEVERE, null, ex);
}
return ans;
}
public static ArrayList<AnswerQuestion> getStAMQuestion(int st_am_id, int q_id) {
Connection conn = ConnectionBuilder.getConnection();
String sql = "select * from student_answer_question where st_ass_id = ? and q_id = ?";
PreparedStatement pstm;
ArrayList<AnswerQuestion> ans = new ArrayList<AnswerQuestion>();
AnswerQuestion a = null;
try {
pstm = conn.prepareStatement(sql);
pstm.setInt(1, st_am_id);
pstm.setInt(2, q_id);
ResultSet rs = pstm.executeQuery();
while (rs.next()) {
a = new AnswerQuestion();
a.setSt_am_id(rs.getInt("st_ass_id"));
a.setQ_id(rs.getInt("q_id"));
a.setQ_order(rs.getInt("q_order"));
a.setAnswer(rs.getString("answer"));
a.setScore(rs.getDouble("score"));
ans.add(a);
}
conn.close();
} catch (SQLException ex) {
Logger.getLogger(Account.class.getName()).log(Level.SEVERE, null, ex);
}
return ans;
}
//setAmQuestionList
public static int[] setAnswerList(List<AnswerQuestion> ansList, int acc_id, int g_id) {
Connection conn = ConnectionBuilder.getConnection();
String data = "";
// for (AnswerQuestion answerQuestion : ansList) {
// data += "(" + answerQuestion.getSt_am_id() + "," + answerQuestion.getQ_id() + "," + answerQuestion.getQ_order() + "," + acc_id + "," + g_id + ",'" + answerQuestion.getAnswer() + "'," + answerQuestion.getScore() + "),";
// }
// data = data.substring(0, data.length() - 1);
// String sql = "insert into student_answer_question(st_ass_id,q_id,q_order,acc_id,g_id,answer,score) values" + data;
String sql = "insert into student_answer_question(st_ass_id,q_id,q_order,acc_id,g_id,answer,score) values(?,?,?,?,?,?,?)";
System.out.println(sql);
PreparedStatement pstm;
int result[] = null;
try {
pstm = conn.prepareStatement(sql);
for (AnswerQuestion answerQuestion : ansList) {
pstm.setInt(1, answerQuestion.getSt_am_id());
pstm.setInt(2, answerQuestion.getQ_id());
pstm.setInt(3, answerQuestion.getQ_order());
pstm.setInt(4, acc_id);
pstm.setInt(5, g_id);
pstm.setString(6, answerQuestion.getAnswer());
pstm.setDouble(7, answerQuestion.getScore());
pstm.addBatch();
}
result = pstm.executeBatch();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(Account.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
//updateScore
public static int updateScore(AnswerQuestion a) {
Connection conn = ConnectionBuilder.getConnection();
String sql = "update student_answer_question set score=? where st_ass_id=? and q_id=? and q_order=? and acc_id=? and g_id=?";
PreparedStatement pstm;
int result = 0;
try {
pstm = conn.prepareStatement(sql);
pstm.setDouble(1, a.getScore());
// System.out.println("score:"+a.getScore());
pstm.setInt(2, a.getSt_am_id());
pstm.setInt(3, a.getQ_id());
// System.out.println(a.getQ_order());
pstm.setInt(4, a.getQ_order());
pstm.setInt(5, a.getAcc_id());
pstm.setInt(6, a.getG_id());
result = pstm.executeUpdate();
// System.out.println("result:"+result);
conn.close();
} catch (SQLException ex) {
Logger.getLogger(Account.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
public static int updateAns(AnswerQuestion a) {
Connection conn = ConnectionBuilder.getConnection();
String sql = "update student_answer_question set answer=? where st_ass_id=? and q_id=? and q_order=?";
PreparedStatement pstm;
int result = 0;
try {
pstm = conn.prepareStatement(sql);
pstm.setString(1, a.getAnswer());
pstm.setInt(2, a.getSt_am_id());
pstm.setInt(3, a.getQ_id());
pstm.setInt(4, a.getQ_order());
result = pstm.executeUpdate();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(Account.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
//updateAllScore
// public static int updateScore(List<AnswerQuestion> a, int st_ass_id) {
// Connection conn = ConnectionBuilder.getConnection();
// String sql = "";
// PreparedStatement pstm;
// int result = 0;
// return result;
// }
//hilightKeyword
@Override
public String toString() {
return "AnswerQuestion{" + "st_am_id=" + st_am_id + ", q_id=" + q_id + ", q_order=" + q_order + ", acc_id=" + acc_id + ", g_id=" + g_id + ", answer=" + answer + ", score=" + score + ", hilightKeyword=" + hilightKeyword + '}';
}
}
|
package ca.jbrains.pos;
public class Sale {
private Display display;
private Catalog catalog;
public Sale(Display display, Catalog catalog) {
this.display = display;
this.catalog = catalog;
}
public void onBarcode(String barcode) {
if ("".equals(barcode))
display.displayScannedEmptyBarcodeMessage();
else if (catalog.hasBarcode(barcode))
display.displayPrice(catalog
.findPriceByBarcode(barcode));
else
display.displayProductNotFoundMessage(barcode);
}
}
|
public class ConsoleScreen implements IHorseScreen {
@Override
public void print(HorseBase horseBase) {
System.out.print(horseBase.getHorseName() + " , " +horseBase.getHorseScore().getValue() + "\n");
}
}
|
package io.github.joaomlneto.travis_ci_tutorial_java;
public class Driver {
public static void main(String[] args) {
int i = 17;
SimpleCalculator simplecalc = new SimpleCalculator();
int result = simplecalc.add(i, 25);
System.out.println("Simple Calculator\n Result: " + result + "\n");
}
}
|
package com.invillia.acme.persistence.util;
import org.springframework.beans.factory.annotation.Value;
import javax.inject.Named;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Named
@Converter
public class CreditCardScramblePersistenceConverter implements AttributeConverter<String, String> {
public static final int CREDIT_CARD_NUMBER_LENGTH = 16;
@Value("invillia.cardScramblingKey")
private String scramblingKey;
@Override
public String convertToDatabaseColumn(String attribute) {
return transform(attribute);
}
@Override
public String convertToEntityAttribute(String dbData) {
return transform(dbData);
}
/**
* Simple masking function to avoid storing credit card numbers out in the open.
* Card data should not be considered secured just by this.
*
* @param attribute
* @return
*/
private String transform(String attribute) {
StringBuilder str = new StringBuilder(CREDIT_CARD_NUMBER_LENGTH);
char[] attributeArray = attribute.toCharArray();
//Performs a XOR with the card chars and the key provided in the application.properties
for(int index = 0; index < attributeArray.length; index++) {
char keyChar = scramblingKey.charAt(index % scramblingKey.length());
str.append((char) (attributeArray[index] ^ keyChar));
}
return str.toString();
}
}
|
package com.mx.cdmx.cacho.partnersample;
import java.util.Objects;
public class Equals {
public static void main(String[] args) {
Person joe = new Person("Joe", "Montana");
Object mrJoe = new Person("Joe", "Montana");
boolean equal = joe.equals(mrJoe);
System.out.println(equal);
}
public static class Person {
private String firstName;
private String lastName;
public Person(String firstName, String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null)
return false;
if (!(o instanceof Person))
return false;
if (getClass() != o.getClass())
return false;
Person person = (Person) o;
return Objects.equals(firstName, person.firstName)
&& Objects.equals(lastName, person.lastName);
}
@Override
public final int hashCode() {
int result = 17;
if (firstName != null) {
result = 31 * result + firstName.hashCode();
}
if (lastName != null) {
result = 31 * result + lastName.hashCode();
}
return result;
}
}
}
|
package ru.job4j.iterator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Класс IterOfIterToIterTest тестирует класс IterOfIterToIter.
*
* @author Gureyev Ilya (mailto:ill-jah@yandex.ru)
* @version 2018-12-07
* @since 2017-05-23
*/
public class IterOfIterToIterTest {
/**
* Тестирует исключение NoSuchElementException.
*/
@Test(expected = NoSuchElementException.class)
public void testNoSuchElementException() {
ArrayList<Integer> aL1 = new ArrayList<>();
aL1.addAll(Arrays.asList(1, 2, 3, 4));
Iterator<Integer> aL1Iter = aL1.iterator();
ArrayList<Integer> aL2 = new ArrayList<>();
aL2.addAll(Arrays.asList(6, 7, 8, 9, 10));
Iterator<Integer> aL2Iter = aL2.iterator();
ArrayList<Iterator<Integer>> alIterI = new ArrayList<>();
alIterI.add(aL1Iter);
alIterI.add(aL2Iter);
IterOfIterToIter<Integer> ioiti = new IterOfIterToIter<>();
Iterator<Integer> iter = ioiti.convert(alIterI.iterator());
ArrayList<Integer> tmp = new ArrayList<>();
for (int a = 0; a < 10; a++) {
tmp.add(iter.next());
}
assertEquals(tmp, tmp);
}
/**
* Тестирует hasNext().
*/
@Test
public void testHasNextTrue() {
ArrayList<Integer> aL1 = new ArrayList<>();
aL1.addAll(Arrays.asList(1, 2, 3, 4));
Iterator<Integer> aL1Iter = aL1.iterator();
ArrayList<Integer> aL2 = new ArrayList<>();
aL2.addAll(Arrays.asList(6, 7, 8, 9, 10));
Iterator<Integer> aL2Iter = aL2.iterator();
ArrayList<Iterator<Integer>> alIterI = new ArrayList<>();
alIterI.add(aL1Iter);
alIterI.add(aL2Iter);
IterOfIterToIter<Integer> ioiti = new IterOfIterToIter<>();
Iterator<Integer> iter = ioiti.convert(alIterI.iterator());
assertTrue(iter.hasNext());
}
/**
* Тестирует hasNext().
*/
@Test
public void testHasNextFalse() {
ArrayList<Integer> aL1 = new ArrayList<>();
Integer[] a1 = new Integer[0];
aL1.addAll(Arrays.asList(a1));
Iterator<Integer> aL1Iter = aL1.iterator();
ArrayList<Integer> aL2 = new ArrayList<>();
Integer[] a2 = new Integer[0];
aL2.addAll(Arrays.asList(a2));
Iterator<Integer> aL2Iter = aL2.iterator();
ArrayList<Iterator<Integer>> alIterI = new ArrayList<>();
alIterI.add(aL1Iter);
alIterI.add(aL2Iter);
IterOfIterToIter<Integer> ioiti = new IterOfIterToIter<>();
Iterator<Integer> iter = ioiti.convert(alIterI.iterator());
assertFalse(iter.hasNext());
}
/**
* Тестирует next().
*/
@Test
public void testNext() {
ArrayList<Integer> aL1 = new ArrayList<>();
aL1.addAll(Arrays.asList(1, 2, 3, 4));
Iterator<Integer> aL1Iter = aL1.iterator();
ArrayList<Integer> aL2 = new ArrayList<>();
aL2.addAll(Arrays.asList(6, 7, 8, 9, 10));
Iterator<Integer> aL2Iter = aL2.iterator();
ArrayList<Iterator<Integer>> alIterI = new ArrayList<>();
alIterI.add(aL1Iter);
alIterI.add(aL2Iter);
IterOfIterToIter<Integer> ioiti = new IterOfIterToIter<>();
Iterator<Integer> iter = ioiti.convert(alIterI.iterator());
int[] expected = new int[]{1, 2, 3, 4, 6, 7, 8, 9, 10};
ArrayList<Integer> tmp = new ArrayList<>();
while (iter.hasNext()) {
tmp.add(iter.next());
}
int[] result = tmp.stream().mapToInt(i->i).toArray();
assertArrayEquals(expected, result);
}
/**
* Тестирует next().
*/
@Test
public void testNextWithoutUsingHasNext() {
ArrayList<Integer> aL1 = new ArrayList<>();
aL1.addAll(Arrays.asList(1, 2, 3, 4));
Iterator<Integer> aL1Iter = aL1.iterator();
ArrayList<Integer> aL2 = new ArrayList<>();
aL2.addAll(Arrays.asList(6, 7, 8, 9, 10));
Iterator<Integer> aL2Iter = aL2.iterator();
ArrayList<Iterator<Integer>> alIterI = new ArrayList<>();
alIterI.add(aL1Iter);
alIterI.add(aL2Iter);
IterOfIterToIter<Integer> ioiti = new IterOfIterToIter<>();
Iterator<Integer> iter = ioiti.convert(alIterI.iterator());
int[] expected = new int[]{1, 2, 3, 4, 6, 7, 8, 9, 10};
ArrayList<Integer> tmp = new ArrayList<>();
for (int a = 0; a < expected.length; a++) {
tmp.add(iter.next());
}
int[] result = tmp.stream().mapToInt(i->i).toArray();
assertArrayEquals(expected, result);
}
}
|
package com.bs.guestbook.dao;
import com.bs.guestbook.entity.ProductPosition;
import java.sql.SQLException;
import java.util.List;
public interface ProductPositionDao {
void addProductPosition(ProductPosition productPosition) throws SQLException;
List getAllProductPositions() throws SQLException;
List getProductsByIdOrder(Integer id) throws SQLException;
void deleteProductPosition(ProductPosition productPosition) throws SQLException;
void updateProductPosition(ProductPosition productPosition) throws SQLException;
ProductPosition getProductPositionById(Integer id) throws SQLException;
List getProductsSortBy(String nameColumn) throws SQLException;
List getPageNumberList();
void setSelectedPageNumber(Integer pageNumber);
int getSelectedPageNumber();
}
|
package com.bramgussekloo.projectb.Activities.EditProduct;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import com.bramgussekloo.projectb.Activities.EditProduct.EditProduct;
import com.bramgussekloo.projectb.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
public class ChooseProduct extends AppCompatActivity {
private Button button;
private Spinner Spinner;
private FirebaseFirestore firebaseFirestore;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_product);
Spinner = findViewById(R.id.spinnerProductName);
setSpinner();
chooseProduct();
}
private void chooseProduct(){
Spinner = findViewById(R.id.spinnerProductName);
button = findViewById(R.id.ChooseProductButton);
firebaseFirestore = FirebaseFirestore.getInstance();
firebaseFirestore.collection("Products").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<String> list = new ArrayList<>();
for (QueryDocumentSnapshot document : task.getResult()) {
list.add(document.getId());
}
Log.d("QuerySnapshot", list.toString());
ArrayAdapter<String> adapter = new ArrayAdapter<>(
getBaseContext(),
android.R.layout.simple_spinner_item,
list
);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner.setAdapter(adapter);
} else {
Log.d("QuerySnapshot", "Error getting documents: ", task.getException());
}
}
});
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), EditProduct.class);
intent.putExtra("productID",Spinner.getSelectedItem().toString());
startActivity(intent);
}
});
}
private void setSpinner(){
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.placeholder, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner.setAdapter(adapter);
}
}
|
package com.androidcorpo.lindapp;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.telephony.SmsManager;
import android.widget.Toast;
import com.androidcorpo.lindapp.elipticurve.EEC;
import com.androidcorpo.lindapp.model.MyKey;
import com.androidcorpo.lindapp.network.ApiClient;
import com.androidcorpo.lindapp.network.ApiInterface;
import com.androidcorpo.lindapp.network.response.PublicKeyResponse;
import com.androidcorpo.lindapp.resources.LindAppDbHelper;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import javax.crypto.SecretKey;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class LindAppUtils {
private static void readPublicKey(final LindAppDbHelper lindAppDbHelper, final String contact, final Context context) {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<PublicKeyResponse> call = apiService.read(contact);
call.enqueue(new Callback<PublicKeyResponse>() {
@Override
public void onResponse(Call<PublicKeyResponse> call, Response<PublicKeyResponse> response) {
PublicKeyResponse keyResponse = response.body();
if (response.isSuccessful() && keyResponse.getCode() == 200) {
String responseContact = keyResponse.getContact();
String responsePublicKey = keyResponse.getPublicKey();
byte[] bytes = EEC.hexToBytes(responsePublicKey);
PublicKey publicKey = null;
try {
publicKey = LindAppUtils.deSerializePublicKey(bytes);
MyKey myKey = new MyKey(responseContact, publicKey);
lindAppDbHelper.saveKey(myKey);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(context, "Public Key save ", Toast.LENGTH_LONG).show();
} else if (keyResponse.getCode() == 404) {
Toast.makeText(context, contact + " doesn't post is Public Key ", Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<PublicKeyResponse> call, Throwable t) {
Toast.makeText(context, "Network issue try again later ", Toast.LENGTH_LONG).show();
}
});
}
public static void sendCypherMessage(final Context context, String plainText, String destiNumber) throws IOException {
LindAppDbHelper lindAppDbHelper = LindAppDbHelper.getInstance(context);
String phoneNumber = getCleanAdress(destiNumber);
String myNumber = getMyContact(context);
if (myNumber == null) {
Toast.makeText(context, myNumber, Toast.LENGTH_LONG).show();
} else {
PublicKey publicKey = lindAppDbHelper.getPublicKey(phoneNumber);
if (publicKey != null) {
sendMSG(lindAppDbHelper,phoneNumber,publicKey,plainText,context);
} else
readPublicKey(lindAppDbHelper, phoneNumber, plainText,context);
}
}
private static void readPublicKey(final LindAppDbHelper lindAppDbHelper, final String phoneNumber, final String plainText, final Context context) {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<PublicKeyResponse> call = apiService.read(phoneNumber);
call.enqueue(new Callback<PublicKeyResponse>() {
@Override
public void onResponse(Call<PublicKeyResponse> call, Response<PublicKeyResponse> response) {
PublicKeyResponse keyResponse = response.body();
if (response.isSuccessful() && keyResponse.getCode() == 200) {
String responseContact = keyResponse.getContact();
String responsePublicKey = keyResponse.getPublicKey();
byte[] bytes = EEC.hexToBytes(responsePublicKey);
PublicKey publicKey = null;
try {
publicKey = LindAppUtils.deSerializePublicKey(bytes);
MyKey myKey = new MyKey(responseContact, publicKey);
lindAppDbHelper.saveKey(myKey);
sendMSG(lindAppDbHelper,phoneNumber,publicKey,plainText,context);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(context, "Public Key save ", Toast.LENGTH_LONG).show();
} else if (keyResponse.getCode() == 404) {
Toast.makeText(context, phoneNumber + " doesn't post is Public Key ", Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<PublicKeyResponse> call, Throwable t) {
Toast.makeText(context, "Network issue try again later "+t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
private static void sendMSG(LindAppDbHelper lindAppDbHelper,String phoneNumber, PublicKey publicKey, String plainText, final Context context) throws IOException {
String myNumber = getMyContact(context);
byte[] iv = new SecureRandom().generateSeed(16);
String bytesToHex = EEC.bytesToHex(iv);
PrivateKey privateKey = lindAppDbHelper.getPrivateKey(myNumber);
SecretKey secretKey = EEC.secretKey(privateKey, publicKey);
String cypherText = EEC.crypt(secretKey, plainText, iv);
String cypherTextIV = bytesToHex + "" + cypherText;
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(context, 0, new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(context, 0, new Intent(DELIVERED), 0);
//---when the SMS has been sent---
context.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(context, "SMS sent", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(context, "Generic failure", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(context, "No service", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(context, "Null PDU", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(context, "Radio off", Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
//---when the SMS has been delivered---
context.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(context, "SMS delivered", Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(context, "SMS not delivered", Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
/*
* These two lines below actually send the message via an intent.
* The default provider does not show up and this is backward compatible to 2.3.3
*
*/
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, cypherTextIV, sentPI, deliveredPI);
}
public static String getCleanAdress(String address) {
if (address != null)
if (address.length() == 9)
return 237 + address;
else if (address.length() >= 12)
return address.substring(address.length() - 12);
return "";
}
public static String getContactName(Context context, String phoneNumber) {
ContentResolver cr = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phoneNumber));
Cursor cursor = cr.query(uri,
new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
if (cursor == null) {
return null;
}
String contactName = null;
if (cursor.moveToFirst()) {
contactName = cursor.getString(cursor
.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return contactName;
}
public static String decryptCypherText(Context context, String msg, String from) throws IOException {
String bytesToHex = msg.substring(0, 32);
String fullMsg = msg.substring(32);
byte[] iv = EEC.hexToBytes(bytesToHex);
LindAppDbHelper lindAppDbHelper = LindAppDbHelper.getInstance(context);
String phoneNumber = getCleanAdress(from);
PublicKey publicKey = lindAppDbHelper.getPublicKey(phoneNumber);
if (publicKey != null) {
String myNumber = getMyContact(context);
PrivateKey privateKey = lindAppDbHelper.getPrivateKey(myNumber);
SecretKey secretKey = EEC.secretKey(privateKey, publicKey);
assert secretKey != null;
String decrypt = EEC.decrypt(secretKey, fullMsg, iv);
return decrypt != null ? decrypt : "error decryption";
} else
readPublicKey(lindAppDbHelper, phoneNumber, context);
return "Error fetching public key try again";
}
private static String getMyContact(Context context) {
SharedPreferences pref = context.getSharedPreferences(Constant.PREFERENCE, 0); // 0 - for private mode
if (pref.contains(Constant.MY_CONTACT)) {
return pref.getString(Constant.MY_CONTACT, "");
} else return null;
}
/**
* To de-serialize a java object from database
*
* @throws IOException
* @throws ClassNotFoundException
*/
public static PrivateKey deSerializePrivateKey(byte[] buf) throws IOException {
ObjectInputStream objectIn = null;
PrivateKey privateKey = null;
if (buf != null)
objectIn = new ObjectInputStream(new ByteArrayInputStream(buf));
try {
privateKey = (PrivateKey) objectIn.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return privateKey;
}
/**
* To de-serialize a java object from database
*
* @throws IOException
* @throws ClassNotFoundException
*/
public static PublicKey deSerializePublicKey(byte[] buf) throws IOException {
ObjectInputStream objectIn = null;
PublicKey publicKey = null;
if (buf != null)
objectIn = new ObjectInputStream(new ByteArrayInputStream(buf));
try {
publicKey = (PublicKey) objectIn.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return publicKey;
}
public static byte[] privateKeyToStream(PrivateKey stu) {
// Reference for stream of bytes
byte[] stream = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(stu);
stream = baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return stream;
}
public static byte[] publicKeyToStream(PublicKey stu) {
// Reference for stream of bytes
byte[] stream = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(stu);
stream = baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return stream;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.