text
stringlengths 10
2.72M
|
|---|
package com.jt;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.File;
@Configuration
public class CommonConfiguration {
@Bean
public EmbeddedServletContainerFactory embeddedServletContainerFactory() {
ConfigurableEmbeddedServletContainer factory = new TomcatEmbeddedServletContainerFactory();
factory.setDocumentRoot
(new File("D:\\tarena\\IdeaWorkSpace\\git\\JT\\1805-manage\\src\\main\\webapp\\"));
return (EmbeddedServletContainerFactory) factory;
}
}
|
package System;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Random;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import Sul.*;
//import Gacha_Panel;
public class Main_Panel extends JPanel{
Random random=new Random();
Deck d;
Main m;
//Deck d;
//Gacha g;
ImageIcon push = new ImageIcon("src/Image/역따봉1.png");
Image puush = push.getImage();
ImageIcon ga = new ImageIcon("src/Image/버튼300,100.png");
Image gaa=ga.getImage();
JLabel feed = new JLabel("먹이기");
JLabel warning=new JLabel("덱이 비어있습니다...");
JLabel deck = new JLabel("덱");
JLabel Gacha = new JLabel("뽑기");
JLabel send = new JLabel(push);
MouseAdapter changetoGacha;
MouseAdapter changetoDeck;
MouseAdapter changetofeed;
MouseAdapter send_message;
MouseAdapter warning_label;
ImageIcon background = new ImageIcon("src/Image/main_background.png");
Image back=background.getImage();
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(back, 0, 0, getWidth(), getHeight(), this);
g.drawImage(main_image, 50, 0, 710, 710, this);
Color c=new Color(0,0,0,150);
g.setColor(c);
g.fillRect(820, 110, 300, 100);
g.fillRect(820, 310, 300, 100);
g.fillRect(820, 510, 300, 100);
}
//JLabel gacha_image;
public void gacha (Deck deck) {
int ran_num=random.nextInt(320);
//System.out.println(ran_num);
if(ran_num<80) {
//For Apple
if(ran_num<41) { deck.my_sul_list.add(new Sul_Apple(1));}
if(ran_num>=41 && ran_num<66){deck.my_sul_list.add(new Sul_Apple(2));}
if(ran_num>=66 && ran_num<75){deck.my_sul_list.add(new Sul_Apple(3));}
if(ran_num==76){deck.my_sul_list.add(new Sul_Apple(4));}
if(ran_num>=77 && ran_num<80){deck.my_sul_list.add(new Sul_Apple(5));}
}else if(ran_num<160) {
//For Beer
if(ran_num<121) {deck.my_sul_list.add(new Sul_Beer(1));}
if(ran_num>=121 && ran_num<146){deck.my_sul_list.add(new Sul_Beer(2));}
if(ran_num>=146 && ran_num<155){deck.my_sul_list.add(new Sul_Beer(3));}
if(ran_num==156){deck.my_sul_list.add(new Sul_Beer(4));}
if(ran_num>=157 && ran_num<160){deck.my_sul_list.add(new Sul_Beer(5));}
}else if(ran_num<240) {
//For fresh
if(ran_num<201) {deck.my_sul_list.add(new Sul_Fresh(1));}
if(ran_num>=201 && ran_num<226){deck.my_sul_list.add(new Sul_Fresh(2));}
if(ran_num>=226 && ran_num<235){deck.my_sul_list.add(new Sul_Fresh(3));}
if(ran_num==236){deck.my_sul_list.add(new Sul_Fresh(4));}
if(ran_num>=237 && ran_num<240){deck.my_sul_list.add(new Sul_Fresh(5));}
}else if(ran_num<320) {
//For wine
if(ran_num<281) {deck.my_sul_list.add(new Sul_Wine(1));}
if(ran_num>=281 && ran_num<306){deck.my_sul_list.add(new Sul_Wine(2));}
if(ran_num>=306 && ran_num<315){deck.my_sul_list.add(new Sul_Wine(3));}
if(ran_num==316){deck.my_sul_list.add(new Sul_Wine(4));}
if(ran_num>=317 && ran_num<320){deck.my_sul_list.add(new Sul_Wine(5));}
}
//for (int i=0;i<deck.my_sul_list.size();i++) {
// System.out.println(deck.my_sul_list.get(i).name);
//}
//System.out.print("\n");
deck.current_sul=deck.my_sul_list.get(deck.my_sul_list.size()-1);
//gacha_image=new JLabel(deck.my_sul_list.get(deck.my_sul_list.size()-1).icon1);
//gacha_image.setLocation(300, 100);
//gacha_image.setSize(700, 700);
//gacha_image.setVerticalAlignment(SwingConstants.TOP);
//gacha_image.setHorizontalAlignment(SwingConstants.CENTER);
}
Image main_image;
Main_Panel(Deck d, Main m){
this.m = m;
Color c1=new Color(255,212, 001);
Color c2=new Color(255, 255, 255, 200);
setLayout(null);
feed.setLocation(820, 110);
feed.setSize(300, 100);
feed.setFont(new Font("DX시인과나",Font.BOLD,50));
feed.setBorder(new TitledBorder(new LineBorder(c1,5)));
feed.setForeground(c2);
feed.setHorizontalAlignment(SwingConstants.CENTER);
add(feed);
deck.setLocation(820, 310);
deck.setSize(300, 100);
deck.setFont(new Font("DX시인과나",Font.BOLD,50));
deck.setForeground(c2);
deck.setBorder(new TitledBorder(new LineBorder(c1,5)));
deck.setHorizontalAlignment(SwingConstants.CENTER);
add(deck);
Gacha.setLocation(820, 510);
Gacha.setSize(300, 100);
Gacha.setFont(new Font("DX시인과나",Font.BOLD,50));
Gacha.setForeground(c2);
Gacha.setBorder(new TitledBorder(new LineBorder(c1,5)));
Gacha.setHorizontalAlignment(SwingConstants.CENTER);
add(Gacha);
send.setLocation(10, 630);
send.setSize(50, 50);
add(send);
warning.setSize(700,100);
warning.setLocation(100,510);
warning.setHorizontalAlignment(SwingConstants.CENTER);
warning.setOpaque(true);
warning.setFont(new Font("DX시인과나",Font.BOLD,50));
Color c=new Color(0,0,0,150);
warning.setForeground(Color.white);
warning.setBackground(c);
warning.setVisible(false);
warning.setEnabled(false);
add(warning);
changetoGacha=new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
super.mouseClicked(e);
m.gacha_panel.count_and_reset();
m.gacha_panel.cnt++;
//System.out.println(m.gacha_panel.cnt);
if (m.gacha_panel.cnt>10) {
m.change("End");
}
else {
gacha(d);
m.gacha_panel.changeimage(d.my_sul_list);
m.change("Gacha");
}
}
};
changetoDeck=new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
super.mouseClicked(e);
m.change("deck");
}
};
changetofeed=new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
if(!void_check(d)) {
m.threadStart();
m.change("game");
} else {
warning.setVisible(true);
warning.setEnabled(true);
}
}
};
send_message=new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
String message = JOptionPane.showInputDialog("개발자에게 평가를 보내주세요.");
if (message!=null) {
// 소켓전송
User u = new User(message);
//System.out.print("Qodor");
u.run();
JOptionPane.showMessageDialog(null, "더 좋은 서비스로 찾아뵙겠습니다.");
}
}
};
warning_label=new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
warning.setVisible(false);
warning.setEnabled(false);
}
};
deck.addMouseListener(changetoDeck);
Gacha.addMouseListener(changetoGacha);
send.addMouseListener(send_message);
feed.addMouseListener(changetofeed);
warning.addMouseListener(warning_label);
this.setFocusable(true);
}
/*
class send_message implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String message = JOptionPane.showInputDialog("개발자에게 평가를 보내주세요.");
if (message!=null) {
// 소켓전송
User u = new User(message);
//System.out.print("Qodor");
u.run();
JOptionPane.showMessageDialog(null, "더 좋은 서비스로 찾아뵙겠습니다.");
}
}
}
*/
public void changemain(ArrayList<Sul_Base> sul, Deck deck) {
main_image = deck.first_sul.icon2.getImage();
repaint();
}
public boolean void_check(Deck deck) {
if(deck.first_sul.name=="None"&&
deck.second_sul.name=="None"&&
deck.third_sul.name=="None"&&
deck.fourth_sul.name=="None") {
return true;
}
else return false;
}
}
|
package com.egova.baselibrary.util;
import java.math.BigDecimal;
public class CalKit {
public static final int defaultScale = 2;
/**
* 两个数相加,四舍五入保留2位小数
*
* @param sum1
* @param sum2
* @return
*/
public static BigDecimal add(String sum1, String sum2) {
return add(sum1, sum2, defaultScale);
}
public static BigDecimal add(String sum1, String sum2, int scale) {
BigDecimal b1 = new BigDecimal(sum1);
BigDecimal b2 = new BigDecimal(sum2);
return b1.add(b2).setScale(scale, BigDecimal.ROUND_HALF_UP);//四舍五入
}
/**
* 两个数相减,四舍五入保留2位小数
*
* @param sum1
* @param sum2
* @return
*/
public static BigDecimal subtract(String sum1, String sum2) {
return subtract(sum1, sum2, defaultScale);//四舍五入
}
public static BigDecimal subtract(String sum1, String sum2, int scale) {
BigDecimal b1 = new BigDecimal(sum1);
BigDecimal b2 = new BigDecimal(sum2);
return b1.subtract(b2).setScale(scale, BigDecimal.ROUND_HALF_UP);//四舍五入
}
/**
* 两个数相乘,四舍五入保留2位小数
*
* @param sum1
* @param sum2
* @return
*/
public static BigDecimal multiply(String sum1, String sum2) {
return multiply(sum1, sum2, defaultScale);
}
public static BigDecimal multiply(String sum1, String sum2, int scale) {
BigDecimal b1 = new BigDecimal(sum1);
BigDecimal b2 = new BigDecimal(sum2);
return b1.multiply(b2).setScale(scale, BigDecimal.ROUND_HALF_UP);//四舍五入
}
/**
* 两个数相除,除数如果为0,则返回0,,四舍五入保留2位小数
*
* @param sum1
* @param sum2
* @return
*/
public static BigDecimal divide(String sum1, String sum2) {
return divide(sum1, sum2, defaultScale);//四舍五入
}
public static BigDecimal divide(String sum1, String sum2, int scale) {
BigDecimal zero = new BigDecimal("0");
BigDecimal b1 = new BigDecimal(sum1);
BigDecimal b2 = new BigDecimal(sum2);
if (b2.compareTo(zero) == 0) {
//如果除数为0,则直接返回0
return zero;
}
return b1.divide(b2).setScale(scale, BigDecimal.ROUND_HALF_UP);//四舍五入
}
}
|
package com.fanfte.algorithm.recursive;
import java.util.ArrayList;
import java.util.List;
public class RestoreIpAddresses {
public static List<String> restoreIpAddresses(String s) {
List<String> res = new ArrayList<>();
if(s == null || s.length() < 4 || s.length() > 12) {
return res;
}
doRestore(res, "", s, 0);
return res;
}
private static void doRestore(List<String> result, String path, String s, int k) {
if(s.isEmpty() || k ==4) {
if(s.isEmpty() && k ==4) {
result.add(path.substring(1));
}
return ;
}
for(int i = 1;i <= (s.charAt(0) == '0' ? 1 : 3) && i <= s.length();i++) {
String part = s.substring(0, i);
if(Integer.valueOf(part) <= 255) {
doRestore(result, path + "." + part, s.substring(i), k + 1);
}
}
}
public static void main(String[] args) {
List<String> strings = restoreIpAddresses("25525511135");
System.out.println(strings);
}
}
|
package net.sduhsd.royr6099.unit11.labassesment;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class ComponentSet {
private List<Component> components;
private void init() {
components = new ArrayList<Component>();
}
public ComponentSet() {
init();
}
public ComponentSet(List<Component> csList) {
components = csList;
}
public ComponentSet(Component[] csArray) {
components = Arrays.asList(csArray);
}
public ComponentSet(String csString) {
setComponents(csString);
}
/**
* Fills the internal {@link}ArrayList of {@link}Component objects from a {@link} String
* @param csString - In the format "name weight cost\nname weight cost\n ..."
*/
public void setComponents(String csString) {
init();
Scanner csScan = new Scanner(csString);
while (csScan.hasNextLine()) {
String name = csScan.next();
double weight = csScan.nextDouble();
double cost = csScan.nextDouble();
components.add(new Component(name, weight, cost));
csScan.nextLine();
}
csScan.close();
}
public void setComponent(int index, String comp) {
Scanner cScan = new Scanner(comp);
String name = cScan.next();
double weight = cScan.nextDouble();
double cost = cScan.nextDouble();
setComponent(index, new Component(name, weight, cost));
cScan.close();
}
public void setComponent(int index, Component comp) {
while (index >= components.size()) {
components.add(null);
}
components.set(index, comp);
}
public void removeComponent(int index) {
components.remove(index);
}
public Component getComponent(int index) {
return components.get(index);
}
public Component getMostExpensive() {
return Collections.max(components);
}
public Component getLeastExpensive() {
return Collections.min(components);
}
public double getTotalCost() {
double total = 0;
for (Component c : components) {
total += c.getCost();
}
return total;
}
public double getTotalWeight() {
double total = 0;
for (Component c : components) {
total += c.getWeight();
}
return total;
}
public void sort() {
Collections.sort(components);
}
public String toString() {
String ret = "";
for (Component c : components) {
ret += c + "\n";
}
return ret;
}
}
|
package com.fixit.core.utils;
import java.util.ArrayList;
import java.util.List;
import com.fixit.core.data.WorkingDay;
import com.fixit.core.data.WorkingHours;
import com.fixit.core.data.mongo.Tradesman;
/**
* @author Kostyantin
* @createdAt 2017/04/15 16:51:58 GMT+3
*/
public class TestUtils {
public static List<Tradesman> createDummyTradesmen(int count) {
List<Tradesman> tradesmen = new ArrayList<>();
for(int i = 0; i < count; i++) {
tradesmen.add(createDummyTradesman());
}
return tradesmen;
}
public static Tradesman createDummyTradesman() {
Tradesman tradesman = new Tradesman();
// tradesman.setProfessionId(1);
tradesman.setContactName("Bob Test");
tradesman.setCompanyName("Bob's Test Plumbers");
tradesman.setEmail("kostya2216@gmail.com");
tradesman.setTelephone("0502835431");
tradesman.setPassword("123456");
tradesman.setLogoUrl("https://thelogocompany.net/wp-content/uploads/2016/10/main_calltheplumber.jpg");
tradesman.setWorkingDays(createWorkingDays());
return tradesman;
}
public static WorkingDay[] createWorkingDays() {
WorkingDay[] wokringDays = new WorkingDay[5];
for(int i = 0; i < 5; i++) {
wokringDays[i] = new WorkingDay(i + 1, createWorkingHours());
}
return wokringDays;
}
public static WorkingHours[] createWorkingHours() {
return new WorkingHours[] {
new WorkingHours(9.30, 13.0),
new WorkingHours(15.00, 21.30)
};
}
}
|
package com.jgw.supercodeplatform.trace.service.dynamic;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.jgw.supercodeplatform.exception.SuperCodeException;
import com.jgw.supercodeplatform.trace.aware.TraceApplicationContextAware;
import com.jgw.supercodeplatform.trace.common.cache.FunctionFieldCache;
import com.jgw.supercodeplatform.trace.common.model.NodeOrFunFields;
import com.jgw.supercodeplatform.trace.common.model.RestResult;
import com.jgw.supercodeplatform.trace.constants.ObjectTypeEnum;
import com.jgw.supercodeplatform.trace.dao.DynamicBaseMapper;
import com.jgw.supercodeplatform.trace.dto.dynamictable.common.AddBusinessDataModel;
import com.jgw.supercodeplatform.trace.dto.dynamictable.common.DynamicHideParam;
import com.jgw.supercodeplatform.trace.dto.dynamictable.common.FieldBusinessParam;
import com.jgw.supercodeplatform.trace.dto.dynamictable.common.LineBusinessData;
import com.jgw.supercodeplatform.trace.exception.SuperCodeTraceException;
import com.jgw.supercodeplatform.trace.pojo.TraceFunFieldConfig;
import com.jgw.supercodeplatform.trace.pojo.tracebatch.TraceBatchInfo;
import com.jgw.supercodeplatform.trace.service.template.TraceFunFieldConfigService;
import com.jgw.supercodeplatform.trace.service.tracebatch.TraceBatchInfoService;
@Component
public class DynamicServiceDelegate {
@Autowired
private TraceBatchInfoService traceBatchInfoService;
@Autowired
private TraceFunFieldConfigService traceFunFieldConfigService;
@Autowired
private TraceApplicationContextAware applicationAware;
@Autowired
private FunctionFieldCache functionFieldManageService;
public RestResult<List<String>> delete(String functionId,List<Long> ids,String traceTemplateId) throws Exception {
RestResult<List<String>> restResult =new RestResult<List<String>>();
StringBuilder sqlFieldValueBuilder = new StringBuilder();
if (null==ids || ids.isEmpty()) {
throw new SuperCodeTraceException("主键id必传", 500);
}
deleteInSqlBuilder(ids, sqlFieldValueBuilder);
String tableName = traceFunFieldConfigService.getEnTableNameByFunctionId(functionId);
if (StringUtils.isBlank(tableName)) {
throw new SuperCodeTraceException("删除节点功能数据时无法根据功能id:"+functionId+"获取到表名", 500);
}
String delete_sql = "delete from " + tableName + sqlFieldValueBuilder.toString();
String query_sql = "select TraceBatchInfoId from " + tableName + sqlFieldValueBuilder.toString();
DynamicBaseMapper dao=applicationAware.getDynamicMapperByFunctionId(traceTemplateId,functionId);
List<LinkedHashMap<String, Object>> data=dao.select(query_sql);
if (null==data || data.isEmpty()) {
throw new SuperCodeTraceException("不存在此记录", 500);
}
dao.delete(delete_sql);
if(data.get(0)!=null){
String traceBatchInfoId=(String) data.get(0).get("TraceBatchInfoId");
TraceBatchInfo traceBatchInfo=traceBatchInfoService.selectByTraceBatchInfoId(traceBatchInfoId);
if (null!=traceBatchInfo) {
traceBatchInfo.setNodeDataCount((traceBatchInfo.getNodeDataCount()==null?0:traceBatchInfo.getNodeDataCount())-ids.size());
traceBatchInfoService.updateTraceBatchInfo(traceBatchInfo);
}
}
restResult.setState(200);
restResult.setMsg("删除成功");
return restResult;
}
private void deleteInSqlBuilder(List<Long> ids,StringBuilder sqlFieldValueBuilder) throws SuperCodeTraceException {
if (null == ids || ids.isEmpty()) {
throw new SuperCodeTraceException("删除数据,参数id必须传", 500);
}
int i = 0;
sqlFieldValueBuilder.append(" where Id in (");
for (Long id : ids) {
sqlFieldValueBuilder.append(id);
i++;
if (i<ids.size()) {
sqlFieldValueBuilder.append(",");
}
}
sqlFieldValueBuilder.append(")");
}
/**
* 新增和修改时参数校验,一定会获取模板id
* @param param
* @param autoNode
* @param traceTemplateId
* @param functionId
* @return
* @throws SuperCodeTraceException
*/
public AddBusinessDataModel addMethodSqlBuilderParamValidate(String functionId,LineBusinessData lineBusinessData,boolean isNode,String traceBatchInfoId,String traceTemplateId) throws SuperCodeTraceException {
RestResult<String> restResult=new RestResult<String>();
restResult.setState(200);
AddBusinessDataModel adDataModel=new AddBusinessDataModel();
try {
if (StringUtils.isBlank(functionId)) {
throw new SuperCodeTraceException("功能id不能为空", 500);
}
if (null==lineBusinessData || null==lineBusinessData.getFields() || lineBusinessData.getFields().isEmpty()) {
throw new SuperCodeTraceException("data不能为空", 500);
}
adDataModel.setFunctionId(functionId);
adDataModel.setLineData(lineBusinessData);
//如果是新增节点业务数据则必须是带批次信息的
if (isNode) {
if (StringUtils.isBlank(traceBatchInfoId)) {
throw new SuperCodeTraceException("节点新增数据,traceBatchInfoId 不能为空", 500);
}
if (StringUtils.isBlank(traceTemplateId)) {
throw new SuperCodeTraceException("节点新增数据,traceTemplateId 不能为空", 500);
}
adDataModel.setTraceBatchInfoId(traceBatchInfoId);
adDataModel.setTraceTemplateId(traceTemplateId);
}else {
//如果新增的是定制功能则在数据里查找批次信息
List<FieldBusinessParam> fields=lineBusinessData.getFields();
for (FieldBusinessParam fieldParam : fields) {
Integer objectType=fieldParam.getObjectType();
if (null!=objectType) {
ObjectTypeEnum objectTypeEnum=ObjectTypeEnum.getType(objectType);
if(objectTypeEnum!=null){
switch (objectTypeEnum) {
case TRACE_BATCH:
case MassifBatch:
case PlantingBatch:
//如果不是自动节点的插入修改则必须传模板id
//如果是自动节点则新增时无模板id但必须有批次号
adDataModel.setTraceBatchInfoId(fieldParam.getObjectUniqueValue());
break;
default:
break;
}
}
}
}
//if (StringUtils.isBlank(adDataModel.getTraceBatchInfoId())) {
List<FieldBusinessParam> batchParams= fields.stream().filter(e->e.getFieldCode().equals("TraceBatchInfoId")).collect(Collectors.toList());
if(CollectionUtils.isNotEmpty(batchParams)){
String batchInfoId= batchParams.get(0).getFieldValue();
if(StringUtils.isEmpty(batchInfoId)){
//throw new SuperCodeTraceException("生产管理新增数据无法获取到批次唯一id", 500);
}else {
adDataModel.setTraceBatchInfoId(batchInfoId);
}
}
//}
}
} catch (Exception e) {
e.printStackTrace();
throw new SuperCodeTraceException("解析data失败:" + e.getMessage(), 500);
}
return adDataModel;
}
/**
* 返回值只对新增有效
* @param lineBusinessData
* @param operateType
* @param sqlFieldNameBuilder
* @param sqlFieldValueBuilder
* @param isNode
* @return
* @throws SuperCodeTraceException
* @throws SuperCodeException
*/
public boolean funAddOrUpdateSqlBuilder(LineBusinessData lineBusinessData, int operateType,StringBuilder sqlFieldNameBuilder,StringBuilder sqlFieldValueBuilder,boolean isNode) throws SuperCodeTraceException, SuperCodeException {
List<FieldBusinessParam> fieldBusinessList=lineBusinessData.getFields();
FieldBusinessParam batchField= getObjectParam(fieldBusinessList,"TraceBatchInfoId");
String traceBatchInfoId=null;
if(batchField!=null){
traceBatchInfoId= batchField.getFieldValue();
}
boolean containObj=false;
for (FieldBusinessParam fieldBusinessParam : fieldBusinessList) {
switch (operateType) {
case 1: // 表示新增数据操作
boolean flag=caseAdd(sqlFieldNameBuilder, sqlFieldValueBuilder, fieldBusinessParam,isNode,traceBatchInfoId);
if (flag) {
containObj=true;
}
break;
case 3: // 表示修改数据操作
caseUpdate(sqlFieldNameBuilder,sqlFieldValueBuilder, fieldBusinessParam);
break;
default:
break;
}
}
return containObj;
}
private FieldBusinessParam getObjectParam(List<FieldBusinessParam> fields,String fieldCode)
{
List<FieldBusinessParam> params= fields.stream().filter(e->e.getFieldCode().equals(fieldCode)).collect(Collectors.toList());
FieldBusinessParam param=null;
if(params!=null&¶ms.size()>0){
param=params.get(0);
}
return param;
}
/**
*
* @param sqlFieldNameBuilder
* @param sqlFieldValueBuilder
* @param isNode
* @param lineNode
* @param fieldCode
* @param fieldType:插入不会传动态表主键id所以fieldType不会有为空的情况
* @return
* @throws SuperCodeTraceException
*/
private boolean caseAdd(StringBuilder sqlFieldNameBuilder, StringBuilder sqlFieldValueBuilder, FieldBusinessParam fieldBusinessParam, boolean isNode,String traceBatchInfoId) throws SuperCodeTraceException {
String fieldCode = fieldBusinessParam.getFieldCode();
// 剩下的类型都可以当字符处理包括时间
String fieldValue = fieldBusinessParam.getFieldValue();
boolean containObj=false;
if (StringUtils.isNotBlank(fieldValue) && !"null".equalsIgnoreCase(fieldValue) && sqlFieldNameBuilder.toString().indexOf(fieldCode)<0) {
sqlFieldNameBuilder.append(fieldCode).append(",");
sqlFieldValueBuilder.append("'").append(fieldValue).append("'").append(",");
Integer objectType=fieldBusinessParam.getObjectType();
if (null!=objectType) {
containObj=true;
ObjectTypeEnum objectTypeEnum=ObjectTypeEnum.getType(objectType);
switch (objectTypeEnum) {
//新增数据设置批次id时只有定制功能才需要在字段数据里找,节点数据新增有单独的字段接收批次唯一id
case TRACE_BATCH:
case PlantingBatch:
if (!isNode) {
if(sqlFieldNameBuilder.toString().indexOf("TraceBatchInfoId")<0 && StringUtils.isEmpty(traceBatchInfoId)){
sqlFieldNameBuilder.append(objectTypeEnum.getFieldCode()).append(",");
sqlFieldValueBuilder.append("'").append(fieldBusinessParam.getObjectUniqueValue()).append("'").append(",");
}
}
break;
case PRODUCT:
sqlFieldNameBuilder.append(objectTypeEnum.getFieldCode()).append(",");
sqlFieldValueBuilder.append("'").append(fieldBusinessParam.getObjectUniqueValue()).append("'").append(",");
break;
case USER:
if(sqlFieldNameBuilder.indexOf("UserId")<0){
sqlFieldNameBuilder.append(objectTypeEnum.getFieldCode()).append(",");
sqlFieldValueBuilder.append("'").append(fieldBusinessParam.getObjectUniqueValue()).append("'").append(",");
}
break;
default:
break;
}
}
}
return containObj;
}
/**
*
* @param sqlFieldNameBuilder
* @param sqlFieldValueBuilder
* @param sqlFieldValueBuilder
* @param lineNode
* @param fieldCode
* @param fieldType:更新不会更新id所以fieldType不会有为空的情况
* @throws SuperCodeTraceException
*/
private void caseUpdate(StringBuilder sqlFieldNameBuilder,StringBuilder sqlFieldValueBuilder, FieldBusinessParam fieldBusinessParam) throws SuperCodeTraceException {
// 剩下的类型都可以当字符处理包括时间
String fieldValue = fieldBusinessParam.getFieldValue();
String fieldCode = fieldBusinessParam.getFieldCode();
if (StringUtils.isNotBlank(fieldValue) && !"null".equalsIgnoreCase(fieldValue)) {
if ("Id".equals(fieldCode)) {
sqlFieldValueBuilder.append(" where Id=").append(fieldValue);
}else {
sqlFieldNameBuilder.append(fieldCode).append("=").append("'").append(fieldValue).append("'")
.append(",");
Integer objectType=fieldBusinessParam.getObjectType();
if (null!=objectType) {
ObjectTypeEnum objectTypeEnum=ObjectTypeEnum.getType(objectType);
switch (objectTypeEnum) {
case TRACE_BATCH:
String traceBatchInfoId=fieldBusinessParam.getObjectUniqueValue();
//修改时,如果没有修改对象字段,前端不会传对象类型的ObjectUniqueValue值
if (StringUtils.isNotBlank(traceBatchInfoId)) {
sqlFieldNameBuilder.append(objectTypeEnum.getFieldCode()).append("=").append("'").append(traceBatchInfoId).append("'")
.append(",");
}
break;
case PRODUCT:
String productId=fieldBusinessParam.getObjectUniqueValue();
if (StringUtils.isNotBlank(productId)) {
sqlFieldNameBuilder.append(objectTypeEnum.getFieldCode()).append("=").append("'").append(productId).append("'")
.append(",");
}
break;
case USER:
String userId=fieldBusinessParam.getObjectUniqueValue();
if (StringUtils.isNotBlank(userId)) {
sqlFieldNameBuilder.append(objectTypeEnum.getFieldCode()).append("=").append("'").append(userId).append("'")
.append(",");
}
break;
default:
break;
}
}
}
}
}
/**
* 隐藏节点业务数据
* @param param
* @return
* @throws SuperCodeTraceException
*/
public RestResult<String> hide(DynamicHideParam param) throws SuperCodeTraceException {
RestResult<String> restResult =new RestResult<String>();
StringBuilder sqlFieldValueBuilder = new StringBuilder();
String functionId = param.getFunctionId();
String tableName = traceFunFieldConfigService.getEnTableNameByFunctionId(functionId);
if (StringUtils.isBlank(tableName)) {
throw new SuperCodeTraceException("删除节点功能数据时无法根据功能id:"+functionId+"获取到表名", 500);
}
deleteInSqlBuilder(param.getIds(), sqlFieldValueBuilder);
String sql = "update " + tableName + " set DeleteStatus= "+param.getDeleteStatus()+sqlFieldValueBuilder.toString();
DynamicBaseMapper dao=applicationAware.getDynamicMapperByFunctionId(param.getTraceTemplateId(),functionId);
dao.update(sql);
restResult.setState(200);
restResult.setMsg("删除成功");
return restResult;
}
/**
* 拼装查询时返回的字段信息
* @param functionId
* @param isNode
* @param traceTemplateId
* @return
* @throws SuperCodeTraceException
*/
public NodeOrFunFields selectFields(String functionId, boolean isNode, String traceTemplateId)
throws SuperCodeTraceException {
Map<String, TraceFunFieldConfig> fieldsMap =null;
if (isNode) {
if (StringUtils.isBlank(traceTemplateId)) {
throw new SuperCodeTraceException("节点业务数据查询必须传模板id", 500);
}
fieldsMap = functionFieldManageService.getFunctionIdFields(traceTemplateId,functionId,2);
} else {
fieldsMap = functionFieldManageService.getFunctionIdFields(null,functionId,1);
}
if (null == fieldsMap || fieldsMap.isEmpty()) {
throw new SuperCodeTraceException("无此功能字段", 500);
}
// 返回的字段已经过fieldWeight排序
StringBuilder fieldNameBuilder = new StringBuilder();
NodeOrFunFields noFields=new NodeOrFunFields();
for (String key : fieldsMap.keySet()) {
TraceFunFieldConfig fieldConfig=fieldsMap.get(key);
if (null!=fieldConfig) {
String fieldType=fieldConfig.getFieldType();
if ("8".equals(fieldType)) {
fieldNameBuilder.append("DATE_FORMAT("+key+",'%Y-%m-%d %H:%i:%S')");
}else if(fieldType.startsWith("13")) {
noFields.setContainObj(true);
}
}
fieldNameBuilder.append(key).append(",");
}
String fields = fieldNameBuilder.substring(0, fieldNameBuilder.length() - 1);
noFields.setFields(fields);
return noFields;
}
/**
* 拼装查询时返回的字段信息
* @param functionId
* @param isNode
* @param traceTemplateId
* @return
* @throws SuperCodeTraceException
*/
public NodeOrFunFields selectFields(Map<String, TraceFunFieldConfig> fieldsMap)
throws SuperCodeTraceException {
if (null == fieldsMap || fieldsMap.isEmpty()) {
throw new SuperCodeTraceException("无此功能字段", 500);
}
NodeOrFunFields noFields=new NodeOrFunFields();
// 返回的字段已经过fieldWeight排序
StringBuilder fieldNameBuilder = new StringBuilder();
for (String key : fieldsMap.keySet()) {
TraceFunFieldConfig fieldConfig=fieldsMap.get(key);
if (null!=fieldConfig) {
String fieldType=fieldConfig.getFieldType();
if ("8".equals(fieldType)) {
fieldNameBuilder.append("DATE_FORMAT("+key+",'%Y-%m-%d %H:%i:%S')");
}else if(fieldType.startsWith("13")) {
noFields.setContainObj(true);
}
}
fieldNameBuilder.append(key).append(",");
}
String fields = fieldNameBuilder.substring(0, fieldNameBuilder.length() - 1);
noFields.setFields(fields);
return noFields;
}
}
|
package com.navarromugas.models;
import java.awt.*;
public class Mosca {
public static final int MAX_LONGITUD_DEL_PASO = 10;
public static final int MAX_COORDENADA_Y_DE_UBICACION = 640;
public static final int MAX_COORDENADA_X_DE_UBICACION = 480;
private Color color;
private int x;
private int y;
private int pasos;
public Mosca(Color color) {
y = (int) Math.random() * MAX_COORDENADA_X_DE_UBICACION;
x = (int) Math.random() * MAX_COORDENADA_Y_DE_UBICACION;
this.color = color;
}
public void dibujar(Graphics g) {
g.setColor(color);
g.fillRect(x, y, 5, 5);
g.fillOval(x+3, y-7, 8, 8);
g.fillOval(x-7, y-7, 8, 8);
}
public void calcularEstadoSiguiente() {
pasos = ((int) (Math.random() * MAX_LONGITUD_DEL_PASO + 1));
x = calcularCoordenada(x, MAX_COORDENADA_X_DE_UBICACION);
y = calcularCoordenada(y, MAX_COORDENADA_Y_DE_UBICACION);
}
private int calcularCoordenada(int x, int maxCoordenadaPermitida) {
return (x > maxCoordenadaPermitida || x < 0) ? (int) Math.random() * maxCoordenadaPermitida : x + pasos * (int) Math.pow(-1.0, (double) ((int) (Math.random() * 2) + 1));
}
}
|
package com.hl.service.impl;
import com.hl.document.UserObjectDocument;
import com.hl.repository.UserObjectDocumentRepository;
import com.hl.service.UserObjectEsSearchService;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@Service
@Log4j2
public class UserObjectEsSearchServiceImpl extends BaseSearchServiceImpl<UserObjectDocument> implements UserObjectEsSearchService {
@Resource
private UserObjectDocumentRepository userObjectDocumentRepository;
@Override
public void save(UserObjectDocument... userObjectDocuments) {
}
@Override
public void delete(String id) {
}
@Override
public void deleteAll() {
}
@Override
public UserObjectDocument getById(String id) {
return userObjectDocumentRepository.findById(id).orElse(null);
}
@Override
public List<UserObjectDocument> getAll() {
List<UserObjectDocument> list = new ArrayList<>();
userObjectDocumentRepository.findAll().forEach(list::add);
return list;
}
@Override
public List<UserObjectDocument> getByCode(String code) {
return userObjectDocumentRepository.findUserObjectDocumentByCodeOrderByCtimeDesc(code);
}
}
|
package tech.icey.ds;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import tech.icey.basic.ListUtil;
import java.util.*;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
public class BPlusTreeTest {
static List<String> getFixedKeySequence() {
return List.of("17", "1", "15", "2", "12", "16", "19",
"18", "5", "6", "13", "14", "8", "7", "11",
"3", "9", "4", "20", "10");
}
static List<String> getFixedValueSequence() {
return List.of("心中想的就是她", "任凭梦里三千落花", "走遍天涯心随你起落", "看惯了长风", "吹动你英勇的头发",
"我心中想得还是她", "哭也欢乐", "悲也潇洒", "只是我的心一直在问", "用什么",
"把你永久留下", "莫笑旧衣衫旧长剑走过天涯", "且看风为屏草为席天地为家",
"意气刀之尖血之涯划过春夏", "把酒一生笑一生醉一世为侠", "轰烈流沙枕上白发杯中酒比划",
"年少风雅鲜衣怒马也不过一刹那", "难免疏漏儿时檐下莫测变化", "隔却山海", "转身从容煎茶");
}
static List<String> getFixedDeletionSequence() {
return List.of("17", "15", "16", "19", "18", "5", "6", "13",
"14", "8", "7", "11", "3", "9", "4", "20", "10",
"1", "2", "12");
}
static List<String> getRandomKeySequence(int size) {
var ret = new ArrayList<String>();
for (var i = 0; i < size; i++) {
ret.add(Integer.toString(i));
}
Collections.shuffle(ret);
return ret;
}
static List<String> getRandomValueSequence(int size) {
var ret = new ArrayList<String>();
var rand1 = getRandomKeySequence(size);
var rand2 = getRandomKeySequence(size);
for (int i = 0; i < rand1.size(); i++) {
ret.add(rand1.get(i) + rand2.get(i));
}
return ret;
}
@Test
void happyTestDegree3() {
testSimpleInsertDelete(3, getFixedKeySequence(), getFixedDeletionSequence(), getFixedDeletionSequence());
}
@Test
void happyTestDegree4() {
testSimpleInsertDelete(4, getFixedKeySequence(), getFixedDeletionSequence(), getFixedDeletionSequence());
}
@Test
void happyTestDegree5() {
testSimpleInsertDelete(5, getFixedKeySequence(), getFixedDeletionSequence(), getFixedDeletionSequence());
}
@Test
void thousandElementDegree3() {
testSimpleInsertDelete(3, getRandomKeySequence(1024), getRandomValueSequence(1024),
getRandomKeySequence(1024));
}
@Test
void thousandElementDegree4() {
testSimpleInsertDelete(4, getRandomKeySequence(1024), getRandomValueSequence(1024),
getRandomKeySequence(1024));
}
@Test
void thousandElementDegree20() {
testSimpleInsertDelete(20, getRandomKeySequence(1024), getRandomValueSequence(1024),
getRandomKeySequence(1024));
}
@Test
void insertDeleteMixTestSimple() {
mixInsertAndDelete(3, 20, 3);
}
@Test
void insertDeleteMixDegree3() {
mixInsertAndDelete(3, 1000, 50);
}
@Test
void insertDeleteMixDegree4() {
mixInsertAndDelete(4, 1000, 50);
}
@Test
void insertDeleteMixDegree20() {
mixInsertAndDelete(20, 1000, 50);
}
void mixInsertAndDelete(int degree, int initSize, int batchSize) {
var r = new Random();
for (var i = 0; i < 10; i++) {
var bplustree = new BPlusTree(degree);
var map = new TreeMap<String, String>();
var keySequence = getRandomKeySequence(initSize);
var valueSequence = getRandomValueSequence(initSize);
for (var j = 0; j < keySequence.size(); j++) {
bplustree.insert(keySequence.get(j), valueSequence.get(j));
map.put(keySequence.get(j), valueSequence.get(j));
assertArrayEquals(ListUtil.flatten(map).toArray(), bplustree.traverse().toArray());
}
for (var j = 0; j < 200; j++) {
var sectionSize = r.nextInt(batchSize);
var keySequence1 = getRandomKeySequence(initSize).subList(0, sectionSize);
var valueSequence1 = getRandomValueSequence(initSize).subList(0, sectionSize);
if (r.nextInt(2) == 1) {
for (var k = 0; k < sectionSize; k++) {
bplustree.delete(keySequence1.get(k));
map.remove(keySequence1.get(k));
assertArrayEquals(ListUtil.flatten(map).toArray(), bplustree.traverse().toArray());
}
} else {
for (var k = 0; k < sectionSize; k++) {
bplustree.insert(keySequence1.get(k), valueSequence1.get(k));
map.put(keySequence1.get(k), valueSequence1.get(k));
assertArrayEquals(ListUtil.flatten(map).toArray(), bplustree.traverse().toArray());
}
}
}
}
}
void testSimpleInsertDelete(int degree, List<String> keySequence, List<String> valueSequence,
List<String> deleteSequence) {
for (var i = 0; i < 10; i++) {
var bplustree = new BPlusTree(degree);
var map = new TreeMap<String, String>();
for (var j = 0; j < keySequence.size(); j++) {
bplustree.insert(keySequence.get(j), valueSequence.get(j));
map.put(keySequence.get(j), valueSequence.get(j));
assertArrayEquals(ListUtil.flatten(map).toArray(), bplustree.traverse().toArray());
}
for (var elem : deleteSequence) {
var deleted = bplustree.delete(elem);
Assertions.assertTrue(deleted);
map.remove(elem);
assertArrayEquals(ListUtil.flatten(map).toArray(), bplustree.traverse().toArray());
}
}
}
}
|
package com.yc.education.service.account;
import com.yc.education.model.account.AccountReceivableFee;
import com.yc.education.service.IService;
import java.util.List;
/**
* @Description
* @Author BlueSky
* @Date 2018-12-07 11:39
*/
public interface IAccountReceivableFeeService extends IService<AccountReceivableFee> {
/**
* 根据 应收账款冲账id 查询
* @param otherid
* @return
*/
List<AccountReceivableFee> listAccountReceivableFee( String otherid);
/**
* 通过外键删除
* @param otherid
* @return
*/
int deleteAccountReceivableFeeByParentId( String otherid);
}
|
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
int k = 1;
int value = 0;
//boolean out = true;
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
String[] strArr = str.split("\\s+");
for (int i = 0; k < strArr.length; i++,k++) {
value = strArr[i].compareTo(strArr[k]);
}
System.out.println(!(value>0));
/*switch (value) {
case 1:
out = false;
break;
}
System.out.println(out);
System.out.println(value);*/
}
}
|
package com.nuthana.automation.test;
import com.nuthana.automation.utils.General;
public class TestCase12 {
public static void main(String[] args) {
// TODO Auto-generated method stub
General gen = new General();
gen.OpenApplication();
gen.newuserregistration();
}
}
|
package com.karya.bean;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
public class SalesTaxesBean {
private int id;
@NotNull
@NotEmpty(message = "Please Enter Title")
private String title;
@NotNull
@NotEmpty(message = "Please Enter Company Name.")
private String company;
@NotNull
@NotEmpty(message = "Please Enter Type")
private String type;
@NotNull
@NotEmpty(message = "Please Enter AccountHead")
private String accounthead;
@Min(value=1)
@NotNull(message= "Please enter Rate")
private int rate;
@Min(value=1)
@NotNull(message= "Please enter Amount")
private int amount;
@Min(value=1)
@NotNull(message= "Please enter Total")
private int total;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getAccounthead() {
return accounthead;
}
public void setAccounthead(String accounthead) {
this.accounthead = accounthead;
}
public int getRate() {
return rate;
}
public void setRate(int rate) {
this.rate = rate;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
}
|
/**
*/
package iotwearable.model.iotw.impl;
import iotwearable.model.iotw.DHT11;
import iotwearable.model.iotw.IotwFactory;
import iotwearable.model.iotw.IotwPackage;
import iotwearable.model.iotw.Pin;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>DHT11</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link iotwearable.model.iotw.impl.DHT11Impl#getPinGND <em>Pin GND</em>}</li>
* <li>{@link iotwearable.model.iotw.impl.DHT11Impl#getPinVcc <em>Pin Vcc</em>}</li>
* <li>{@link iotwearable.model.iotw.impl.DHT11Impl#getPinData <em>Pin Data</em>}</li>
* </ul>
*
* @generated
*/
public class DHT11Impl extends InputDeviceImpl implements DHT11 {
/**
* The default value of the '{@link #getPinGND() <em>Pin GND</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getPinGND()
* @generated
* @ordered
*/
protected static final Pin PIN_GND_EDEFAULT = (Pin)IotwFactory.eINSTANCE.createFromString(IotwPackage.eINSTANCE.getPin(), "GND,IO");
/**
* The cached value of the '{@link #getPinGND() <em>Pin GND</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getPinGND()
* @generated
* @ordered
*/
protected Pin pinGND = PIN_GND_EDEFAULT;
/**
* The default value of the '{@link #getPinVcc() <em>Pin Vcc</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getPinVcc()
* @generated
* @ordered
*/
protected static final Pin PIN_VCC_EDEFAULT = (Pin)IotwFactory.eINSTANCE.createFromString(IotwPackage.eINSTANCE.getPin(), "Vcc,IO");
/**
* The cached value of the '{@link #getPinVcc() <em>Pin Vcc</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getPinVcc()
* @generated
* @ordered
*/
protected Pin pinVcc = PIN_VCC_EDEFAULT;
/**
* The default value of the '{@link #getPinData() <em>Pin Data</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getPinData()
* @generated
* @ordered
*/
protected static final Pin PIN_DATA_EDEFAULT = (Pin)IotwFactory.eINSTANCE.createFromString(IotwPackage.eINSTANCE.getPin(), "Data,IO");
/**
* The cached value of the '{@link #getPinData() <em>Pin Data</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getPinData()
* @generated
* @ordered
*/
protected Pin pinData = PIN_DATA_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
protected DHT11Impl() {
super();
this.name ="DHT11";
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return IotwPackage.Literals.DHT11;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Pin getPinGND() {
return pinGND;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setPinGND(Pin newPinGND) {
Pin oldPinGND = pinGND;
pinGND = newPinGND;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, IotwPackage.DHT11__PIN_GND, oldPinGND, pinGND));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Pin getPinVcc() {
return pinVcc;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setPinVcc(Pin newPinVcc) {
Pin oldPinVcc = pinVcc;
pinVcc = newPinVcc;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, IotwPackage.DHT11__PIN_VCC, oldPinVcc, pinVcc));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Pin getPinData() {
return pinData;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setPinData(Pin newPinData) {
Pin oldPinData = pinData;
pinData = newPinData;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, IotwPackage.DHT11__PIN_DATA, oldPinData, pinData));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case IotwPackage.DHT11__PIN_GND:
return getPinGND();
case IotwPackage.DHT11__PIN_VCC:
return getPinVcc();
case IotwPackage.DHT11__PIN_DATA:
return getPinData();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case IotwPackage.DHT11__PIN_GND:
setPinGND((Pin)newValue);
return;
case IotwPackage.DHT11__PIN_VCC:
setPinVcc((Pin)newValue);
return;
case IotwPackage.DHT11__PIN_DATA:
setPinData((Pin)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case IotwPackage.DHT11__PIN_GND:
setPinGND(PIN_GND_EDEFAULT);
return;
case IotwPackage.DHT11__PIN_VCC:
setPinVcc(PIN_VCC_EDEFAULT);
return;
case IotwPackage.DHT11__PIN_DATA:
setPinData(PIN_DATA_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case IotwPackage.DHT11__PIN_GND:
return PIN_GND_EDEFAULT == null ? pinGND != null : !PIN_GND_EDEFAULT.equals(pinGND);
case IotwPackage.DHT11__PIN_VCC:
return PIN_VCC_EDEFAULT == null ? pinVcc != null : !PIN_VCC_EDEFAULT.equals(pinVcc);
case IotwPackage.DHT11__PIN_DATA:
return PIN_DATA_EDEFAULT == null ? pinData != null : !PIN_DATA_EDEFAULT.equals(pinData);
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuilder result = new StringBuilder(super.toString());
result.append(" (pinGND: ");
result.append(pinGND);
result.append(", pinVcc: ");
result.append(pinVcc);
result.append(", pinData: ");
result.append(pinData);
result.append(')');
return result.toString();
}
@Override
public EList<Pin> getPins() {
EList<Pin> pins = new BasicEList<Pin>();
pins.add(pinGND);
pins.add(pinVcc);
pins.add(pinData);
return pins;
}
@Override
public void modifyPin(Pin pin) {
if(pin.getName().equals(pinGND.getName())){
setPinGND(pin);
}
else if(pin.getName().equals(pinVcc.getName())){
setPinVcc(pin);
}
else if(pin.getName().equals(pinData.getName())) {
setPinData(pin);
}
}
} //DHT11Impl
|
// https://www.youtube.com/watch?v=sFt3KVGyeWw
class Solution {
public List<Integer> sequentialDigits(int low, int high) {
String digits = "123456789";
int n = 10;
List<Integer> result = new ArrayList();
int lowLen = String.valueOf(low).length();
int highLen = String.valueOf(high).length();
for (int length = lowLen; length < highLen + 1; ++length) {
for (int start = 0; start < n - length; ++start) {
int num = Integer.parseInt(digits.substring(start, start + length));
if (num >= low && num <= high) result.add(num);
}
}
return result;
}
}
|
package com.romens.yjkgrab.utils;
import android.content.Context;
import android.util.DisplayMetrics;
import android.util.TypedValue;
/**
* Created by myq on 15-12-9.
*/
public class DimenHelper {
private static DisplayMetrics metrics;
public static int dp(float px, Context context) {
return (int) (0.5f + TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, px, getMetrics(context)));
}
public static int sp(float px, Context context) {
return (int) (0.5f + TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, px, getMetrics(context)));
}
private static DisplayMetrics getMetrics(Context context) {
if (metrics == null) {
synchronized (DimenHelper.class) {
if (metrics == null) {
metrics = context.getApplicationContext().getResources().getDisplayMetrics();
}
}
}
return metrics;
}
}
|
package matrices;
@SuppressWarnings("serial")
public class RotationZMatrix extends Matrix4f {
private float theta;
/**
* Constructs a new Matrix that rotates objects around the Z-axis.
*
* @param theta The rotation angle in degrees.
*/
public RotationZMatrix(float theta)
{
super( (float)Math.cos(Math.toRadians(theta)), (float)-Math.sin(Math.toRadians(theta)), 0, 0,
(float)Math.sin(Math.toRadians(theta)), (float) Math.cos(Math.toRadians(theta)), 0, 0,
0, 0, 1, 0,
0, 0, 0, 1);
this.theta = theta%360;
}
@Override
public RotationZMatrix inv() {
return new RotationZMatrix(-theta);
}
@Override
public float det() {
return 1; //or -1...
}
@Override
public boolean isIdentity() {
return theta == 0;
}
@Override
public boolean isSingular() {
return false;
}
}
|
package person;
import org.w3c.dom.ls.LSOutput;
import java.util.ArrayList;
import java.util.List;
public class Group<T extends Person> {
private List<T> personGroup = new ArrayList<>();
public T add(T person){
personGroup.add(person);
System.out.println(person);
return person;
}
public class Group1<T extends Person>{
//规定main在执行这里的时候只能是person的子类(student and teacher)或person
// 就可以在这里system print in (person.getFirstName)了, 上面的就不行 因为非常generic(范型)
}
}
|
package exercicio04;
import java.util.Scanner;
public class Usuario
{
private Integer id;
private String nome;
private String senha;
Scanner entrada = new Scanner(System.in);
int operador;
Usuario(Integer id, String nome, String senha)
{
System.out.println("Bem vindo, insira os adados por favor\n");
System.out.println("0=Id\n1=Nome\n2=Senha\n");
operador=entrada.nextInt();
if(operador==0)
{
System.out.println("Insira seu Id:\n");
id=entrada.nextInt();
}
else if(operador==1)
{
System.out.println("Insira seu Nome:\n");
nome=entrada.next();
}
else if(operador==2)
{
System.out.println("Insira sua senha:\n");
senha=entrada.next();
}
}
public String getNome() {
return nome;
}
public String getSenha() {
return senha;
}
public Integer getId() {
return id;
}
}
|
package com.n0texpecterr0r.classtimetable.ui;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.n0texpecterr0r.classtimetable.R;
import com.n0texpecterr0r.classtimetable.table.bean.Course;
/**
* @author Created by Nullptr
* @date 2018/8/14 20:08
* @describe 课程详情Dialog
*/
public class CourseDialog extends Dialog {
private TextView mTvName;
private TextView mTvLocation;
private TextView mTvTeacher;
private TextView mTvTime;
private TextView mTvWeek;
private ImageView mIvClose;
private Course mCourse;
public CourseDialog(@NonNull Context context, Course course) {
super(context,R.style.CourseDialogStyle);
mCourse = course;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_course);
// 空白处不关闭
setCanceledOnTouchOutside(false);
mTvName = findViewById(R.id.course_tv_name);
mTvLocation = findViewById(R.id.course_tv_location);
mTvTeacher = findViewById(R.id.course_tv_teacher);
mTvTime = findViewById(R.id.course_tv_time);
mTvWeek = findViewById(R.id.course_tv_week);
mIvClose = findViewById(R.id.course_iv_close);
mTvName.setText(mCourse.getName());
if (mCourse.getClassroom().equals("")) {
mTvLocation.setText("暂无课室安排");
} else {
mTvLocation.setText(mCourse.getClassroom());
}
if (mCourse.getTeacher().equals("")) {
mTvTeacher.setText("暂无老师安排");
}else{
mTvTeacher.setText(mCourse.getTeacher());
}
mTvTime.setText(mCourse.getStartNum()+"-"+mCourse.getEndNum()+"节");
mTvWeek.setText(mCourse.getStartWeek()+"-"+mCourse.getEndWeek()+"周");
mIvClose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
}
}
|
package com.example.dailyroutineplanner;
public class Summary {
private int SummaryID, Success, Miss;
public Summary(int summaryID, int success, int miss) {
SummaryID = summaryID;
Success = success;
Miss = miss;
}
public int getSummaryID() {
return SummaryID;
}
public int getSuccess() {
return Success;
}
public int getMiss() {
return Miss;
}
}
|
package com.hc.element_ec.sign;
import android.app.Activity;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatTextView;
import android.util.Patterns;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;
import com.hc.element_ec.R;
import com.heyskill.element_core.fragments.BaseFragment;
public class SignInFragment extends BaseFragment {
private TextInputEditText mEmail = null;
private TextInputEditText mPassword = null;
private AppCompatButton btn_sign_in;
private AppCompatTextView tv_link_sign_up;
private ISignListener mISignListener = null;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if(activity instanceof ISignListener){
mISignListener = (ISignListener) activity;
}
}
@Override
public Object setLayout() {
return R.layout.element_sign_in;
}
@Override
public void onBindView(Bundle savedInstanceState, View rootView) {
initViewID(rootView);
btn_sign_in.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onClickSignIn();
}
});
tv_link_sign_up.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onclickToSignUp();
}
});
}
private void initViewID(View rootView){
mEmail = rootView.findViewById(R.id.edit_sign_in_email);
mPassword = rootView.findViewById(R.id.edit_sign_in_password);
btn_sign_in = rootView.findViewById(R.id.btn_sign_in);
tv_link_sign_up = rootView.findViewById(R.id.tv_link_sign_up);
}
private boolean checkForm() {
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
boolean isPass = true;
if (email.isEmpty() || !Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
mEmail.setError("错误的邮箱格式");
isPass = false;
} else {
mEmail.setError(null);
}
if (password.isEmpty() || password.length() < 6) {
mPassword.setError("请填写至少6位数密码");
isPass = false;
} else {
mPassword.setError(null);
}
return isPass;
}
private void onClickSignIn(){
if(checkForm()){
Toast.makeText(getContext(), "登录成功", Toast.LENGTH_SHORT).show();
//SignHandler.onSignIn("123",mISignListener);
}
}
private void onclickToSignUp(){
// getSupportDelegate().start(new SignUpFragment());
}
}
|
package com.challenge.jacobtcantera.movietestapp.domain.model;
/**
* Created by jacob on 20/01/2018.
*/
public class Movie {
private static final String BASE_URL = "http://image.tmdb.org/t/p/";
private static final String COVER_SIZE = "w342";
private String title;
private String overview;
private String year;
private String image;
public Movie(String title, String overview, String year, String image) {
this.title = title;
this.overview = overview;
this.year = year;
this.image = image;
}
public String getTitle() {
return title;
}
public String getOverview() {
return overview;
}
public String getYear() {
return year;
}
public String getImage() {
return image;
}
public String getImageUrl() {
return BASE_URL + COVER_SIZE + image;
}
}
|
package de.xconnortv.warps.utils;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
public class InventoryFill {
private final Inventory inv;
private List<Integer> sideSlots = new ArrayList<>();
public InventoryFill(Inventory inv) {
this.inv = inv;
}
public void fillSidesWithItem(ItemStack item) {
int size = inv.getSize();
int rows = size / 9;
String name = "§6";
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(name);
item.setItemMeta(meta);
if (rows >= 3) {
for (int i = 0; i <= 8; i++) {
this.inv.setItem(i, item);
sideSlots.add(i);
}
for (int s = 8; s < (this.inv.getSize() - 9); s += 9) {
int lastSlot = s + 1;
this.inv.setItem(s, item);
this.inv.setItem(lastSlot, item);
sideSlots.add(s);
sideSlots.add(lastSlot);
}
for (int lr = (this.inv.getSize() - 9); lr < this.inv.getSize(); lr++) {
this.inv.setItem(lr, item);
sideSlots.add(lr);
}
}
}
public List<Integer> getNonSideSlots() {
List<Integer> availableSlots = new ArrayList<>();
for (int i = 0; i < this.inv.getSize(); i++) {
if (!this.sideSlots.contains(i)) {
availableSlots.add(i);
}
}
return availableSlots;
}
}
|
package redington.week3.project;
public class SquareAndCubeTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
SquareAndCube a1=new SquareAndCube();
a1.getInput();
a1.square();
a1.cube();
}
}
|
package com.unimelb.comp90015.Server.Dictionary;
/**
* Xulin Yang, 904904
*
* @create 2020-03-24 0:15
* description: interface for dictionary to provide extendability
**/
public interface IDictionary {
/**
* @param word the word to be searched
* @return word's meaning
* @throws WordNotFoundException the word not existing in the dictionary
*/
String search(String word) throws WordNotFoundException;
/**
* @param word word the word to be deleted
* @throws WordNotFoundException the word not existing in the dictionary
*/
void remove(String word) throws WordNotFoundException;
/**
* @param word the word to be added
* @param meaning the word's meaning
* @throws DuplicateWordException the word already existing in the dictionary
*/
void add(String word, String meaning) throws DuplicateWordException;
/**
* save the dictionary to disk
*/
void save();
}
|
package com.nick.java.handler;
import com.nick.java.GraphType;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GraphTypeHandler implements ActionListener
{
GraphType gt;
public GraphTypeHandler(GraphType gt)
{
this.gt = gt;
}
public void actionPerformed(ActionEvent ae)
{
Object o = ae.getSource();
if (o==gt.b1)
{
if (gt.list1.getSelectedItem().equals("Column-Graph")|gt.list1.getSelectedItem().equals("Line-Graph")|gt.list1.getSelectedItem().equals("Pie-Graph"))
{
CardLayout c1 = (CardLayout)(gt.g.getLayout());
c1.show(gt.g,"enter_data");
}
}
if (o==gt.b2)
{
gt.g.setVisible(false);
}
}
}
|
package racingcar.vo;
import racingcar.domain.Car;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class RacingResultOfRound {
private final List<Car> carsOfRound;
private final int round;
public RacingResultOfRound(List<Car> carsOfRound, int round) {
this.carsOfRound = carsOfRound;
this.round = round;
}
public List<Car> getCarsOfRound() {
return Collections.unmodifiableList(carsOfRound);
}
public int getRound() {
return round;
}
public List<Car> getWinners() {
int maxMovedDistance = getMaxMovedDistance();
return this.carsOfRound.stream()
.filter(car -> maxMovedDistance == car.getMovedDistance())
.collect(Collectors.toList());
}
int getMaxMovedDistance() {
return this.carsOfRound.stream()
.mapToInt(Car::getMovedDistance)
.max()
.getAsInt();
}
}
|
package group.dao;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import org.apache.log4j.Logger;
import group.Group;
import souvenirs.Picture;
import tool.DB;
public class GroupDAO {
private Logger logger = Logger.getLogger(GroupDAO.class);
private static GroupDAO group_dao = new GroupDAO();
/**
* 单例模式获取对象的方法
*
* @return SouvenirDAO类的对象
*/
public static GroupDAO getInstance() {
return group_dao;
}
public List<Group> queryGroupByUserID(String user_id, int start_pos, int content_length) throws Exception {
String sql = "select group_id, group_name, intro, shared_album_name, album_cover, create_timestamp from query_group_with_user where user_id=? limit ?, ?";
List<Object> para = Arrays.asList(user_id, start_pos, content_length);
return DB.execSQLQueryO(sql, para, new GroupImplStore());
}
public List<Group> queryGroupByUserIDGroupID(String user_id, String group_id) throws Exception {
String sql = "select group_id, group_name, intro, shared_album_name, album_cover, create_timestamp from query_group_with_user "
+ "where user_id=? and group_id = ?";
List<Object> para = Arrays.asList(user_id, group_id);
return DB.execSQLQueryO(sql, para, new GroupImplStore());
}
public int getGroupNumberByUserID(String user_id) throws Exception {
String sql = "select count(*) from query_group_with_user where user_id = ?";
List<Object> para = Arrays.asList(user_id);
List<List<Object>> result = DB.execSQLQueryO(sql, para);
if (result.size() == 0 || result.get(0).size() == 0)
throw new Exception("No Result!");
else
return (new Long((Long) result.get(0).get(0))).intValue();
}
public int updateGroupName(String group_id, String new_name) throws Exception {
String sql = "update `group` set group_name = ? where group_id=?";
List<Object> para = Arrays.asList(new_name, group_id);
return DB.execSQLUpdateO(sql, para);
}
public int updateIntro(String group_id, String new_intro) throws Exception {
String sql = "update `group` set intro = ? where group_id=?";
List<Object> para = Arrays.asList(new_intro, group_id);
return DB.execSQLUpdateO(sql, para);
}
public int leaveGroup(String user_id, String group_id) throws Exception {
String sql = "delete from `user_belong_group` where user_id=? and group_id=?";
List<Object> para = Arrays.asList(user_id, group_id);
return DB.execSQLUpdateO(sql, para);
}
public List<Group> searchGroup(String group_id, boolean is_fuzzy) throws Exception {
String sql = "";
if (is_fuzzy) {
sql = "select group_id, group_name, intro, shared_album_name, album_cover, create_timestamp from `group`"
+ "where group_id like ?";
group_id = "%" + group_id + "%";
} else
sql = "select group_id, group_name, intro, shared_album_name, album_cover, create_timestamp from `group` where group_id=?";
List<Object> para = Arrays.asList(group_id);
return DB.execSQLQueryO(sql, para, new GroupImplStore());
}
public int joininGroup(String user_id, String group_id) throws Exception {
String sql = "insert into user_belong_group values(?, ?)";
List<String> para = Arrays.asList(user_id, group_id);
return DB.execSQLUpdate(sql, para);
}
public String createGroup(String group_name, String description, String salbum_name, String format) throws Exception {
int try_times = 0;
while (try_times <= 3) {
String sql = "select count(*) from `group`";
List<Object> para = Arrays.asList();
List<List<Object>> rs = DB.execSQLQueryO(sql, para);
if (rs.size() == 1 && rs.get(0).size() == 1) {
sql = "insert into `group`(group_id, group_name, intro, shared_album_name, album_cover) values(?, ?, ?, ?, ?)";
long group_id = (long)rs.get(0).get(0) + 1;
String str = "000000000";
String group_id_str = str.substring(0, 9-String.valueOf(group_id).length())+String.valueOf(group_id);
para = Arrays.asList(group_id_str, group_name, description, salbum_name,
(File.separator + "group" + File.separator + group_id_str + "_cover." + format).replaceAll("\\\\", "\\\\\\\\"));
try {
DB.execSQLUpdateO(sql, para);
return group_id_str;
} catch (Exception e) {
// TODO: handle exception
logger.warn("Creating new group failed, try again. Parameters: group_name=<"+group_name+">, group_id=<"+group_id+">");
}
} else
throw new Exception("Cannot query valid result set!");
}
return "";
}
public String createGroup(String group_name, String description, String salbum_name) throws Exception {
int try_times = 0;
while (try_times <= 3) {
String sql = "select count(*) from `group`";
List<Object> para = Arrays.asList();
List<List<Object>> rs = DB.execSQLQueryO(sql, para);
if (rs.size() == 1 && rs.get(0).size() == 1) {
sql = "insert into `group`(group_id, group_name, intro, shared_album_name) values(?, ?, ?, ?)";
long group_id = (long)rs.get(0).get(0) + 1;
String str = "000000000";
String group_id_str = str.substring(0, 9-String.valueOf(group_id).length())+String.valueOf(group_id);
para = Arrays.asList(group_id_str, group_name, description, salbum_name);
int rs2 = DB.execSQLUpdateO(sql, para);
if (rs2 == 1)
return group_id_str;
else
return "";
} else
throw new Exception("Cannot query valid result set!");
}
return "";
}
}
|
package com.factory.factorydeletedetails.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
/**
* Author: Amit
* Date: 03-01-2020
*/
@Repository
public class ApplicationDeleteDaoImpl implements ApplicationDeleteDao {
JdbcTemplate jdbcTemplate;
@Autowired
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public int getDeleteAllApplicationFromDb() {
return jdbcTemplate.update("delete from applications");
}
@Override
public int getDeleteApplicationByIdFromDb(int id) {
Object[] params = {id};
return jdbcTemplate.update("delete from applications where id=?", params);
}
}
|
package com.github.xiaomi007.annotations;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import com.github.xiaomi007.annotations.annotations.Key;
import com.github.xiaomi007.annotations.annotations.Table;
import com.github.xiaomi007.annotations.models.Cat;
import com.github.xiaomi007.annotations.models.Dog;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import static android.content.ContentValues.TAG;
/**
* //TODO: Javadoc on com.github.xiaomi007.annotations.MyDB
*
* @author Damien
* @version //TODO version
* @since 2016-11-01
*/
public class MyDB extends SQLiteOpenHelper {
private Handler handler;
private Handler mainHandler;
private Class<?>[] classes = {
Dog.class,
Cat.class
};
public MyDB(Context context) {
super(context, "MyDB", null, 5);
final HandlerThread handlerThread = new HandlerThread("queries");
handlerThread.start();
handler = new Handler(handlerThread.getLooper());
mainHandler = new Handler(context.getMainLooper());
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG, "onCreate: " + Thread.currentThread().getName());
for (Class<?> aClass : classes) {
db.execSQL(createTable(aClass));
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
Log.d(TAG, "onUpgrade() called with: i = [" + i + "], i1 = [" + i1 + "]");
for (Class<?> aClass : classes) {
Table table = aClass.getAnnotation(Table.class);
db.execSQL("DROP TABLE IF EXISTS " + table.table() + ";");
}
onCreate(db);
}
public static String createTable(Class<?> clazz) {
StringBuilder sb = new StringBuilder();
StringBuilder unique = new StringBuilder();
sb.append("CREATE TABLE ");
Table table = clazz.getAnnotation(Table.class);
sb.append(table.table()).append(" (");
final Field[] fields = clazz.getFields();
boolean isFirst = true;
boolean isFirstUnique = true;
for (int i = 0, fieldsLength = fields.length; i < fieldsLength; i++) {
Field field = fields[i];
Key key = field.getAnnotation(Key.class);
if (key.isPrimary()) {
if (!isFirstUnique) {
unique.append(", ");
} else {
unique.append(", UNIQUE (");
isFirstUnique = false;
}
unique.append(key.field());
}
if (!isFirst) {
sb.append(", ");
} else {
isFirst = false;
}
sb.append(key.field()).append(" ").append("TEXT");
}
if (!isFirstUnique) {
sb.append(unique.toString());
sb.append(") ON CONFLICT REPLACE");
}
sb.append(");");
Log.d(TAG, "createTable: " + sb.toString());
return sb.toString();
}
public void insert(final Object o) {
handler.post(new Runnable() {
@Override
public void run() {
Table table = o.getClass().getAnnotation(Table.class);
SQLiteDatabase database = getWritableDatabase();
database.insert(table.table(), null, KeyParser.getValues(o));
database.close();
}
});
}
public void update(final Object o, final ContentValues values, final String where) {
handler.post(new Runnable() {
@Override
public void run() {
Table table = o.getClass().getAnnotation(Table.class);
SQLiteDatabase database = getWritableDatabase();
int i = database.update(table.table(), values, where, null);
if (i == 0) {
database.insert(table.table(), null, values);
}
database.close();
}
});
}
public <T> void queryAsync(Class<T> t, Query<List<T>> query) {
final MyRunnable<T> runnable = new MyRunnable<>(t, query);
handler.post(runnable);
}
public interface Query<T> {
void result(T t);
}
public class MyRunnable<T> implements Runnable {
private static final String TAG = "MyRunnable";
private Class<T> t;
private Query<List<T>> query;
public MyRunnable(Class<T> t, Query<List<T>> query) {
this.t = t;
this.query = query;
}
@Override
public void run() {
Table table = t.getAnnotation(Table.class);
Cursor cursor = null;
try {
cursor = getReadableDatabase().query(table.table(), null, null, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
final List<T> list = new ArrayList<>();
do {
Field[] fields = t.getDeclaredFields();
try {
T o = t.newInstance();
list.add(o);
for (Field field : fields) {
Key key = field.getAnnotation(Key.class);
if (key.field().equals("id")) {
Log.d(TAG, "run: " + cursor.getLong(cursor.getColumnIndexOrThrow(key.field())));
field.set(o, cursor.getLong(cursor.getColumnIndexOrThrow(key.field())));
} else {
Log.d(TAG, "run: " + cursor.getString(cursor.getColumnIndexOrThrow(key.field())));
field.set(o, cursor.getString(cursor.getColumnIndexOrThrow(key.field())));
}
}
} catch (Exception e) {
Log.e(TAG, "run: ", e);
}
} while (cursor.moveToNext());
mainHandler.post(new Runnable() {
@Override
public void run() {
query.result(list);
}
});
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
}
}
|
package com.redhat.service.bridge.manager.api.user.validators.actions;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import com.redhat.service.bridge.actions.ActionProvider;
import com.redhat.service.bridge.actions.ActionProviderException;
import com.redhat.service.bridge.actions.ActionProviderFactory;
import com.redhat.service.bridge.actions.ValidationResult;
import com.redhat.service.bridge.infra.models.actions.BaseAction;
import com.redhat.service.bridge.manager.api.models.requests.ProcessorRequest;
@ApplicationScoped
public class ActionParamValidatorContainer implements ConstraintValidator<ValidActionParams, ProcessorRequest> {
@Inject
ActionProviderFactory actionProviderFactory;
@Override
public boolean isValid(ProcessorRequest value, ConstraintValidatorContext context) {
/*
* Centralised handling of Action parameters. The idea here being that for each Action we support, we
* provide the ability to check:
*
* - The action 'type' is recognised
* - The parameters supplied to configure the Action are valid.
*/
BaseAction baseAction = value.getAction();
if (baseAction == null) {
return false;
}
if (baseAction.getParameters() == null || baseAction.getParameters().isEmpty()) {
return false;
}
ActionProvider actionProvider;
try {
actionProvider = actionProviderFactory.getActionProvider(baseAction.getType());
} catch (ActionProviderException e) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("Action of type '" + baseAction.getType() + "' is not recognised.").addConstraintViolation();
return false;
}
ValidationResult v = actionProvider.getParameterValidator().isValid(baseAction);
if (!v.isValid()) {
String message = v.getMessage();
if (message == null) {
message = "Parameters for Action '" + baseAction.getName() + "' of Type '" + baseAction.getType() + "' are not valid.";
}
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
}
return v.isValid();
}
}
|
package org.oatesonline.yaffle.services.impl;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.json.simple.JSONArray;
import org.json.simple.JSONValue;
import org.oatesonline.yaffle.entities.dao.DAOFactory;
import org.oatesonline.yaffle.entities.dao.DAOPlayer;
import org.oatesonline.yaffle.entities.impl.Player;
import org.oatesonline.yaffle.entities.impl.Team;
import org.oatesonline.yaffle.services.ILeaderboardService;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;
public class LeaderboardService extends ServerResource implements ILeaderboardService {
/**
*
* @return a JSON or XML String of the current Leaderboard
*/
@Get
public String getLeaderboard(){
String ret = "{ \"players\":";
SortedSet<Player> lboard = new TreeSet<Player>();
DAOPlayer daoP = DAOFactory.getDAOPlayerInstance();
List<Player> plyrs = daoP.getAllPlayers();
lboard.addAll(plyrs); //Sorts the players into descending order
List<Player> pList = new ArrayList<Player>();
pList.addAll(0, lboard);
ret += JSONArray.toJSONString(pList);
ret += "}";
return ret;
}
@Post("json"/* "application/json" */)
public String updateLeaderboard(){
StringBuffer ret = new StringBuffer ("");
DAOPlayer daoP = DAOFactory.getDAOPlayerInstance();
Set<Player> plyrs = daoP.updateLeaderboard();
Iterator<Player> itp = plyrs.iterator();
while (itp.hasNext()){
ret.append(itp.next().toJSONString());
}
return ret.toString();
}
}
|
package duke.command;
import duke.ImageType;
import duke.Storage;
import duke.TaskList;
import duke.Ui;
import duke.exception.EmptyDescriptionException;
import duke.exception.WrongFormatException;
import duke.task.Deadline;
import duke.task.Event;
import duke.task.TaskType;
import duke.task.Todo;
/**
* Represents a TaskCommand.
*/
public class TaskCommand extends Command {
/**
* Type of task.
*/
protected TaskType taskType;
/**
* Description of task.
*/
protected String description;
/**
* Creates a TaskCommand object.
* @param taskType Type of task.
* @param description Description of task.
*/
public TaskCommand(TaskType taskType, String description) {
super(CommandType.TASK, ImageType.TICK);
this.taskType = taskType;
this.description = description;
}
/**
* Executes an add task command
* @param ui Ui associated with the command.
* @param taskList Task list associated with the command.
* @return Acknowledgement that a task has been added.
* @throws EmptyDescriptionException For when the user did not give a description.
* @throws WrongFormatException For when the description does not fit the format of the task type.
*/
@Override
public String execute(Ui ui, TaskList taskList) throws EmptyDescriptionException,
WrongFormatException {
if (description.isEmpty()) {
throw new EmptyDescriptionException();
}
try {
switch (taskType) {
case TODO:
taskList.addTask(new Todo(description, taskType));
break;
case DEADLINE:
String[] deadlineSplit = description.split(",");
taskList.addTask(new Deadline(deadlineSplit[0], deadlineSplit[1], taskType));
break;
case EVENT:
String[] eventSplit = description.split(",");
taskList.addTask(new Event(eventSplit[0], eventSplit[1], taskType));
break;
default:
}
Storage.saveTaskChanges(taskList);
return ui.printAddAcknowledgement(taskList) + ui.printAdditionActionMessage();
} catch (IndexOutOfBoundsException e) {
throw new WrongFormatException();
}
}
}
|
package com.ifeng.recom.mixrecall.core.channel.excutor;
import com.google.common.collect.Lists;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.ifeng.recom.mixrecall.common.api.SearchApi;
import com.ifeng.recom.mixrecall.common.dao.elastic.EsClientFactory;
import com.ifeng.recom.mixrecall.common.dao.hbase.HBaseUtils;
import com.ifeng.recom.mixrecall.common.model.Document;
import com.ifeng.recom.mixrecall.core.cache.DocPreloadCache;
import org.apache.logging.log4j.util.Strings;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static org.elasticsearch.index.query.QueryBuilders.rangeQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
/**
* Created by lilg1 on 2018/1/23.
*/
public class UserSearchQuery {
private final static Logger logger = LoggerFactory.getLogger(UserSearchQuery.class);
private static TransportClient client;
private final static String INDEX = "preload-news";
private final static String TYPE = "all";
private final static boolean available = true;
private final static boolean offline = false;
private static String[] needFetchSource = new String[]{"docId", "simId"};
static {
client = EsClientFactory.getClient();
}
/**
* 根据用户搜索词查询搜索接口获取文章
*
* @param searchQuery
* @return
*/
public static List<Document> searchQueryEs(String searchQuery) {
List<String> rowkeys = Lists.newArrayList();
JsonObject searchResult=null;
JsonArray items=null;
try{
searchResult = SearchApi.doSearch(searchQuery);
items = searchResult.getAsJsonArray("items");
}catch (Exception e){
logger.error("{} searchQueryEs error:{}",searchQuery,e);
}
if (items ==null||items.size()<1){
return Lists.newArrayList();
}
logger.info("SearchApi searchSize is :{}",items.size());
for (JsonElement j: items){
String id = j.getAsJsonObject().get("id").getAsString();
String sourceFrom = j.getAsJsonObject().get("sourceFrom").getAsString();
if("weMedia".equals(sourceFrom)){
sourceFrom = "sub";
rowkeys.add(sourceFrom+"_"+id);
}else if ("video".equals(sourceFrom)) {
rowkeys.add(id);
}else {
rowkeys.add(sourceFrom+"_"+id);
}
}
//搜索id转推荐id
Map<String, String> news_itemf_index = HBaseUtils.queryCmppIdBySubId(rowkeys, "news_itemf_index");
Set<String> docids = news_itemf_index.values().stream().map(s -> s.substring("cmpp_".length())).collect(Collectors.toSet());
logger.info("searchQuery:{} --- id2docIdfromHbase :{} --- docids:{} ",searchQuery,news_itemf_index,docids);
//根据docid取推荐库取document
List<Document> rt = new ArrayList<>();
Map<String, Document> documentMap = DocPreloadCache.getBatchDocsWithQueryNoClone(docids);
Set<String> includeSimIds = new HashSet<>();
Collection<Document> values = documentMap.values();
//过滤docidmiss && simid为空
Set<Document> collect = values.stream().filter(document -> document!=null && !Strings.isBlank(document.getSimId())).collect(Collectors.toSet());
for (Document d : collect){
if (!includeSimIds.contains(d.getSimId())) {
d.setRecallTag(searchQuery);
rt.add(d);
}
includeSimIds.add(d.getSimId());
}
return rt;
}
}
|
package com.legaoyi.storer.handler;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;
import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueWrapper;
import com.legaoyi.storer.service.DeviceService;
import com.legaoyi.storer.util.BatchMessage;
import com.legaoyi.storer.util.Constants;
import com.legaoyi.storer.util.ServerRuntimeContext;
import com.legaoyi.common.disruptor.DisruptorEventBatchProducer;
import com.legaoyi.common.message.ExchangeMessage;
import com.legaoyi.common.util.DateUtils;
/**
*
* 终端上行消息处理入口
*
* @author <a href="mailto:shengbo.gao@gmail.com;78772895@qq.com">gaoshengbo</a>
* @version 1.0.0
* @since 2015-01-30
*/
@Component("deviceUpMessageHandler")
public class DeviceUpMessageHandler extends MessageHandler {
private static final Logger logger = LoggerFactory.getLogger(DeviceUpMessageHandler.class);
private static final String DEFULT_PROTOCOL_VERSION = "2011";
@Autowired
@Qualifier("deviceService")
private DeviceService deviceService;
@Autowired
@Qualifier("messageBatchSaveProducer")
private DisruptorEventBatchProducer messageBatchSaveProducer;
@Value("${batchSave.threadPool.size}")
private int threadPoolSize = 5;
@Autowired
@Qualifier("cacheManager")
private CacheManager cacheManager;
private ExecutorService fixedThreadPool = null;
@PostConstruct
public void init() {
fixedThreadPool = Executors.newFixedThreadPool(threadPoolSize);
}
@Override
public void handle(ExchangeMessage message) throws Exception {
if (message.getMessageId().equals(ExchangeMessage.MESSAGEID_GATEWAY_UP_MESSAGE)
|| message.getMessageId().equals(ExchangeMessage.MESSAGEID_GATEWAY_UP_MEDIA_MESSAGE)) {
fixedThreadPool.execute(new Runnable() {
@SuppressWarnings("unchecked")
public void run() {
try {
Map<?, ?> map = (Map<?, ?>) message.getMessage();
Map<?, ?> messageHeader = (Map<?, ?>) map.get(Constants.MAP_KEY_MESSAGE_HEADER);
String messageId = (String) messageHeader.get(Constants.MAP_KEY_MESSAGE_ID);
String simCode = (String) messageHeader.get(Constants.MAP_KEY_SIM_CODE);
Map<String, Object> device = deviceService.getDeviceInfo(simCode);
String protocolVersion = null;
if (device != null) {
message.putExtAttribute(Constants.MAP_KEY_DEVICE, device);
protocolVersion = (String) device.get("protocolVersion");
} else {
protocolVersion = DEFULT_PROTOCOL_VERSION;
}
try {
MessageHandler messageHandler = ServerRuntimeContext.getBean(
Constants.ELINK_MESSAGE_STORER_BEAN_PREFIX.concat(messageId).concat("_")
.concat(protocolVersion)
.concat(Constants.ELINK_MESSAGE_STORER_MESSAGE_HANDLER_BEAN_SUFFIX),
MessageHandler.class);
messageHandler.handle(message);
} catch (NoSuchBeanDefinitionException e) {
} catch (Exception e) {
logger.error(" handler message error,message={}", message, e);
}
if (device != null) {
// 保存消息
messageBatchSaveProducer
.produce(new BatchMessage(Constants.BATCH_MESSAGE_DEVICE_UP_MESSAGE, message));
// 流量统计
Integer length = (Integer) map.get("length");
if (length != null) {
updateDataCount((String) device.get(Constants.MAP_KEY_DEVICE_ID), messageId, length);
}
try {
//调用扩展消息处理器,如809消息上报
MessageHandler messageHandler = ServerRuntimeContext.getBean(
Constants.ELINK_MESSAGE_STORER_BEAN_PREFIX.concat(messageId).concat("_ext")
.concat(Constants.ELINK_MESSAGE_STORER_MESSAGE_HANDLER_BEAN_SUFFIX),
MessageHandler.class);
messageHandler.handle(message);
} catch (NoSuchBeanDefinitionException e) {
} catch (Exception e) {
logger.error(" handler message error,message={}", message, e);
}
} else {
// 非法消息
Map<String, Object> messageBody = (Map<String, Object>) map
.get(Constants.MAP_KEY_MESSAGE_BODY);
messageBody.put(Constants.MAP_KEY_MESSAGE_ID, messageId);
messageBody.put("desc", "无设备信息");
Map<String, Object> messageHeader1 = (Map<String, Object>) map
.get(Constants.MAP_KEY_MESSAGE_HEADER);
messageHeader1.put(Constants.MAP_KEY_MESSAGE_ID, "unknown");
messageBatchSaveProducer
.produce(new BatchMessage(Constants.BATCH_MESSAGE_DEVICE_UP_MESSAGE, message));
}
} catch (Exception e) {
logger.error(" handler message error,message={}", message, e);
}
}
});
} else if (getSuccessor() != null) {
getSuccessor().handle(message);
}
}
@SuppressWarnings("unchecked")
private void updateDataCount(String deviceId, String messageId, int length) {
String date = DateUtils.format(new Date(), "MMdd");
String key = deviceId.concat(date);
Cache cache = cacheManager.getCache(com.legaoyi.common.util.Constants.CACHE_NAME_DEVICE_DATA_COUNT_CACHE);
ValueWrapper value = cache.get(key);
Map<String, Object> data = null;
if (value != null) {
data = (Map<String, Object>) value.get();
} else {
data = new HashMap<String, Object>();
}
Integer count = (Integer) data.get(messageId);
if (count == null) {
count = 1;
} else {
count++;
}
data.put(messageId, count);
Integer dataSize = (Integer) data.get("dataSize");
if (dataSize == null) {
dataSize = length;
} else {
dataSize += length;
}
data.put("dataSize", dataSize);
cache.put(key, data);
}
}
|
/**
* (C) Copyright 2005-2009 Yerbabuena Software <http://www.yerbabuena.es>
* Authors: vs@athento.com (Yerbabuena Software)
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* $Id$
*/
package org.athento.nuxeo.rm.restlets;
import static org.jboss.seam.ScopeType.EVENT;
import java.io.Serializable;
import java.util.Collection;
/**
* Conflicto con checkstyle. Es necesario usar el logger de Apache.
*/
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* --------------------------------------------------------
*/
import org.dom4j.dom.DOMDocument;
import org.dom4j.dom.DOMDocumentFactory;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.nuxeo.ecm.core.NXCore;
import org.nuxeo.ecm.core.api.ClientException;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.IdRef;
import org.nuxeo.ecm.core.lifecycle.LifeCycle;
import org.nuxeo.ecm.core.lifecycle.LifeCycleService;
import org.nuxeo.ecm.core.lifecycle.LifeCycleState;
import org.nuxeo.ecm.core.lifecycle.LifeCycleTransition;
import org.nuxeo.ecm.platform.ui.web.api.NavigationContext;
import org.nuxeo.ecm.platform.ui.web.restAPI.BaseNuxeoRestlet;
import org.nuxeo.ecm.platform.ui.web.tag.fn.LiveEditConstants;
import org.nuxeo.ecm.platform.util.RepositoryLocation;
import org.restlet.data.CharacterSet;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.w3c.dom.Element;
/**
*
* Restlet para la extracción del ciclo de vida.
*
*/
@Name("lifeCyclePolicy")
@Scope(EVENT)
public class ExtraerCicloDeVida extends BaseNuxeoRestlet implements
LiveEditConstants, Serializable {
/**
* Constante 'destinationState'.
*/
private static final String DESTINATION_STATE = "destinationState";
/**
* Constante 'transition'.
*/
private static final String TRANSITION = "transition";
/**
* Constante 'transitions'.
*/
private static final String TRANSITIONS = "transitions";
/**
* Constante 'allowedTransition'.
*/
private static final String ALLOWED_TRANSITION = "allowedTransition";
/**
* Constante 'allowedTransitions'.
*/
private static final String ALLOWED_TRANSITIONS = "allowedTransitions";
/**
* Constante 'state'.
*/
private static final String STATE = "state";
/**
* Constante 'states'.
*/
private static final String STATES = "states";
/**
* Constante 'lifeCycle'.
*/
private static final String LIFE_CYCLE = "lifeCycle";
/**
* Constante '*'.
*/
private static final String AN_OBJECT = "*";
/**
* Constante 'docid'.
*/
private static final String DOCID = "docid";
/**
* Constante 'repo'.
*/
private static final String REPO = "repo";
/**
* Constante name.
*/
private static final String NAME = "name";
/**
* Version Serial.
*/
private static final long serialVersionUID = -5354813433902271188L;
/**
* Logger.
*/
private static final Log LOG = LogFactory.getLog(ExtraerCicloDeVida.class);
/**
* Contexto de navegacion.
*/
@In(create = true)
private transient NavigationContext navigationContext;
/**
* Interfaz de la implementación de la sesión.
*/
private transient CoreSession documentManager;
/**
* Interfaz del servicio de ciclos de vida.
*/
private transient LifeCycleService lifeCycleService;
/**
* Manejador principal del restlet.
*
* @param req
* the req
* @param res
* the res
*/
@Override
public void handle(Request req, Response res) {
/* Conflicto con Checkstyle. No se pueden declarar como final los métodos de
* beans EJB que hagan uso de dependencias inyectadas, ya que dichas
* dependencias toman el valor null. No se declara como final debido a que en
* ese caso la inyección de dependencias dejaría de funcionar.
*/
// Getting the repository and the document id of the document
String repo = (String) req.getAttributes().get(REPO);
String docid = (String) req.getAttributes().get(DOCID);
DocumentModel dm = null;
try {
if (repo == null || repo.equals(AN_OBJECT)) {
handleError(res, "Repositorio no especificado.");
throw new ClientException("Repositorio no especificado.");
}
// Getting the document...
navigationContext.setCurrentServerLocation(new RepositoryLocation(
repo));
documentManager = navigationContext.getOrCreateDocumentManager();
if (docid == null || docid.equals(AN_OBJECT)) {
handleError(res, "identificador de documento no especificado");
throw new ClientException("Identificador de documento no"
+ "especificado.");
} else {
dm = documentManager.getDocument(new IdRef(docid));
}
lifeCycleService = NXCore.getLifeCycleService();
String lifeCycleName = dm.getLifeCyclePolicy();
LOG.debug("Ciclo de vida asociado : " + lifeCycleName);
LifeCycle lifeCycle = lifeCycleService
.getLifeCycleByName(lifeCycleName);
Collection<LifeCycleState> states = lifeCycle.getStates();
Collection<LifeCycleTransition> transitions = lifeCycle
.getTransitions();
DOMDocumentFactory domFactory = new DOMDocumentFactory();
DOMDocument result = (DOMDocument) domFactory.createDocument();
Element current = result.createElement(LIFE_CYCLE);
current.setAttribute(NAME, lifeCycleName);
result.setRootElement((org.dom4j.Element) current);
Element statesElement = result.createElement(STATES);
for (LifeCycleState state : states) {
String stateName = state.getName();
Element stateElement = result.createElement(STATE);
stateElement.setAttribute(NAME, stateName);
Element transitionsElement = result
.createElement(ALLOWED_TRANSITIONS);
Collection<String> allowedTransitions = state
.getAllowedStateTransitions();
for (String transitionName : allowedTransitions) {
Element transitionElement = result
.createElement(ALLOWED_TRANSITION);
transitionElement.setAttribute(NAME, transitionName);
transitionsElement.appendChild(transitionElement);
}
stateElement.appendChild(transitionsElement);
statesElement.appendChild(stateElement);
}
current.appendChild(statesElement);
Element transitionsListElement = result
.createElement(TRANSITIONS);
for (LifeCycleTransition transition : transitions) {
Element transitionElement = result.createElement(TRANSITION);
transitionElement.setAttribute(NAME, transition.getName());
transitionsListElement.appendChild(transitionElement);
transitionElement.setAttribute(DESTINATION_STATE,
transition.getDestinationStateName());
}
current.appendChild(transitionsListElement);
res.setEntity(result.asXML(), MediaType.TEXT_XML);
res.getEntity().setCharacterSet(CharacterSet.UTF_8);
} catch (ClientException e) {
LOG.info(
"[RESTLET]Error consultando el ciclo de vida del documento.",
e);
handleError(res, e);
}
/**
* Conflicto con checkstyle. Es necesario capturar la excepción
* Exception, dado que el código nativo de Nuxeo lanza dicha excepción.
* En caso contrario, este código no compilaría
*/
catch (Exception e) {
LOG.error("[RESTLET] Error en la ejecución del restlet ", e);
handleError(res, e);
}
}
}
|
package com.badawy.carservice.utils;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.badawy.carservice.R;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* Created by Mahmoud Badawy 24/3/2020
*/
public class CustomCalendar extends ConstraintLayout {
// Constant Variables
int DAYS_AFTER_TODAY = 1;
// Layout Views
ImageView nextDayBtn;
TextView dateTv;
TextView resetDateTV;
// Global Variables
Calendar calendar;
Date currentDay;
SimpleDateFormat dateFormatter;
SimpleDateFormat timeFormatter;
SimpleDateFormat yearFormatter;
// Constructor
public CustomCalendar(Context context, AttributeSet attrs) {
super(context, attrs);
initControl(context, attrs);
}
// Initialize Component Control
private void initControl(Context context, AttributeSet attrs) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.component_custom_calendar, this);
initUi();
calendar = Calendar.getInstance();
currentDay = calendar.getTime();
dateFormatter = new SimpleDateFormat("EEEE, d MMMM", Locale.ENGLISH);
timeFormatter = new SimpleDateFormat("h:mm", Locale.ENGLISH);
yearFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
dateTv.setText(dateFormatter.format(currentDay));
}
public String getTimeOfDay(){
int timeOfDay = calendar.get(Calendar.AM_PM);
if (timeOfDay == Calendar.AM){
return "am";
}
else {
return "pm";
}
}
public void setArrowClick(OnClickListener listener){
nextDayBtn.setOnClickListener(listener);
}
public void setResetDayClick(OnClickListener listener){
resetDateTV.setOnClickListener(listener);
}
// Initialize Views
private void initUi() {
resetDateTV = findViewById(R.id.customCalendar_resetDate);
nextDayBtn = findViewById(R.id.customCalendar_nextDay);
dateTv = findViewById(R.id.customCalendar_date);
}
public String getDay(){
return dateFormatter.format(calendar.getTime());
}
// Reset the calender to show Today`s Date
public void resetDate() {
calendar.setTime(currentDay);
dateTv.setText(dateFormatter.format(currentDay));
}
// Get the next day from the calendar
public void getNextDay() {
calendar.getTimeInMillis();
calendar.add(Calendar.DAY_OF_YEAR, DAYS_AFTER_TODAY);
dateTv.setText(dateFormatter.format(calendar.getTime()));
}
public String getTime() {
return timeFormatter.format(calendar.getTime());
}
public String getDateInYearFormat() {
return yearFormatter.format(calendar.getTime());
}
}
|
package slimeknights.tconstruct.gadgets.client;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.RenderItem;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.entity.RenderSnowball;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.client.registry.IRenderFactory;
import javax.annotation.Nonnull;
import slimeknights.tconstruct.gadgets.TinkerGadgets;
import slimeknights.tconstruct.gadgets.entity.EntityThrowball;
public class RenderThrowball extends RenderSnowball<EntityThrowball> {
public static final IRenderFactory<EntityThrowball> FACTORY = new Factory();
public RenderThrowball(RenderManager renderManagerIn, Item p_i46137_2_, RenderItem p_i46137_3_) {
super(renderManagerIn, p_i46137_2_, p_i46137_3_);
}
@Nonnull
@Override
public ItemStack getStackToRender(EntityThrowball entityIn) {
if(entityIn.type != null) {
return new ItemStack(item, 1, entityIn.type.ordinal());
}
return ItemStack.EMPTY;
}
private static class Factory implements IRenderFactory<EntityThrowball> {
@Override
public Render<? super EntityThrowball> createRenderFor(RenderManager manager) {
return new RenderThrowball(manager, TinkerGadgets.throwball, Minecraft.getMinecraft().getRenderItem());
}
}
}
|
package com.entity.entities;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;
import java.util.List;
public class ClassificationResponse implements Serializable {
private static final long serialVersionUID = -1027333772123933415L;
@JsonProperty("entity")
@JsonInclude(JsonInclude.Include.NON_NULL)
private String entity;
@JsonProperty("entityClass")
@JsonInclude(JsonInclude.Include.NON_NULL)
private Object entityClass;
@JsonProperty("score")
@JsonInclude(JsonInclude.Include.NON_NULL)
private String score;
public ClassificationResponse() {
}
public ClassificationResponse(String entity, Object entityClass, String score) {
this.entity = entity;
this.entityClass = entityClass;
this.score = score;
}
public String getEntity() {
return entity;
}
public void setEntity(String entity) {
this.entity = entity;
}
public Object getEntityClass() {
return entityClass;
}
public void setEntityClass(Object entityClass) {
this.entityClass = entityClass;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
public static String toPercentage(Double number) {
return Math.ceil(number * 100) + "%";
}
}
|
package Study2;
import java.util.*;
public class S5 {
public static void main(String[] args){
HashMap<Integer, String> Sites = new HashMap<>();
Sites.put(1,"one");
Sites.put(2,"two");
Sites.put(3,"three");
Sites.put(4,"four");
System.out.println(Sites);
}
}
|
package madeinbrazil;
import java.util.List;
/**
*
* @author Daniel Machado
* @author Eduardo Mallmann
*/
public class main {
public static void main(String[] args) {
//Criando DB
System.out.println("Criando Database...");
try {
StartDBDataSource.criarBd();
} catch (Exception e) {
System.out.println(e.getMessage());
}
//Criando DAO
InstrumentoDAODTOderby dao = new InstrumentoDAODTOderby();
//Inserindo elementos no DB
System.out.println("Inserindo dados na tabela...");
try {
dao.inserir(new InstrumentoDTO("001", "GUITARRA", "SG SPECIAL FADED WORN CHERRY", "VINHO (WORN CHERRY) (WC)", "GIBSON", 5599.00));
dao.inserir(new InstrumentoDTO("002", "GUITARRA", "SG FADED 2016 T", "MARROM (WORN BROWN) (WB)", "GIBSON", 8989.00));
dao.inserir(new InstrumentoDTO("003", "GUITARRA", "SG FADED 2016 T", "VINHO (WORN CHERRY) (WC)", "GIBSON", 8989.00));
dao.inserir(new InstrumentoDTO("004", "GUITARRA", "SG STANDARD 2014 MIN-ETUNE", "MARROM (WALNUT) (592)", "GIBSON", 9229.00));
dao.inserir(new InstrumentoDTO("005", "GUITARRA", "LES PAUL 50S TRIBUTE 2016 T", "PRETO (SATIN EBONY) (SE)", "GIBSON", 9549.00));
} catch (Exception e) {
System.out.println(e.getMessage());
}
//Listando todos instrumentos
System.out.println();
System.out.println("Listando todos os intrumentos da tabela:");
try {
List<InstrumentoDTO> list = dao.buscarTodos();
System.out.println("PID TIPO MODELO COR MARCA PRECO");
for (InstrumentoDTO instrumento : list) {
System.out.println(instrumento.toString());
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
//Buscar por PID = 1
System.out.println();
System.out.println("Listando instrumento com PID = 1:");
try {
InstrumentoDTO instrumento = dao.buscarPorPID(1);
System.out.println("PID TIPO MODELO COR MARCA PRECO");
System.out.println(instrumento.toString());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
|
package com.kharis.expense.tracker.model.response;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class CategoryResponse {
private Long categoryId;
private String categoryName;
private String categoryDesc;
private Date createdAt;
private Date updatedAt;
}
|
/*
package com.wy.test.config;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
*/
/**
* @author wenyang
* @description TODO
* @since 2019/12/26 9:40
*//*
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {
public void addResourceHandlers(ResourceHandlerRegistry registry){
registry.addResourceHandler("/templates/blog")
.addResourceLocations("classpath:/templates/blog/");
super.addResourceHandlers(registry);
}
}
*/
|
package de.fu_berlin.cdv.chasingpictures.api;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.List;
/**
* Class to receive results from searching for places.
* @author Simon Kalt
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class PlacesApiResult extends ApiResult<List<Place>> {
public List<Place> getPlaces() {
return getData();
}
public void setPlaces(List<Place> places) {
setData(places);
}
}
|
package Schnittstellen;
import java.io.File;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import com.kellnersystem.artikelliste.Artikelliste;
import com.kellnersystem.main.Kellnersystem;
import com.sun.jersey.api.client.*;
public class RestSchnittstelle
{
static String restURI = "http://localhost:8080";
static JAXBContext jc;
static Marshaller marshaller;
static Unmarshaller unmarshaller;
public void deleteBestellung(int tischNummer, int bestellNummer) {
String uri = restURI + "/tisch/" + tischNummer + "/bestellung/" + bestellNummer;
WebResource wrs = Client.create().resource(uri);
wrs.delete();
}
public void deleteBestellung(int tischNummer) {
String uri = restURI + "/tisch/" + tischNummer + "/bestellung";
WebResource wrs = Client.create().resource(uri);
wrs.delete();
}
public void postBestellung(Kellnersystem.Tisch.Bestellungen.Bestellung bs, int tischId) {
String uri = restURI + "/tisch/" + tischId + "/bestellung/";
WebResource wrs = Client.create().resource( uri );
Kellnersystem ks = new Kellnersystem();
ks.getTisch().add(new Kellnersystem.Tisch());
ks.getTisch().get(0).setBestellungen(new Kellnersystem.Tisch.Bestellungen());
ks.getTisch().get(0).getBestellungen().getBestellung().add(bs);
String result = wrs.type(MediaType.TEXT_XML).accept(MediaType.TEXT_XML).post(String.class, ks );
//System.out.println(result);
}
public Kellnersystem getTisch() {
String uri = restURI + "/tisch";
WebResource wrs = Client.create().resource(uri);
return wrs.accept(MediaType.TEXT_XML).get(Kellnersystem.class);
}
public Kellnersystem.Tisch.Bestellungen getBestellungen(int tischNummer) {
String uri = restURI + "/tisch/" + tischNummer + "/bestellung";
WebResource wrs = Client.create().resource( uri );
File ergebnisGetZahlvorgang = wrs.accept(MediaType.TEXT_XML).get(File.class);
//System.out.println("" + ergebnisGetZahlvorgang.toString());
Kellnersystem ts = wrs.accept(MediaType.TEXT_XML).get(Kellnersystem.class);
return ts.getTisch().get(0).getBestellungen();
}
public Kellnersystem.Tisch.Bestellungen.Bestellung getBestellung(int tischNummer, int bestellNummer) {
String uri = restURI + "/tisch/" + tischNummer + "/bestellung/" + bestellNummer;
WebResource wrs = Client.create().resource(uri);
Kellnersystem ks = wrs.accept(MediaType.TEXT_XML).get(Kellnersystem.class);
return ks.getTisch().get(0).getBestellungen().getBestellung().get(0);
}
public void postArtikel(Artikelliste.Artikel ar) {
String uri = restURI + "/artikel/";
WebResource wrs = Client.create().resource(uri);
Artikelliste al = new Artikelliste();
al.getArtikel().add(ar);
String result =wrs.type(MediaType.TEXT_XML).accept(MediaType.TEXT_XML).post(String.class, al);
//System.out.println(result);
}
public void putArtikel(Artikelliste.Artikel ar, int artikelId) {
String uri = restURI + "/artikel/" + artikelId;
WebResource wrs = Client.create().resource(uri);
Artikelliste al = new Artikelliste();
al.getArtikel().add(ar);
wrs.type(MediaType.TEXT_XML).accept(MediaType.TEXT_XML).put(String.class, al);
}
public Artikelliste getArtikel() {
String uri = restURI + "/artikel/";
WebResource wrs = Client.create().resource(uri);
return wrs.accept(MediaType.TEXT_XML).get(Artikelliste.class);
}
}
|
package com.example.testproject.setting;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.example.testproject.R;
public class CallForwardingActivity extends AppCompatActivity {
public static void start(Context context) {
context.startActivity(new Intent(context, CallForwardingActivity.class));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call_forwarding);
getWindow().setStatusBarColor(Color.parseColor("#FA00D43B"));
}
}
|
//@ObjectsPackage(namespace = WS_OBJECTS_NAMESPACE)
//@XmlSchema(
// namespace = WS_OBJECTS_NAMESPACE + "/WebService",
// elementFormDefault = XmlNsForm.QUALIFIED,
// location = WS_OBJECTS_NAMESPACE + "/WebService.xsd"
//)
package com.db.persistence.wsSoap;
|
package seedbed.unitTest;
import org.apache.log4j.Logger;
import org.testng.annotations.Test;
import org.testng.Assert;
/**
* <b>Description:</b> Class that has the unit test for CU1050 gestionar operaciones
* <b>Use case:</b> CU1050 gestionar operaciones
* @author Andrés Cruz
*/
public class ArithmeticOperationsTest {
private final static Logger Log = Logger.getLogger(ArithmeticOperationsTest.class);
@Test
public void validateSumResultSucces() {
Log.info("Begins running validateSumResultSucces()");
int number1 = 300;
int number2 = 150;
int result = 450;
//Assert.assertFalse(number1+number2==result);
Assert.assertTrue(number1+number2==result);
}
}
|
package edu.mit.cci.simulation.excel.responsesurfaces;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
/**
* User: jintrone
* Date: 2/25/11
* Time: 7:42 AM
*/
public class SimpleResponseSurfaceTest {
Polynomial p = new Polynomial(new double[]{4, 5});
SliceSegment<Float, Integer> s1 = new SliceSegment<Float, Integer>(3f, 4f, 100, p);
SliceSegment<Float, Integer> s2 = new SliceSegment<Float, Integer>(4f, 5f, 103, p);
SliceSegment<Float, Integer> s3 = new SliceSegment<Float, Integer>(1f, 2f, 1, p);
SliceSegment<Float, Integer> s4 = new SliceSegment<Float, Integer>(3f, 6f, 2, p);
SliceSegment<Float, Integer> s5 = new SliceSegment<Float, Integer>(1f, 2f, 100, p);
SliceSegment<Float, Integer> s6 = new SliceSegment<Float, Integer>(3f, 6f, 103, p);
Slice<Float, Integer> sl1 = new Slice<Float, Integer>();
Slice<Float, Integer> sl2 = new Slice<Float, Integer>();
Slice<Float, Integer> sl3 = new Slice<Float, Integer>();
{
sl1.add(s2);
sl1.add(s1);
sl2.add(s3);
sl2.add(s4);
sl3.add(s5);
sl3.add(s6);
}
@Test
public void testInvalidCheck() throws Exception {
SimpleResponseSurface<Float,Integer> rs = new SimpleResponseSurface<Float, Integer>();
rs.addSlice(sl1);
try {
rs.addSlice(sl2);
Assert.fail("Should disallow adding slices with different indices");
} catch (IllegalArgumentException ex) {
}
}
@Test
public void testReset() throws Exception {
SimpleResponseSurface<Float,Integer> rs = new SimpleResponseSurface<Float, Integer>();
rs.addSlice(sl1);
rs.removeSlice(sl1);
rs.addSlice(sl2);
}
@Test
public void testOrdering() throws Exception {
SimpleResponseSurface<Float,Integer> rs = new SimpleResponseSurface<Float, Integer>();
rs.addSlice(sl3);
rs.addSlice(sl1);
Assert.assertTrue(rs.getSlices().indexOf(sl1)<rs.getSlices().indexOf(sl3));
}
@Test
public void testCrosswiseGet() throws Exception {
SimpleResponseSurface<Float,Integer> rs = new SimpleResponseSurface<Float, Integer>();
rs.addSlice(sl3);
rs.addSlice(sl1);
Assert.assertNull(rs.getAtIndex(1));
List<SliceSegment<Float,Integer>> segs = rs.getAtIndex(100);
Assert.assertTrue(segs.size()==2);
Assert.assertSame(segs.get(0),s1);
Assert.assertSame(segs.get(1),s5);
}
}
|
// Binary Search in Java
//Author: Diana Mascarenhas
package arrays;
import java.util.Arrays;
import java.util.Scanner;
public class binarySearch
{
public static void main(String args[])
{
Search obj= new Search();
int a[]= {14,1,19,34,-4,9,87,2};
Scanner sc= new Scanner(System.in);
System.out.println("Enter element to be searched");
int search = sc.nextInt();
Arrays.sort(a);
System.out.println("Sorted array is as shown:");
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
System.out.println();
int x = obj.binSearch(a, 0, a.length-1, search);
if(x== -1)
System.out.println("Element Not found");
else
System.out.println("Element Found at "+x);
}
}
class Search
{
public int binSearch(int a[], int low, int high, int x)
{
int mid;
if(high>=low)
{
mid = low +(high-1)/2;
if(a[mid]==x)
return mid;
else if(x>a[mid])
return binSearch(a, mid+1, high, x);
else
return binSearch(a, low, mid-1, x);
}
return -1;
}
}
|
package sd.service;
/**
* This is a simple Calculator class that
* has four public methods that will be used
* as an Axis2 Web Service.
*
* @author Shane Doyle <iamshanedoyle>
*/
public class Calculator {
private double result = 0;
/**
* This method is used for adding two values and
* it returns the result.
* @param value1
* @param value2
* @return
*/
public double Add(double value1, double value2) {
if(validValues(value1, value2)) {
result = value1 + value2;
}
return result;
}
/**
* This method is used for dividing two values and
* it returns the result.
* @param value1
* @param value2
* @return
*/
public double Divide(double value1, double value2) {
if(validValues(value1, value2)) {
result = value1 / value2;
}
return result;
}
/**
* This method is used for multiplying two values and
* it returns the result.
* @param value1
* @param value2
* @return
*/
public double Multiply(double value1, double value2) {
if(validValues(value1, value2)) {
result = value1 * value2;
}
return result;
}
/**
* This method is used for subtracting two values and
* it returns the result.
* @param value1
* @param value2
* @return
*/
public double Subtract(double value1, double value2) {
if(validValues(value1, value2)) {
result = value1 - value2;
}
return result;
}
/**
* This method is used to check if the values are valid.
* @param value1
* @param value2
* @return
*/
private boolean validValues(double value1, double value2) {
if(value1==0.00&&value2==0.0) {
return false;
} else {
return true;
}
}
}
|
package com.xld.common.validator;
import com.baidu.unbiz.fluentvalidator.Validator;
import com.baidu.unbiz.fluentvalidator.ValidatorChain;
import com.xld.common.other.StrUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/**
* 字符串校验链
* @author sjl
*/
public class StringValidatorChainFactor {
/**
* 默认校验字段名
*/
private static final String FIELD_NAME = "该字段";
/**
* 是否允许为空
* true 允许为空 false 不允许
*/
private static final boolean IS_ALLOW_NULL = false;
/**
* 默认校验规则 允许中英文 数字 下划线
*/
private static final Pattern DEFAULT = PatternUtil.CHINESE_ENGLISH;
/**
* 默认最小长度
*/
private static final int MIN_LENGTH = 1;
/**
* 默认最大长度
*/
private static final int MAX_LENGTH = Integer.MAX_VALUE;
/**
* 获取校验链
* @param filedName
*/
public static ValidatorChain getValidatorChain(String filedName) {
return getValidatorChain(filedName, IS_ALLOW_NULL, DEFAULT, MIN_LENGTH, MAX_LENGTH);
}
/**
* 获取校验链
* @param filedName
*/
public static ValidatorChain getValidatorChain(String filedName, boolean isAllowNull) {
return getValidatorChain(filedName, isAllowNull, DEFAULT, MIN_LENGTH, MAX_LENGTH);
}
/**
* 获取校验链
* @param filedName
*/
public static ValidatorChain getValidatorChain(String filedName, Pattern pattern) {
return getValidatorChain(filedName, IS_ALLOW_NULL, pattern, MIN_LENGTH, MAX_LENGTH);
}
/**
* 获取校验链
* @param filedName
*/
public static ValidatorChain getValidatorChain(String filedName, int minLength, int maxLength) {
return getValidatorChain(filedName, IS_ALLOW_NULL, DEFAULT, minLength, maxLength);
}
/**
* 获取校验链
* @param filedName
*/
public static ValidatorChain getValidatorChain(String filedName, Pattern pattern, int minLength, int maxLength) {
return getValidatorChain(filedName, IS_ALLOW_NULL, pattern, minLength, maxLength);
}
/**
* 获取校验链
* @param filedName
*/
public static ValidatorChain getValidatorChain(String filedName, boolean isAllowNull,
Pattern pattern, int minLength, int maxLength) {
if (StrUtil.isEmpty(filedName)) {
filedName = FIELD_NAME;
}
ValidatorChain chain = new ValidatorChain();
List<Validator> validators = new ArrayList<>();
if (pattern != null) {
validators.add(new StringRuleValidator(filedName, isAllowNull, pattern));
}
validators.add(new StringLengthValidator(filedName, isAllowNull, minLength, maxLength));
chain.setValidators(validators);
return chain;
}
}
|
package com.example.tarena.protop.util;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* 作者:Linqiang
* 时间:2016/5/18:20:24
* 邮箱: linqiang2010@outlook.com
* 说明:
*/
public class DBHelper extends SQLiteOpenHelper {
private static DBHelper instance;
public static DBHelper getInstance(Context context){
instance= new DBHelper(context);
return instance;
}
public DBHelper(Context context) {
super(context, "news.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
/**
* _id : 57334c9d67765903fb61c418
* createdAt : 2016-05-11T23:15:41.98Z
* desc : 还在用ListView?
* publishedAt : 2016-05-12T12:04:43.857Z
* source : web
* type : Android
* url : http://www.jianshu.com/p/a92955be0a3e
* used : true
* who : 陈宇明
*/
//Android表
String sql = "create table tb_android(_id integer primary key autoincrement,wid text ,createdAt integer not null ," +
"desc text not null, publishedAt integer not null,source text ,type text ,url text,used integer ,who text,read integer,fav integer )";
db.execSQL(sql);
//ios表
String sql2 = "create table tb_ios(_id integer primary key autoincrement,wid text ,createdAt integer not null ," +
"desc text not null, publishedAt integer not null,source text ,type text ,url text,used integer ,who text ,read integer,fav integer)";
db.execSQL(sql2);
//web表
String sql3 = "create table tb_web(_id integer primary key autoincrement,wid text ,createdAt integer not null ," +
"desc text not null, publishedAt integer not null,source text ,type text ,url text,used integer ,who text,read integer ,fav integer)";
db.execSQL(sql3);
//tools表
String sql4 = "create table tb_tools(_id integer primary key autoincrement,wid text ,createdAt integer not null ," +
"desc text not null, publishedAt integer not null,source text ,type text ,url text,used integer ,who text ,read integer,fav integer)";
db.execSQL(sql4);
//已阅读过的文章
String sql5 = "create table tb_read(_id integer primary key autoincrement,wid text ,createdAt integer not null ," +
"desc text not null, publishedAt integer not null,source text ,type text ,url text,used integer ,who text ,read integer,fav integer)";
db.execSQL(sql5);
//我的收藏
String sql6 = "create table tb_favo(_id integer primary key autoincrement,wid text ,createdAt integer not null ," +
"desc text not null, publishedAt integer not null,source text ,type text ,url text,used integer ,who text ,read integer,fav integer)";
db.execSQL(sql6);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
|
//
// Decompiled by Procyon v0.5.36
//
package com.davivienda.multifuncional.tablas.totalesestacionmultifuncional.servicio;
import javax.persistence.Query;
import com.davivienda.sara.base.exception.EntityServicioExcepcion;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Collection;
import java.util.Calendar;
import javax.persistence.EntityManager;
import com.davivienda.sara.base.AdministracionTablasInterface;
import com.davivienda.sara.entitys.Totalesestacionmultifuncional;
import com.davivienda.sara.base.BaseEntityServicio;
public class TotalesEstacionMultiSessionServicio extends BaseEntityServicio<Totalesestacionmultifuncional> implements AdministracionTablasInterface<Totalesestacionmultifuncional>
{
public TotalesEstacionMultiSessionServicio(final EntityManager em) {
super(em, Totalesestacionmultifuncional.class);
}
public Collection<Totalesestacionmultifuncional> getTotalesEstacionMultiRangoFecha(final Calendar fechaInicial, final Calendar fechaFinal) throws EntityServicioExcepcion {
Collection<Totalesestacionmultifuncional> regs = null;
try {
Query query = null;
query = this.em.createNamedQuery("Totalesestacionmultifuncional.Fecha");
query.setParameter("fechaInicial", (Object)fechaInicial.getTime());
query.setParameter("fechaFinal", (Object)fechaFinal.getTime());
regs = (Collection<Totalesestacionmultifuncional>)query.getResultList();
}
catch (IllegalStateException ex) {
Logger.getLogger("globalApp").log(Level.SEVERE, "No se tiene acceso a la unidad de persistencia ", ex);
throw new EntityServicioExcepcion(ex);
}
catch (IllegalArgumentException ex2) {
Logger.getLogger("globalApp").log(Level.WARNING, "El par\u00e1metro no es v\u00e1lido ", ex2);
throw new EntityServicioExcepcion(ex2);
}
System.out.println(("TotalesEstacionMultiSessionServicio.getTotalesEstacionMultiRangoFecha(): regs " + regs != null) ? regs.size() : 0);
return regs;
}
}
|
package jp.ac.sojou.izumi.chikaken.synthesizerui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ModuleEditor extends JDialog {
private static final long serialVersionUID = 2818457378573720117L;
private Module module;
private MyPanel myPanel;
public ModuleEditor(Module m, MyPanel mp) {
this.module = m;
this.myPanel = mp;
setModal(true);
final JTextField nameField = new JTextField(m.name);
JButton applyButton = new JButton("Apply");
applyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
applyAction(nameField);
}
});
nameField.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
if (KeyEvent.VK_ENTER == e.getKeyCode()) {
applyAction(nameField);
}
}
});
JButton deleteButton = new JButton("Delete");
deleteButton.setForeground(Color.RED);
deleteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
myPanel.deleteModule(module);
setVisible(false);
myPanel.repaint();
}
});
setLayout(new BorderLayout());
add(new JLabel("Name:"), BorderLayout.WEST);
add(nameField, BorderLayout.CENTER);
JPanel buttons = new JPanel();
buttons.add(applyButton);
buttons.add(deleteButton);
add(buttons, BorderLayout.SOUTH);
pack();
}
private void applyAction(final JTextField nameField) {
module.name = nameField.getText();
setVisible(false);
myPanel.repaint();
}
}
|
package com.example.Bank_App_5.models;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public abstract class BankAccount {
public double balance;
public double interestRate;
public long accountNumber;
public Date accountOpenedOn = null;
private List<Transaction> transactions = new ArrayList<Transaction>();
/* >------------BankAccount Constructors--------------------< */
public BankAccount() {
}
public BankAccount(double balance, double interestRate) {
this.balance = balance;
this.interestRate = interestRate;
this.accountOpenedOn = new Date();
this.accountNumber = MeritBank.getNextAccountNumber();
}
public BankAccount(double balance, double interestRate, Date accountOpenedOn) {
this.balance = balance;
this.interestRate = interestRate;
this.accountOpenedOn = accountOpenedOn;
}
// >-----------------AccountNumber----------------------<
public BankAccount(long accountNumber, double balance, double interestRate, Date accountOpenedOn) {
this.balance = balance;
this.interestRate = interestRate;
this.accountOpenedOn = accountOpenedOn;
this.accountNumber = accountNumber;
}
public long getAccountNumber() {
return accountNumber;
}
public long setAccountNumber() {
return this.accountNumber;
}
public double getBalance() {
return balance;
}
public double getInterestRate() {
return interestRate;
}
public Date getOpenedOn() {
return accountOpenedOn;
}
public boolean withdraw(double amount) {
if (balance <= amount) {
System.out.println("Sorry you do not have that much in your account you have $" + balance);
return false;
} else {
balance -= amount;
System.out.println("Your new balance is $" + balance);
return true;
}
}
public boolean deposit(double amount) {
if (0 < amount) {
System.out.println("Deposit bank: " + amount);
this.balance = this.balance + amount;
return true;
} else
System.out.println(" more than 250000");
return false;
}
public double futureValue(int years) {
System.out.println("This is FV Debugg" + this.balance + " " + this.interestRate);
double value = 0.00;
double powered = Math.pow((1 + interestRate), years);
// double fv = 100.0 * Math.pow(1 + 0.01, 3);
value = balance * powered;
return value;
}
public void addTransaction(Transaction transaction) {
this.transactions.add(transaction);
}
public List<Transaction> getTransactions() {
return transactions;
}
public String writeToString() {
StringBuilder accountData = new StringBuilder();
accountData.append(accountNumber).append(",");
accountData.append(accountOpenedOn).append(",");
accountData.append(balance).append(",");
accountData.append(interestRate);
return accountData.toString();
}
}
|
package com.gxjtkyy.standardcloud.admin.service.impl;
import com.gxjtkyy.standardcloud.admin.domain.vo.DocVO;
import com.gxjtkyy.standardcloud.admin.domain.vo.request.QueryDocPageReq;
import com.gxjtkyy.standardcloud.admin.service.DocService;
import com.gxjtkyy.standardcloud.admin.service.TemplateService;
import com.gxjtkyy.standardcloud.common.constant.DocConstant;
import com.gxjtkyy.standardcloud.common.constant.DocTemplate;
import com.gxjtkyy.standardcloud.common.domain.Page;
import com.gxjtkyy.standardcloud.common.domain.dto.BriefDocDTO;
import com.gxjtkyy.standardcloud.common.domain.dto.DetailDocDTO;
import com.gxjtkyy.standardcloud.common.domain.dto.TemplateDTO;
import com.gxjtkyy.standardcloud.common.domain.vo.DocRequestVO;
import com.gxjtkyy.standardcloud.common.domain.vo.ResponseVO;
import com.gxjtkyy.standardcloud.common.exception.BaseException;
import com.gxjtkyy.standardcloud.common.exception.DocException;
import com.gxjtkyy.standardcloud.common.parser.StandDocParser;
import com.mongodb.WriteResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
import static com.gxjtkyy.standardcloud.common.constant.ResultCode.*;
/**
* @Package com.gxjtkyy.standardcloud.admin.service.impl
* @Author lizhenhua
* @Date 2018/6/28 8:22
*/
@Slf4j
@Service
public class DocServiceImpl implements DocService{
@Autowired
private MongoTemplate mongoTemplate;
@Autowired
private TemplateService templateService;
@Override
public void addDoc(String name, String templateId, String docPath) throws BaseException {
//查询模板是否存在
TemplateDTO template = templateService.getTemplateById(templateId);
DetailDocDTO detailDoc = new StandDocParser(template, docPath).doParse(name);
String tableName = DocTemplate.getTemplateByType(detailDoc.getDocType()).getTableName();
BriefDocDTO briefDoc = new BriefDocDTO(detailDoc);
mongoTemplate.insert(detailDoc, tableName);
mongoTemplate.insert(briefDoc, DocConstant.COLLECTION_DOC_STAND_CATALOG);
}
@Override
public ResponseVO getListByPage(QueryDocPageReq request) throws DocException {
ResponseVO response = new ResponseVO();
Page<DocVO> page = new Page<>();
Criteria criteria = new Criteria();
if(!StringUtils.isEmpty(request.getDocId())){
criteria.and("_id").is(request.getDocId());
}
if(!StringUtils.isEmpty(request.getDocName())){
criteria.and("docName").regex(request.getDocName());
}
if(null != request.getDocType()){
criteria.and("docType").is(request.getDocType());
}
Query query = new Query(criteria);
//查询总数
int count = (int) mongoTemplate.count(query, BriefDocDTO.class, DocConstant.COLLECTION_DOC_STAND_CATALOG);
page.setCount(count);
//排序
query.with(new Sort(Sort.Direction.DESC, "viewCount"));
int start = (request.getCurrentPage() - 1) * request.getPageSize();
query.skip(start).limit(request.getPageSize());
//skip方法是跳过条数,而且是一条一条的跳过,如果集合比较大时(如书页数很多)skip会越来越慢, 需要更多的处理器(CPU),这会影响性能。后续升级改用Morphia框架
List<BriefDocDTO> list = mongoTemplate.find(query, BriefDocDTO.class, DocConstant.COLLECTION_DOC_STAND_CATALOG);
List<DocVO> docVOS = new ArrayList<>();
for(BriefDocDTO briefDoc : list){
DocVO vo = new DocVO();
vo.setDocType(briefDoc.getDocType());
vo.setCreateTime(briefDoc.getCreateTime());
vo.setDocId(briefDoc.getDocId());
vo.setDocName(briefDoc.getDocName());
docVOS.add(vo);
}
page.setCurrentPage(request.getCurrentPage());
page.setPageSize(request.getPageSize());
page.setDataList(docVOS);
response.setData(page);
return response;
}
@Override
public ResponseVO deleteDoc(DocRequestVO request) throws DocException {
Criteria criteria = new Criteria("_id");
criteria.is(request.getDocId());
Query query = new Query(criteria);
BriefDocDTO briefDoc = mongoTemplate.findOne(query, BriefDocDTO.class, DocConstant.COLLECTION_DOC_STAND_CATALOG);
if (null == briefDoc) {
log.error("摘要表中查询不到文档 --> id: {}", request.getDocId());
throw new DocException(RESULT_CODE_1007, RESULT_DESC_1007);
}
new Criteria("_id").is(request.getDocId());
WriteResult result = mongoTemplate.remove(new Query(criteria), DocTemplate.getTemplateByType(briefDoc.getDocType()).getTableName());
if(result.getN() > 0){
mongoTemplate.remove(new Query(criteria),DocConstant.COLLECTION_DOC_STAND_CATALOG);
return new ResponseVO();
}
ResponseVO response = new ResponseVO();
response.setCode(RESULT_CODE_9999);
response.setMsg(RESULT_DESC_9999);
return response;
}
}
|
package com.jfronny.raut.gui;
import com.jfronny.raut.RaUt;
import dev.emi.trinkets.api.TrinketsApi;
import io.github.cottonmc.cotton.gui.CottonCraftingController;
import io.github.cottonmc.cotton.gui.widget.WGridPanel;
import io.github.cottonmc.cotton.gui.widget.WItemSlot;
import io.github.cottonmc.cotton.gui.widget.WLabel;
import io.github.cottonmc.cotton.gui.widget.WPlayerInvPanel;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.Inventory;
import net.minecraft.item.ItemStack;
import net.minecraft.recipe.RecipeType;
import net.minecraft.text.Text;
import net.minecraft.text.TranslatableText;
public class BackpackController extends CottonCraftingController {
ItemStack theStack;
public BackpackController(int syncId, PlayerInventory playerInventory, ItemStack stack, int size, int slotNumber) {
super(RecipeType.SMELTING, syncId, playerInventory);
theStack = stack;
this.playerInventory = playerInventory;
Inventory inv;
if (slotNumber == -1) {
inv = TrinketsApi.getTrinketsInventory(playerInventory.player);
for (int i = 0; i < inv.getInvSize(); i++) {
if (inv.getInvStack(i).isItemEqual(stack)) {
slotNumber = i;
}
}
} else {
inv = playerInventory;
}
this.blockInventory = new BackpackInventory(theStack, BackpackInventory.Size.values()[size], inv, slotNumber);
WGridPanel rootPanel = (WGridPanel) getRootPanel();
Text label = stack.hasCustomName() ? stack.getName() : new TranslatableText("gui." + RaUt.MOD_ID + ".backpack");
rootPanel.add(new WLabel(label, WLabel.DEFAULT_TEXT_COLOR), 0, 0);
int rows = (int) Math.ceil(blockInventory.getInvSize() / 9.0);
for (int i = 1; i <= rows; i++) {
for (int j = 0; j < 9; j++) {
WItemSlot slot = WItemSlot.of(blockInventory, ((i - 1) * 9) + j);
rootPanel.add(slot, j, i);
}
}
rootPanel.add(new WLabel(new TranslatableText("container.inventory"), WLabel.DEFAULT_TEXT_COLOR), 0, rows + 1);
WPlayerInvPanel playerInv = this.createPlayerInventoryPanel();
//playerInv.
rootPanel.add(playerInv, 0, rows + 2);
rootPanel.validate(this);
}
@Override
public int getCraftingResultSlotIndex() {
return -1;
}
}
|
package com.tandon.tanay.locationtracker.ui.base;
import android.content.Context;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.tandon.tanay.locationtracker.LocationTracker;
public abstract class BaseActivity extends AppCompatActivity implements BaseView {
private LocationTracker locationTracker;
private Snackbar snackbar;
@Override
public void showErrorMessage(View view, int messageResId) {
showErrorMessage(view, messageResId, -1, null);
}
@Override
public void showErrorMessage(View view, int messageResId, int actionResId, View.OnClickListener clickListener) {
dismissSnackbar();
if (view != null) {
snackbar = Snackbar.make(view, messageResId, Snackbar.LENGTH_INDEFINITE);
if (actionResId != -1 && clickListener != null) {
snackbar.setAction(actionResId, clickListener);
}
snackbar.show();
}
}
@Override
public void dismissSnackbar() {
if (snackbar != null) {
snackbar.dismiss();
}
}
@Override
public Context getViewContext() {
return this;
}
public BaseActivity getBaseActivity() {
return this;
}
public LocationTracker getApp() {
if (locationTracker == null) {
locationTracker = (LocationTracker) getApplicationContext();
}
return locationTracker;
}
}
|
/*
* 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 vista;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.JTextField;
/**
*
* @author Sergio Cruz
*/
public class VentanaRegistrar extends javax.swing.JInternalFrame {
/**
* Creates new form VentanaRegistrar
*/
public VentanaRegistrar() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
lblNro = new javax.swing.JLabel();
spr1 = new javax.swing.JSeparator();
lblFecha = new javax.swing.JLabel();
lblIdentificacion = new javax.swing.JLabel();
lblNombre = new javax.swing.JLabel();
lblDatosPaciente = new javax.swing.JLabel();
lblDireccion = new javax.swing.JLabel();
lblTelefono = new javax.swing.JLabel();
lblAfilicion = new javax.swing.JLabel();
txtNombre = new javax.swing.JTextField();
txtIdentificacion = new javax.swing.JTextField();
txtDireccion = new javax.swing.JTextField();
txtTelefono = new javax.swing.JTextField();
cmbAfiliacion = new javax.swing.JComboBox<>();
txtNro = new javax.swing.JTextField();
txtDia = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
txtMes = new javax.swing.JTextField();
jLabel10 = new javax.swing.JLabel();
txtAno = new javax.swing.JTextField();
spr2 = new javax.swing.JSeparator();
lblDatosServicio = new javax.swing.JLabel();
lblServicio = new javax.swing.JLabel();
cmbTipoServicio = new javax.swing.JComboBox<>();
lblCodigo = new javax.swing.JLabel();
txtCodigo = new javax.swing.JTextField();
lblDescripcion = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
txtaDescripcion = new javax.swing.JTextArea();
spr3 = new javax.swing.JSeparator();
btnRegistrar = new javax.swing.JButton();
btnFechaSistema = new javax.swing.JButton();
setClosable(true);
setResizable(true);
lblNro.setText("Numero Registro:");
lblFecha.setText("Fecha de Ingreso:");
lblIdentificacion.setText("Número Identificaión:");
lblNombre.setText("Nombre:");
lblDatosPaciente.setText("Datos Paciente:");
lblDireccion.setText("Dirección:");
lblTelefono.setText("Telefono:");
lblAfilicion.setText("Tipo Afiliación:");
txtNombre.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtNombreActionPerformed(evt);
}
});
txtIdentificacion.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtIdentificacionActionPerformed(evt);
}
});
txtDireccion.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtDireccionActionPerformed(evt);
}
});
txtTelefono.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtTelefonoActionPerformed(evt);
}
});
cmbAfiliacion.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Sisben", "Tipo A", "Tipo B", "Tipo C" }));
txtNro.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtNroActionPerformed(evt);
}
});
txtDia.setText("dia");
txtDia.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtDiaActionPerformed(evt);
}
});
jLabel1.setText("/");
txtMes.setText("mes");
txtMes.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtMesActionPerformed(evt);
}
});
jLabel10.setText("/");
txtAno.setText("año");
lblDatosServicio.setText("Datos del Servicio:");
lblServicio.setText("Servicio:");
cmbTipoServicio.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Cita Médica General", "Vacunación", "Laboratorios", "Hospitalización" }));
cmbTipoServicio.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmbTipoServicioActionPerformed(evt);
}
});
lblCodigo.setText("Código:");
txtCodigo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtCodigoActionPerformed(evt);
}
});
lblDescripcion.setText("Descripción:");
txtaDescripcion.setColumns(20);
txtaDescripcion.setRows(5);
jScrollPane1.setViewportView(txtaDescripcion);
btnRegistrar.setText("Registrar");
btnFechaSistema.setText("Fecha Sistema");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(spr3, javax.swing.GroupLayout.PREFERRED_SIZE, 680, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(lblDescripcion)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 585, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(lblServicio)
.addGap(32, 32, 32)
.addComponent(cmbTipoServicio, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(29, 29, 29)
.addComponent(lblCodigo)
.addGap(18, 18, 18)
.addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(lblDatosServicio)
.addComponent(spr2, javax.swing.GroupLayout.PREFERRED_SIZE, 680, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblDatosPaciente)
.addComponent(spr1, javax.swing.GroupLayout.PREFERRED_SIZE, 680, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblNombre)
.addComponent(lblDireccion))
.addGap(25, 25, 25)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(31, 31, 31)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(lblTelefono)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(lblAfilicion)
.addGap(18, 18, 18)
.addComponent(cmbAfiliacion, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(lblIdentificacion)
.addGap(32, 32, 32)
.addComponent(txtIdentificacion, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(layout.createSequentialGroup()
.addComponent(lblNro)
.addGap(18, 18, 18)
.addComponent(txtNro, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblFecha)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(txtDia, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 3, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtMes, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel10)
.addGap(7, 7, 7)
.addComponent(txtAno, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnFechaSistema)
.addGap(15, 15, 15))))
.addGroup(layout.createSequentialGroup()
.addGap(299, 299, 299)
.addComponent(btnRegistrar)))
.addContainerGap(38, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(14, 14, 14)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblNro)
.addComponent(lblFecha)
.addComponent(txtNro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtDia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)
.addComponent(txtMes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel10)
.addComponent(txtAno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnFechaSistema))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(spr1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblDatosPaciente)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblNombre)
.addComponent(lblIdentificacion)
.addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtIdentificacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblDireccion)
.addComponent(lblTelefono)
.addComponent(lblAfilicion)
.addComponent(txtTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cmbAfiliacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(spr2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblDatosServicio)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblServicio)
.addComponent(cmbTipoServicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblCodigo)
.addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblDescripcion)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(spr3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnRegistrar)
.addContainerGap(19, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void txtNombreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNombreActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtNombreActionPerformed
private void txtIdentificacionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtIdentificacionActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtIdentificacionActionPerformed
private void txtDireccionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtDireccionActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtDireccionActionPerformed
private void txtTelefonoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtTelefonoActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtTelefonoActionPerformed
private void txtNroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNroActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtNroActionPerformed
private void txtCodigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCodigoActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtCodigoActionPerformed
private void cmbTipoServicioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbTipoServicioActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cmbTipoServicioActionPerformed
private void txtDiaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtDiaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtDiaActionPerformed
private void txtMesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtMesActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtMesActionPerformed
public JButton getBtnFechaSistema() {
return btnFechaSistema;
}
public void setBtnFechaSistema(JButton btnFechaSistema) {
this.btnFechaSistema = btnFechaSistema;
}
public JButton getBtnRegistrar() {
return btnRegistrar;
}
public void setBtnRegistrar(JButton btnRegistrar) {
this.btnRegistrar = btnRegistrar;
}
public JComboBox<String> getCmbAfiliacion() {
return cmbAfiliacion;
}
public void setCmbAfiliacion(JComboBox<String> cmbAfiliacion) {
this.cmbAfiliacion = cmbAfiliacion;
}
public JComboBox<String> getCmbTipoServicio() {
return cmbTipoServicio;
}
public void setCmbTipoServicio(JComboBox<String> cmbTipoServicio) {
this.cmbTipoServicio = cmbTipoServicio;
}
public JLabel getjLabel1() {
return jLabel1;
}
public void setjLabel1(JLabel jLabel1) {
this.jLabel1 = jLabel1;
}
public JLabel getjLabel10() {
return jLabel10;
}
public void setjLabel10(JLabel jLabel10) {
this.jLabel10 = jLabel10;
}
public JScrollPane getjScrollPane1() {
return jScrollPane1;
}
public void setjScrollPane1(JScrollPane jScrollPane1) {
this.jScrollPane1 = jScrollPane1;
}
public JLabel getLblAfilicion() {
return lblAfilicion;
}
public void setLblAfilicion(JLabel lblAfilicion) {
this.lblAfilicion = lblAfilicion;
}
public JLabel getLblCodigo() {
return lblCodigo;
}
public void setLblCodigo(JLabel lblCodigo) {
this.lblCodigo = lblCodigo;
}
public JLabel getLblDatosPaciente() {
return lblDatosPaciente;
}
public void setLblDatosPaciente(JLabel lblDatosPaciente) {
this.lblDatosPaciente = lblDatosPaciente;
}
public JLabel getLblDatosServicio() {
return lblDatosServicio;
}
public void setLblDatosServicio(JLabel lblDatosServicio) {
this.lblDatosServicio = lblDatosServicio;
}
public JLabel getLblDescripcion() {
return lblDescripcion;
}
public void setLblDescripcion(JLabel lblDescripcion) {
this.lblDescripcion = lblDescripcion;
}
public JLabel getLblDireccion() {
return lblDireccion;
}
public void setLblDireccion(JLabel lblDireccion) {
this.lblDireccion = lblDireccion;
}
public JLabel getLblFecha() {
return lblFecha;
}
public void setLblFecha(JLabel lblFecha) {
this.lblFecha = lblFecha;
}
public JLabel getLblIdentificacion() {
return lblIdentificacion;
}
public void setLblIdentificacion(JLabel lblIdentificacion) {
this.lblIdentificacion = lblIdentificacion;
}
public JLabel getLblNombre() {
return lblNombre;
}
public void setLblNombre(JLabel lblNombre) {
this.lblNombre = lblNombre;
}
public JLabel getLblNro() {
return lblNro;
}
public void setLblNro(JLabel lblNro) {
this.lblNro = lblNro;
}
public JLabel getLblServicio() {
return lblServicio;
}
public void setLblServicio(JLabel lblServicio) {
this.lblServicio = lblServicio;
}
public JLabel getLblTelefono() {
return lblTelefono;
}
public void setLblTelefono(JLabel lblTelefono) {
this.lblTelefono = lblTelefono;
}
public JSeparator getSpr1() {
return spr1;
}
public void setSpr1(JSeparator spr1) {
this.spr1 = spr1;
}
public JSeparator getSpr2() {
return spr2;
}
public void setSpr2(JSeparator spr2) {
this.spr2 = spr2;
}
public JSeparator getSpr3() {
return spr3;
}
public void setSpr3(JSeparator spr3) {
this.spr3 = spr3;
}
public JTextField getTxtAno() {
return txtAno;
}
public void setTxtAno(JTextField txtAno) {
this.txtAno = txtAno;
}
public JTextField getTxtCodigo() {
return txtCodigo;
}
public void setTxtCodigo(JTextField txtCodigo) {
this.txtCodigo = txtCodigo;
}
public JTextField getTxtDia() {
return txtDia;
}
public void setTxtDia(JTextField txtDia) {
this.txtDia = txtDia;
}
public JTextField getTxtDireccion() {
return txtDireccion;
}
public void setTxtDireccion(JTextField txtDireccion) {
this.txtDireccion = txtDireccion;
}
public JTextField getTxtIdentificacion() {
return txtIdentificacion;
}
public void setTxtIdentificacion(JTextField txtIdentificacion) {
this.txtIdentificacion = txtIdentificacion;
}
public JTextField getTxtMes() {
return txtMes;
}
public void setTxtMes(JTextField txtMes) {
this.txtMes = txtMes;
}
public JTextField getTxtNombre() {
return txtNombre;
}
public void setTxtNombre(JTextField txtNombre) {
this.txtNombre = txtNombre;
}
public JTextField getTxtNro() {
return txtNro;
}
public void setTxtNro(JTextField txtNro) {
this.txtNro = txtNro;
}
public JTextField getTxtTelefono() {
return txtTelefono;
}
public void setTxtTelefono(JTextField txtTelefono) {
this.txtTelefono = txtTelefono;
}
public JTextArea getTxtaDescripcion() {
return txtaDescripcion;
}
public void setTxtaDescripcion(JTextArea txtaDescripcion) {
this.txtaDescripcion = txtaDescripcion;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnFechaSistema;
private javax.swing.JButton btnRegistrar;
private javax.swing.JComboBox<String> cmbAfiliacion;
private javax.swing.JComboBox<String> cmbTipoServicio;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel lblAfilicion;
private javax.swing.JLabel lblCodigo;
private javax.swing.JLabel lblDatosPaciente;
private javax.swing.JLabel lblDatosServicio;
private javax.swing.JLabel lblDescripcion;
private javax.swing.JLabel lblDireccion;
private javax.swing.JLabel lblFecha;
private javax.swing.JLabel lblIdentificacion;
private javax.swing.JLabel lblNombre;
private javax.swing.JLabel lblNro;
private javax.swing.JLabel lblServicio;
private javax.swing.JLabel lblTelefono;
private javax.swing.JSeparator spr1;
private javax.swing.JSeparator spr2;
private javax.swing.JSeparator spr3;
private javax.swing.JTextField txtAno;
private javax.swing.JTextField txtCodigo;
private javax.swing.JTextField txtDia;
private javax.swing.JTextField txtDireccion;
private javax.swing.JTextField txtIdentificacion;
private javax.swing.JTextField txtMes;
private javax.swing.JTextField txtNombre;
private javax.swing.JTextField txtNro;
private javax.swing.JTextField txtTelefono;
private javax.swing.JTextArea txtaDescripcion;
// End of variables declaration//GEN-END:variables
}
|
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
class MaxMinMidle {
//метод возвращает наибольший элемент
static int Max(int...arr) {
Arrays.sort(arr); //сортируем полученный массив
return arr[arr.length-1]; //возвращаем наибольший
}
//метод возвращает наименьший элемент
static int Min(int...arr) {
Arrays.sort(arr); //сортируем полученный массив
return arr[0];//возвращаем наименьший
}
//метод возвращает среднее значание
static double Midle(int...arr) {
double sum = 0;
for (int i=0; i<arr.length;++i) {sum+=arr[i];}
return sum/arr.length;
}
}
public class example32_03 {
public static void main(String[] args) {
try {
System.out.println("Программа с классом, в котором есть статические методы.\n"
+"Им можно передавать произвольное количество целочисленных аргументов (или целочисленный массив).\n"
+"Методы позволяют вычислить: наибольшее значение, наименьшее значение, а также среднее значение из набора аргументов.");
Scanner in = new Scanner(System.in);
Random rnd = new Random(); // Random для "случайного" заполнения исходного массива
MaxMinMidle obj=new MaxMinMidle();
System.out.println("-----------------------------------------------------");
System.out.println("Введите количество аргументов:");
int size=in.nextInt();
int array[]=new int[size];
System.out.println("Аргументы созданы генератором случайных чисел в диапазоне от 0 до 200:");
for (int i=0 ; i<array.length ; i++) {array[i] = rnd.nextInt(200); // Присвоение i-тому элементу массива случайного значения
System.out.print(array[i]+" ");}
System.out.println();
System.out.println("-----------------------------------------------------");
System.out.println("Наибольшее значение:"+obj.Max(array));
System.out.println("Наименьшее значение:"+obj.Min(array));
System.out.printf("Среднее значение элементов массива= %.2f", obj.Midle(array));
}
catch (Exception error) { System.out.println("При обработке данных произошла ошибка!"); //обработка исключения
}
}
}
|
package cglib;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
/**
* Specific method interceptor for {@link Object#hashCode()}.
*
* @author <a href="http://blog.frankel.ch/">Nicolas Frankel</a>
*/
public class HashCodeAlwaysZeroMethodInterceptor implements MethodInterceptor {
/**
* For {@link Object#hashCode()}, always returns <code>0</code>.
* Otherwise, does what is expected.
*
* @see net.sf.cglib.proxy.MethodInterceptor#intercept(Object, Method,
* Object[], MethodProxy)
*/
public Object intercept(Object object, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
if ("hashCode".equals(method.getName())) {
return 0;
}
return methodProxy.invokeSuper(object, args);
}
}
|
package com._520it.line;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LineServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取请求行的信息
//1.获取请求方法
String method = request.getMethod();
System.out.println("method:"+method);
//2.获取路径
String requestURI = request.getRequestURI();
StringBuffer requestURL = request.getRequestURL();
System.out.println("uri:"+requestURI);
System.out.println("url:"+requestURL);
//3.获取WEB 应用
String contextPath = request.getContextPath();
System.out.println("web应用:"+contextPath);
//4.获取get方式下的请求参数
String queryString = request.getQueryString();
System.out.println("query:"+queryString);
//5.获取客户端的IP地址
String remoteAddr = request.getRemoteAddr();
System.out.println("ip:"+remoteAddr);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
|
package server.sport.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;
import server.sport.model.UserResponsibility;
import server.sport.model.UserResponsibilityPK;
public interface UserResponsibilityRepository extends JpaRepository<UserResponsibility, UserResponsibilityPK> {
@Transactional
@Modifying
@Query(value = "UPDATE dbo.user_responsibilities SET user_id = ?1 WHERE responsibility_id = ?2 AND activity_id=?3", nativeQuery = true)
int saveUserResponsibilityForActivity(int user_id, int responsibility_id, int activity_id);
@Transactional
@Modifying
@Query(value = "INSERT INTO dbo.user_responsibilities (responsibility_id, activity_id) VALUES (?,?)", nativeQuery = true)
int saveResponsibilityForActivity(int responsibility_id, int activity_id);
}
|
package com.emc.subscribe.client;
import com.emc.subscribe.handler.MessageHandler;
import io.netty.handler.logging.LogLevel;
import java.util.HashMap;
import java.util.Map;
@SuppressWarnings({"unused", "WeakerAccess"})
public class SubscribeClientBuilder {
/**最大接收长度*/
private int maxFrameLength;
/**消息结束符*/
private String lineSeparator;
/**编码方式*/
private String charsetName;
/**日志级别*/
private LogLevel logLevel;
/**服务端ip*/
private String ip;
/**服务端端口*/
private int port;
/**消息处理对象*/
private MessageHandler messageHandler;
/**订阅用户名*/
private String username;
/**订阅消息主题及密钥*/
private Map<String, String> topics;
/**长连接保持心跳时间 (大于10 秒)*/
private int heartBeatTime;
public SubscribeClient build(){
checkParam();
return SubscribeClient.instance(ip,port)
.updateDefaultParam(maxFrameLength,lineSeparator,charsetName,logLevel,heartBeatTime)
.subscribe(username,topics)
.setMessageHandler(messageHandler)
.initialize();
}
private void checkParam(){
if(ip==null || ip.equals("")||port<1){
throw new RuntimeException("ip,port error!");
}else if(topics.size()==0){
throw new RuntimeException("subscribed topic is empty!");
}else if(username==null || username.equals("")){
throw new RuntimeException("username is empty!");
}
}
public SubscribeClientBuilder(){
this.topics=new HashMap<String,String>();
}
public SubscribeClientBuilder(String ip, int port) {
this();
this.ip=ip;
this.port=port;
}
public SubscribeClientBuilder(String ip,int port,MessageHandler messageHandler){
this(ip,port);
this.messageHandler=messageHandler;
}
public int getMaxFrameLength() {
return maxFrameLength;
}
/**
* 设置最大读取长度(默认:10kb)
* @param maxFrameLength 最大读取长度
* @return 当前对象
*/
public SubscribeClientBuilder setMaxFrameLength(int maxFrameLength) {
this.maxFrameLength = maxFrameLength;
return this;
}
public String getLineSeparator() {
return lineSeparator;
}
/**
* 设置消息结束分隔符(默认:$$)
* @param lineSeparator 消息结束分隔符
* @return 当前对象
*/
public SubscribeClientBuilder setLineSeparator(String lineSeparator) {
this.lineSeparator = lineSeparator;
return this;
}
public String getCharsetName() {
return charsetName;
}
/**
* 设置编码方式(默认:GBK)
* @param charsetName 编码方式
* @return 当前对象
*/
public SubscribeClientBuilder setCharsetName(String charsetName) {
this.charsetName = charsetName;
return this;
}
public String getIp() {
return ip;
}
/**
* 设置服务端IP
* @param ip 服务端IP
* @return 当前对象
*/
public SubscribeClientBuilder setIp(String ip) {
this.ip = ip;
return this;
}
public int getPort() {
return port;
}
/**
* 设置服务端端口
* @param port 服务端端口
* @return 当前对象
*/
public SubscribeClientBuilder setPort(int port) {
this.port = port;
return this;
}
public MessageHandler getMessageHandler() {
return messageHandler;
}
/**
* 设置消息处理对象
* @param messageHandler 消息处理对象
* @return 当前对象
*/
public SubscribeClientBuilder setMessageHandler(MessageHandler messageHandler) {
this.messageHandler = messageHandler;
return this;
}
public String getUsername() {
return username;
}
/**
* 设置用户名
* @param username 用户名
* @return 当前对象
*/
public SubscribeClientBuilder setUsername(String username) {
this.username = username;
return this;
}
public Map<String, String> getTopics() {
return topics;
}
/**
* 设置订阅主题
* @param topics 主题
* @return 当前对象
*/
public SubscribeClientBuilder setTopics(Map<String, String> topics) {
this.topics.putAll(topics);
return this;
}
public SubscribeClientBuilder setTopic(String appId,String appSecret){
this.topics.put(appId,appSecret);
return this;
}
/**
* 设置日志级别 (默认:INFO)
* @param logLevel 日志级别
* @return 当前对象
*/
public SubscribeClientBuilder setLogLevel(LogLevel logLevel) {
this.logLevel = logLevel;
return this;
}
public int getHeartBeatTime() {
return heartBeatTime;
}
/**
* 设置长连接心跳时间 大于10秒才生效(默认:60s)
* @param heartBeatTime 心跳时间
* @return 当前对象
*/
public SubscribeClientBuilder setHeartBeatTime(int heartBeatTime) {
this.heartBeatTime = heartBeatTime;
return this;
}
}
|
package com.lsjr.zizi.view;
import android.content.Context;
import android.view.MotionEvent;
import android.widget.LinearLayout;
/**
* 创建人:$ gyymz1993
* 创建时间:2017/8/3 13:03
*/
public class TLinearLayout extends LinearLayout {
public TLinearLayout(Context context) {
super(context);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return super.onTouchEvent(event);
}
@Override
public boolean performClick() {
return super.performClick();
}
}
|
package com.jd.jarvisdemonim.ui.testadapteractivity.showcustomview;
import android.animation.Animator;
import android.animation.ValueAnimator;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.jd.jarvisdemonim.R;
import com.jd.jdkit.elementkit.activity.DBaseActivity;
import com.jd.myadapterlib.RecyCommonAdapter;
import com.jd.myadapterlib.RecyMultiItemTypeAdapter;
import com.jd.myadapterlib.delegate.RecyViewHolder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import butterknife.Bind;
/**
* Auther: Jarvis Dong
* Time: on 2017/3/30 0030
* Name:
* OverView:
* Usage:
*/
public class NormalTestCartActivity extends DBaseActivity {
@Bind(R.id.recycler)
RecyclerView mRecyler;
@Bind(R.id.img_cart)
ImageView ImgCart;
@Bind(R.id.relation_id)
RelativeLayout mRelation;
List mdatas;
private RecyCommonAdapter madapter;
//动画
private PathMeasure pathMeasure;
HashMap<Integer, PathMeasure> map = new HashMap<>();
int count=0;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 0) {
int pos = msg.arg1;
ImageView iv = (ImageView) msg.obj;
addCartAnimator(iv, pos);
}
}
};
@Override
public int getContentViewId() {
return R.layout.activity_cart;
}
@Override
protected void initView(Bundle savedInstanceState) {
mdatas = new ArrayList();
madapter = new RecyCommonAdapter(mRecyler, R.layout.item_cart, mdatas) {
@Override
protected void convert(RecyViewHolder viewHolder, Object item, int position) {
if (item instanceof CartBean) {
CartBean cb = (CartBean) item;
viewHolder.setImageResource(R.id.img_cart_item, cb.imgSrc);
}
}
};
}
@Override
protected void initVariable() {
mRecyler.setAdapter(madapter);
mRecyler.setLayoutManager(new LinearLayoutManager(mContext));
}
@Override
protected void processLogic(Bundle savedInstanceState) {
madapter.setOnItemClickListener(new RecyMultiItemTypeAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
ImageView iv = (ImageView) view.findViewById(R.id.img_cart_item);
// addCartAnimator(iv);
Message msg = Message.obtain();
msg.what = 0;
msg.obj = iv;
msg.arg1 = position;
handler.sendMessage(msg);
}
@Override
public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
return false;
}
});
mdatas.add(new CartBean(R.drawable.head_icon_2));
mdatas.add(new CartBean(R.drawable.head_icon_3));
mdatas.add(new CartBean(R.drawable.head_icon_4));
mdatas.add(new CartBean(R.drawable.head_icon_5));
mdatas.add(new CartBean(R.drawable.head_icon_6));
madapter.setDatas(mdatas);
}
class CartBean {
public CartBean(int imgSrc) {
this.imgSrc = imgSrc;
}
private int imgSrc;
}
//添加到购物车的方法;
public void addCartAnimator(final ImageView imageView, final int pos) {
count++;
if (imageView == null)
throw new IllegalArgumentException("imageview must not null");
/**
* 防止点击的item使用的是同一个mCurrentPostion;造成动画跳位;
*/
final float[] mCurrentPosition = new float[2];
//执行动画的图片;
final ImageView pathImg = new ImageView(mContext);
pathImg.setImageResource(R.drawable.pic2);
RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
mRelation.addView(pathImg, rl);
//计算动画的起始和终点坐标;
int[] parentLoc = new int[2];
mRelation.getLocationInWindow(parentLoc);//recyclerview
int[] startLoc = new int[2];
imageView.getLocationInWindow(startLoc);//item中的img;
int[] endLoc = new int[2];
ImgCart.getLocationInWindow(endLoc);//购物车;
//计算动画的位置;
//开始点:就是说getLocationInWindow得到的是View的起点,左上角;
float startX = startLoc[0] - parentLoc[0] + imageView.getWidth() / 2 - 30;//-pathImg.getWidth()正中
float startY = startLoc[1] - parentLoc[1] + imageView.getHeight() / 2 - 30;
//结束点:
float endX = endLoc[0] - parentLoc[0] + ImgCart.getWidth() / 2 - pathImg.getWidth();
float endY = endLoc[1] - parentLoc[1] + ImgCart.getHeight() / 2 - pathImg.getHeight();
//插值动画;
Path path = new Path();
path.moveTo(startX, startY);
path.quadTo((startX + endX) / 2, startY, endX, endY);
pathMeasure = new PathMeasure(path, false);
/**
* 添加至map中,避免造成动画的乱闯;
*/
if (!map.keySet().contains(pos)) {
map.put(pos, pathMeasure);
}
//使用属性动画插值,长度到0-贝塞尔曲线长度;
ValueAnimator valueAnimator = new ValueAnimator().ofFloat(0, pathMeasure.getLength());
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float animatedValue = (float) animation.getAnimatedValue();
// float animatedFraction = animation.getAnimatedFraction();
//计算切线,移动view到此;
PathMeasure pathMeasure = map.get(pos);
pathMeasure.getPosTan(animatedValue, mCurrentPosition, null);
pathImg.setTranslationX(mCurrentPosition[0]);
pathImg.setTranslationY(mCurrentPosition[1]);
}
});
valueAnimator.setDuration(3000).start();
valueAnimator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
mRelation.removeView(pathImg);
count--;
if(count==0){
map.clear();
}
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
}
|
package com.bwie.juan_mao.jingdong_kanglijuan.view.shop;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bwie.juan_mao.jingdong_kanglijuan.R;
import com.bwie.juan_mao.jingdong_kanglijuan.adapter.ProductAdapter;
import com.bwie.juan_mao.jingdong_kanglijuan.adapter.RecommendShopAdapter;
import com.bwie.juan_mao.jingdong_kanglijuan.adapter.ShopperAdapter;
import com.bwie.juan_mao.jingdong_kanglijuan.base.BaseActivity;
import com.bwie.juan_mao.jingdong_kanglijuan.bean.DefaultAddrBean;
import com.bwie.juan_mao.jingdong_kanglijuan.bean.MessageBean;
import com.bwie.juan_mao.jingdong_kanglijuan.bean.ProductBean;
import com.bwie.juan_mao.jingdong_kanglijuan.bean.RecommendBean;
import com.bwie.juan_mao.jingdong_kanglijuan.bean.RegisterBean;
import com.bwie.juan_mao.jingdong_kanglijuan.bean.ShopperBean;
import com.bwie.juan_mao.jingdong_kanglijuan.presenter.CartPresenter;
import com.bwie.juan_mao.jingdong_kanglijuan.view.ICartView;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class CartActivity extends BaseActivity<CartPresenter> implements ICartView {
@BindView(R.id.txt_edit_complete)
TextView txtEditComplete;
@BindView(R.id.img_msg)
ImageView imgMsg;
@BindView(R.id.rv_shopper)
RecyclerView rvShopper;
@BindView(R.id.img_recommend)
ImageView imgRecommend;
@BindView(R.id.rv_recommend)
RecyclerView rvRecommend;
@BindView(R.id.cb_checkall)
CheckBox cbCheckall;
@BindView(R.id.txt_total_price)
TextView txtTotalPrice;
@BindView(R.id.btn_account)
Button btnAccount;
@BindView(R.id.txt_delete)
TextView txtDelete;
private List<ShopperBean<List<ProductBean>>> cartList;
private ShopperAdapter adapter;
private boolean isEdited = false;
private List<RecommendBean.DataBean.ListBean> list;
private RecommendShopAdapter recommendShopAdapter;
private TextView txtTip;
private Button btnCancel;
private Button btnConfirm;
private AlertDialog alertDialog;
@Override
protected void initData() {
// 设置弹框
View view = View.inflate(this, R.layout.dialog_delete_cart, null);
txtTip = view.findViewById(R.id.txt_tip);
btnCancel = view.findViewById(R.id.btn_cancel);
btnConfirm = view.findViewById(R.id.btn_confirm);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(view);
alertDialog = builder.create();
// 设置嵌套滑动
rvRecommend.setNestedScrollingEnabled(false);
rvShopper.setNestedScrollingEnabled(false);
list = new ArrayList<>();
rvRecommend.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
rvRecommend.setNestedScrollingEnabled(false);
recommendShopAdapter = new RecommendShopAdapter(this, list);
rvRecommend.setAdapter(recommendShopAdapter);
recommendShopAdapter.setOnItemClickListener(new RecommendShopAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
RecommendBean.DataBean.ListBean listBean = list.get(position);
Intent intent = new Intent(CartActivity.this, ShopWebActivity.class);
intent.putExtra("pid", listBean.getPid());
startActivity(intent);
}
});
cartList = new ArrayList<>();
// 商家的列表
adapter = new ShopperAdapter(this, cartList);
// 添加一级条目(商家)状态发生变化时
adapter.setOnShopperClickListener(new ShopperAdapter.OnShopperClickListener() {
@Override
public void onShopperClick(int position, boolean isCheck) {
// 为了效率考虑,当点击状态变成未选中时,全选按钮肯定就不是全选了,就不用再循环一次
if (!isCheck) {
cbCheckall.setChecked(false);
} else {
// 如果是商家变成选中状态时,需要循环遍历所有的商家是否被选中
// 循环遍历之前先设置一个true标志位,只要有一个是未选中就改变这个标志位为false
boolean isAllShopperChecked = true;
for (ShopperBean<List<ProductBean>> listShopper : cartList) {
// 只要有一个商家没有被选中,全选复选框就变成未选中状态,并且结束循环
if (!listShopper.isChecked()) {
isAllShopperChecked = false;
break;
}
}
cbCheckall.setChecked(isAllShopperChecked);
}
// 一级条目发生变化时,计算一下总价
calculatePrice();
}
});
adapter.setOnAddDecreaseProductListener(new ProductAdapter.OnAddDecreaseProductListener() {
@Override
public void onChange(int position, int num) {
calculatePrice();
}
});
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
rvShopper.setLayoutManager(layoutManager);
rvShopper.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
rvShopper.setAdapter(adapter);
}
@Override
public void onResume() {
super.onResume();
presenter.getCarts();
presenter.getRecommend(71);
cbCheckall.setChecked(false);
changeView();
}
private void changeView() {
if (isEdited) {
txtEditComplete.setText("完成");
txtTotalPrice.setVisibility(View.GONE);
txtDelete.setVisibility(View.VISIBLE);
imgMsg.setVisibility(View.INVISIBLE);
imgRecommend.setVisibility(View.GONE);
rvRecommend.setVisibility(View.GONE);
btnAccount.setVisibility(View.GONE);
} else {
txtEditComplete.setText("编辑");
txtTotalPrice.setVisibility(View.VISIBLE);
txtDelete.setVisibility(View.GONE);
imgMsg.setVisibility(View.VISIBLE);
imgRecommend.setVisibility(View.VISIBLE);
rvRecommend.setVisibility(View.VISIBLE);
btnAccount.setVisibility(View.VISIBLE);
}
}
@Override
protected void setListener() {
super.setListener();
cbCheckall.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isChecked = cbCheckall.isChecked();
// 遍历一级列表,和下方的全选状态一致
for (ShopperBean<List<ProductBean>> listShopper : cartList) {
listShopper.setChecked(isChecked);
// 遍历二级列表,和下方的全选状态一致
List<ProductBean> products = listShopper.getList();
for (ProductBean product : products) {
product.setChecked(isChecked);
}
}
calculatePrice();
adapter.notifyDataSetChanged();
}
});
}
// 计算商品总价
private void calculatePrice() {
// 遍历商家
float totalPrice = 0;
for (ShopperBean<List<ProductBean>> listShopper : cartList) {
// 遍历商家的商品
List<ProductBean> list = listShopper.getList();
for (ProductBean product : list) {
// 如果商品被选中
if (product.isChecked()) {
totalPrice += product.getNum() * product.getPrice();
}
}
}
txtTotalPrice.setText("总价:¥" + totalPrice);
}
@Override
protected CartPresenter providePresenter() {
return new CartPresenter();
}
@Override
protected int provideLayoutId() {
return R.layout.activity_cart;
}
@Override
public Context getContext() {
return this;
}
@Override
public void getCarts(MessageBean<List<ShopperBean<List<ProductBean>>>> data) {
// 获取商家列表
List<ShopperBean<List<ProductBean>>> shoppers = data.getData();
if (shoppers != null) {
cartList.clear();
cartList.addAll(shoppers);
adapter.notifyDataSetChanged();
}
}
@Override
public void getRecommend(RecommendBean data) {
list.clear();
for (int i = 0; i < data.getData().size(); i++) {
for (int j = 0; j < data.getData().get(i).getList().size(); j++) {
List<RecommendBean.DataBean.ListBean> listBeans = data.getData().get(i).getList();
list.addAll(listBeans);
}
}
recommendShopAdapter.notifyDataSetChanged();
}
/**
* 用不到
*
* @param data
*/
@Override
public void deleteCart(RegisterBean data) {
}
@Override
public void getDefaultAddr(DefaultAddrBean data) {
}
/**
* 用不到
*
* @param data
*/
@Override
public void createOrder(RegisterBean data) {
}
/**
* 用不到
* @param data
*/
@Override
public void updateCarts(RegisterBean data) {
}
@Override
public void onCartFailed(Throwable t) {
Toast.makeText(this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
@OnClick({R.id.txt_edit_complete, R.id.img_msg, R.id.btn_account, R.id.txt_delete})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.txt_edit_complete:
isEdited = !isEdited;
changeView();
break;
case R.id.img_msg:
Toast.makeText(this, "此功能尚在开发中~", Toast.LENGTH_SHORT).show();
break;
case R.id.txt_delete:
int count = 0;
for (ShopperBean<List<ProductBean>> listShopper : cartList) {
// 遍历商家的商品
List<ProductBean> list = listShopper.getList();
for (ProductBean product : list) {
// 如果商品被选中
if (product.isChecked()) {
count++;
}
}
}
if (count != 0) {
txtTip.setText("确认要删除这" + count + "种商品吗?");
alertDialog.show();
// 如果确认就遍历删除
btnConfirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
for (ShopperBean<List<ProductBean>> listShopper : cartList) {
// 遍历商家的商品
List<ProductBean> list = listShopper.getList();
for (ProductBean product : list) {
// 如果商品被选中
if (product.isChecked()) {
presenter.deleteCart(product.getPid());
}
}
}
isEdited = false;
changeView();
alertDialog.dismiss();
presenter.getCarts();
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
alertDialog.dismiss();
}
});
}
break;
case R.id.btn_account:
List<ShopperBean<List<ProductBean>>> listBean = new ArrayList<>();
for (ShopperBean<List<ProductBean>> listShopper : cartList) {
// 遍历商家的商品
if (listShopper.isChecked()) {
listBean.add(listShopper);
} else {
for (ProductBean productBean : listShopper.getList()) {
if (productBean.isChecked()) {
// 自己创建一个shopperBean
List<ProductBean> productList = new ArrayList<>();
productList.add(productBean);
ShopperBean<List<ProductBean>> listShopperBean = new ShopperBean<>();
listShopperBean.setList(productList);
listShopperBean.setSellerName(listShopper.getSellerName());
listBean.add(listShopperBean);
}
}
}
}
if (listBean.size() != 0) {
Intent intent = new Intent(this, PlaceOrderActivity.class);
intent.putExtra("list", (Serializable) listBean);
startActivity(intent);
} else {
Toast.makeText(this, "请选中商品再下单", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
|
package com.project.daicuongbachkhoa.student.physicsonestudent;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.project.daicuongbachkhoa.R;
public class OutlinePhysicsOne extends AppCompatActivity {
PDFView outlinePhysicsOne;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_outline_physics_one);
outlinePhysicsOne = findViewById(R.id.outlinePhysicsOne);
outlinePhysicsOne.fromAsset("outline_physicsone.pdf")
.defaultPage(0)
.enableAnnotationRendering(true)
.swipeHorizontal(true)
.scrollHandle(new DefaultScrollHandle(this))
.spacing(2)
.load();
}
}
|
package com.xuchengpu.shoppingmall.community.adapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.List;
/**
* Created by 许成谱 on 2017/3/5 17:31.
* qq:1550540124
* for:
*/
//也可以用pageradapter API一提供了封装好的 FragmentPagerAdapter,使用更方便
public class CommunityPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragments;
private String[] titles = new String[]{"新帖", "热帖"};
public CommunityPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments=fragments;
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
//返回标题给指示器
@Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
|
import java.awt.*;
import java.javax.swing.*;
class screen extends JWindow
{
JProgressBar pb1;
JLabel l1,l2;
public void de()
{
pb1=new JProgressBar(0,100);
pb1.setStringPainted(true);
l1=new JLabel("WELCOME");
l2=new JLabel("PlEASE WATE");
setBounds(10,10,500,500);
l1.setBounds(20,50,300,30);
pb1.setBounds(10,100,400,10);
l2.setBounds(20,150,100,20);
add(l1);
add(l2);
add(pb1);
try
{
for(i=0;i<=100;i+=2)
{
pb1.setValue(pb1.getValue()+i);
pb1.setString(String.valueOf(i)+"%");
Thread.sleep(1000);
}
}
setVisible(false);
from1 f=new from1();
f.setVisible(true);
f.de();
catch Exception e;
{
}
}
}
|
/*
* Copyright 2002-2020 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.aop.aspectj.autoproxy;
import java.util.Comparator;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJAopUtils;
import org.springframework.aop.aspectj.AspectJPrecedenceInformation;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.util.Assert;
/**
* Orders AspectJ advice/advisors by precedence (<i>not</i> invocation order).
*
* <p>Given two pieces of advice, {@code A} and {@code B}:
* <ul>
* <li>If {@code A} and {@code B} are defined in different aspects, then the advice
* in the aspect with the lowest order value has the highest precedence.</li>
* <li>If {@code A} and {@code B} are defined in the same aspect, if one of
* {@code A} or {@code B} is a form of <em>after</em> advice, then the advice declared
* last in the aspect has the highest precedence. If neither {@code A} nor {@code B}
* is a form of <em>after</em> advice, then the advice declared first in the aspect
* has the highest precedence.</li>
* </ul>
*
* <p>Important: This comparator is used with AspectJ's
* {@link org.aspectj.util.PartialOrder PartialOrder} sorting utility. Thus, unlike
* a normal {@link Comparator}, a return value of {@code 0} from this comparator
* means we don't care about the ordering, not that the two elements must be sorted
* identically.
*
* @author Adrian Colyer
* @author Juergen Hoeller
* @since 2.0
*/
class AspectJPrecedenceComparator implements Comparator<Advisor> {
private static final int HIGHER_PRECEDENCE = -1;
private static final int SAME_PRECEDENCE = 0;
private static final int LOWER_PRECEDENCE = 1;
private final Comparator<? super Advisor> advisorComparator;
/**
* Create a default {@code AspectJPrecedenceComparator}.
*/
public AspectJPrecedenceComparator() {
this.advisorComparator = AnnotationAwareOrderComparator.INSTANCE;
}
/**
* Create an {@code AspectJPrecedenceComparator}, using the given {@link Comparator}
* for comparing {@link org.springframework.aop.Advisor} instances.
* @param advisorComparator the {@code Comparator} to use for advisors
*/
public AspectJPrecedenceComparator(Comparator<? super Advisor> advisorComparator) {
Assert.notNull(advisorComparator, "Advisor comparator must not be null");
this.advisorComparator = advisorComparator;
}
@Override
public int compare(Advisor o1, Advisor o2) {
int advisorPrecedence = this.advisorComparator.compare(o1, o2);
if (advisorPrecedence == SAME_PRECEDENCE && declaredInSameAspect(o1, o2)) {
advisorPrecedence = comparePrecedenceWithinAspect(o1, o2);
}
return advisorPrecedence;
}
private int comparePrecedenceWithinAspect(Advisor advisor1, Advisor advisor2) {
boolean oneOrOtherIsAfterAdvice =
(AspectJAopUtils.isAfterAdvice(advisor1) || AspectJAopUtils.isAfterAdvice(advisor2));
int adviceDeclarationOrderDelta = getAspectDeclarationOrder(advisor1) - getAspectDeclarationOrder(advisor2);
if (oneOrOtherIsAfterAdvice) {
// the advice declared last has higher precedence
if (adviceDeclarationOrderDelta < 0) {
// advice1 was declared before advice2
// so advice1 has lower precedence
return LOWER_PRECEDENCE;
}
else if (adviceDeclarationOrderDelta == 0) {
return SAME_PRECEDENCE;
}
else {
return HIGHER_PRECEDENCE;
}
}
else {
// the advice declared first has higher precedence
if (adviceDeclarationOrderDelta < 0) {
// advice1 was declared before advice2
// so advice1 has higher precedence
return HIGHER_PRECEDENCE;
}
else if (adviceDeclarationOrderDelta == 0) {
return SAME_PRECEDENCE;
}
else {
return LOWER_PRECEDENCE;
}
}
}
private boolean declaredInSameAspect(Advisor advisor1, Advisor advisor2) {
return (hasAspectName(advisor1) && hasAspectName(advisor2) &&
getAspectName(advisor1).equals(getAspectName(advisor2)));
}
private boolean hasAspectName(Advisor advisor) {
return (advisor instanceof AspectJPrecedenceInformation ||
advisor.getAdvice() instanceof AspectJPrecedenceInformation);
}
// pre-condition is that hasAspectName returned true
private String getAspectName(Advisor advisor) {
AspectJPrecedenceInformation precedenceInfo = AspectJAopUtils.getAspectJPrecedenceInformationFor(advisor);
Assert.state(precedenceInfo != null, () -> "Unresolvable AspectJPrecedenceInformation for " + advisor);
return precedenceInfo.getAspectName();
}
private int getAspectDeclarationOrder(Advisor advisor) {
AspectJPrecedenceInformation precedenceInfo = AspectJAopUtils.getAspectJPrecedenceInformationFor(advisor);
return (precedenceInfo != null ? precedenceInfo.getDeclarationOrder() : 0);
}
}
|
package com.youthlin.example.cglib.bean;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* 创建: youthlin.chen
* 时间: 2017-11-09 10:26
*/
public class FiledRecorder<T> implements MethodInterceptor {
private static final String SET = "set";
private static final String INIT = "init";
private static final String CHANGED = "changed";
private Map<String, String> fieldStatusMap = new HashMap<>();
private Map<String, Object> fieldValueMap = new HashMap<>();
public FiledRecorder(Class<T> clazz) {
for (Field field : clazz.getDeclaredFields()) {
String fieldName = field.getName();
fieldStatusMap.put(fieldName, INIT);
fieldValueMap.put(fieldName, null);
}
}
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
String methodName = method.getName();
if (methodName.length() > 3 && methodName.startsWith(SET) && objects != null && objects.length == 1) {
String filedName = methodName.substring(SET.length());
filedName = filedName.substring(0, 1).toLowerCase() + filedName.substring(1);
Object newValue = objects[0];
if (!Objects.equals(newValue, fieldValueMap.get(filedName))) {
fieldValueMap.put(filedName, newValue);
fieldStatusMap.put(filedName, CHANGED);
}
}
return methodProxy.invokeSuper(o, objects);
}
public Map<String, String> getFieldStatusMap() {
return fieldStatusMap;
}
public Map<String, Object> getFieldValueMap() {
return fieldValueMap;
}
}
|
package com.lti.CaseStudy.CaseStudy2;
import com.lti.CaseStudy.CaseStudyPlan.Course;
import com.lti.CaseStudy.CaseStudyPlan.Student;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* Created by busis on 2020-12-04.
*/
public class AppEngine {
public void introduce(Course course) throws ClassNotFoundException, SQLException {
//insert into course
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/lti","root","tuningfork1212");
PreparedStatement preparedStatement = con.prepareStatement("Insert into course values (?,?,?,?)");
preparedStatement.setInt(1,course.getId());
preparedStatement.setString(2, course.getName());
preparedStatement.setInt(3, course.getFees());
preparedStatement.setInt(4,course.getDuration());
preparedStatement.executeUpdate();
}
public void register(Student student) throws SQLException, ClassNotFoundException {
//insert into student
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/lti","root","tuningfork1212");
PreparedStatement preparedStatement = con.prepareStatement("Insert into student values (?,?,?)");
preparedStatement.setInt(1, student.getId());
preparedStatement.setString(2, student.getName());
preparedStatement.setDate(3, (Date) student.getDateOfBirth());
preparedStatement.executeUpdate();
}
public Student[] listOfStudents() throws ClassNotFoundException,SQLException {
//select all rows from student and pass as StudentArray
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/lti","root","tuningfork1212");
Statement stmnt = con.createStatement();
ResultSet rs = stmnt.executeQuery("SELECT * from student");
List<Student> studentList = new ArrayList<Student>();
while (rs.next()){
studentList.add(new Student(rs.getInt(1),rs.getString(2),rs.getDate(3)));
}
int numOfStudents=0;
numOfStudents=studentList.size();
Student[] students = new Student[numOfStudents];
for(int i=0;i<numOfStudents;i++){
students[i]=new Student(studentList.get(i).getId(),studentList.get(i).getName(),studentList.get(i).getDateOfBirth());
}
return students;
}
public Course[] listOfCourses() throws ClassNotFoundException,SQLException{
//select all from course table and pass as CoursesArray
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/lti","root","tuningfork1212");
Statement stmnt = con.createStatement();
ResultSet rs = stmnt.executeQuery("SELECT * from course");
List<Course> courseList = new ArrayList<Course>();
while (rs.next()){
courseList.add(new Course(rs.getInt(1),rs.getString(2),rs.getInt(3),rs.getInt(4)));
}
int numOfCourses=0;
numOfCourses=courseList.size();
Course[] courses = new Course[numOfCourses];
for(int i=0;i<numOfCourses;i++){
courses[i]=new Course(courseList.get(i).getId(),courseList.get(i).getName(),courseList.get(i).getFees(),courseList.get(i).getDuration());
}
return courses;
}
public void enroll(Student student,Course course) throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/lti","root","tuningfork1212");
PreparedStatement preparedStatement = con.prepareStatement("Insert into enroll values (?,?,CURDATE())");
preparedStatement.setInt(1, student.getId());
preparedStatement.setInt(2, course.getId());
preparedStatement.executeUpdate();
}
public Enroll[] listOfEnrollments() throws ClassNotFoundException,SQLException{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/lti","root","tuningfork1212");
Statement stmnt = con.createStatement();
ResultSet rs = stmnt.executeQuery("SELECT * from enroll");
List<Enroll> enrollList= new ArrayList<Enroll>();
while (rs.next()){
int studentId = rs.getInt(1);
int courseId = rs.getInt(2);
java.util.Date date = rs.getDate(3);
Student tempStudent;
Course tempCourse;
PreparedStatement preparedStatement = con.prepareStatement("SELECT * from student WHERE id=?");
preparedStatement.setInt(1,studentId);
ResultSet rs2 = preparedStatement.executeQuery();
tempStudent = new Student(rs2.getInt(1),rs2.getString(2),rs2.getDate(3));
PreparedStatement preparedStatement1 = con.prepareStatement("SELECT * from course WHERE courseid=?");
preparedStatement1.setInt(1,courseId);
ResultSet rs3 = preparedStatement1.executeQuery();
tempCourse = new Course(rs3.getInt(1),rs3.getString(2),rs3.getInt(3),rs3.getInt(4));
enrollList.add(new Enroll(tempStudent,tempCourse,date));
}
int numOfEnrolls=0;
numOfEnrolls=enrollList.size();
Enroll[] enrolls = new Enroll[numOfEnrolls];
for(int i=0;i<numOfEnrolls;i++){
enrolls[i]=new Enroll(enrollList.get(i).getStudent(),enrollList.get(i).getCourse(),enrollList.get(i).getEnrollmentDate());
}
return enrolls;
}
}
|
package kr.or.ddit.newsboard.controller;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.or.ddit.newsboard.service.NewsBoardService;
import kr.or.ddit.vo.SuccessBoardVO;
import kr.or.ddit.vo.newsboardVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/user/newsboard/")
public class NewsBoardController {
@Autowired
private NewsBoardService service;
@RequestMapping("newsboardList")
public ModelAndView newsboardList(HttpServletRequest request,
ModelAndView modelAndView) {
List<newsboardVO> newsboardList = null;
try {
newsboardList = service.newsboardList();
} catch (Exception e) {
e.printStackTrace();
}
// breadcrumb
modelAndView.addObject("breadcrumb_title", "뉴스 센터");
modelAndView.addObject("breadcrumb_first", "소식 게시판");
modelAndView.addObject("breadcrumb_first_url", request.getContextPath() + "/user/newsboard/newsboardList.do");
modelAndView.addObject("newsboardList", newsboardList);
modelAndView.setViewName("user/newsboard/newsboardList");
return modelAndView;
}
@RequestMapping("newsboardForm")
public ModelAndView newsboardView(HttpServletRequest request,
ModelAndView modelAndView) throws Exception {
modelAndView.addObject("breadcrumb_title", "뉴스 센터");
modelAndView.addObject("breadcrumb_first", "소식 게시판");
modelAndView.addObject("breadcrumb_first_url", request.getContextPath() + "/user/newsboard/newsboardList.do");
modelAndView.addObject("breadcrumb_second", "소식 게시글 등록");
modelAndView.setViewName("user/newsboard/newsboardForm");
return modelAndView;
}
@RequestMapping("newsboardView")
public ModelAndView newsboardView(ModelAndView modelAndView,
String news_no) throws Exception {
Map<String, String> params = new HashMap<String, String>();
params.put("news_no", news_no);
newsboardVO newsBoardInfo = service.newsboardInfo(params);
modelAndView.addObject("newsboardInfo", newsBoardInfo);
modelAndView.setViewName("user/newsboard/newsboardView");
return modelAndView;
}
@RequestMapping("newsboardInsert")
public String insertNewsboard (newsboardVO newsboardInfo,
HttpServletRequest request,
HttpServletResponse response,
String news_title,
String news_content,
String mem_id) throws Exception{
newsboardInfo.setMem_id(mem_id);
newsboardInfo.setNews_title(news_title);
newsboardInfo.setNews_content(news_content);
service.insertNewsboard(newsboardInfo);
String taskResult = null;
String message = null;
taskResult = "success";
message = URLEncoder.encode("게시글이 정상적으로 등록되었습니다.", "UTF-8");
return "redirect:/user/newsboard/newsboardList.do?taskResult=" + taskResult + "&message=" + message;
}
@RequestMapping("modifyNewsBoard")
public String modifyNewsBoard(newsboardVO newsboardInfo) throws Exception {
int chk = service.modifyNewsBoard(newsboardInfo);
String taskResult = null;
String message = null;
if (chk > 0) {
taskResult = "success";
message = URLEncoder.encode("게시글이 정상적으로 수정되었습니다.", "UTF-8");
} else {
taskResult = "warning";
message = URLEncoder.encode("게시글 수정에 실패했습니다.", "UTF-8");
}
return "redirect:/user/newsboard/newsboardList.do?taskResult=" + taskResult + "&message=" + message;
}
@RequestMapping("deleteNewsBoard")
public String deleteNewsBoard(String news_no) throws Exception {
Map<String, String> params = new HashMap<String, String>();
params.put("news_no", news_no);
int chk = service.deleteNewsBoard(params);
String taskResult = null;
String message = null;
if (chk > 0) {
taskResult = "success";
message = URLEncoder.encode("게시글이 정상적으로 삭제되었습니다.", "UTF-8");
} else {
taskResult = "warning";
message = URLEncoder.encode("게시글 삭제에 실패했습니다.", "UTF-8");
}
return "redirect:/user/newsboard/newsboardList.do?taskResult=" + taskResult + "&message=" + message;
}
}
|
package pages;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import pojo.Book;
public class BillServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.handleRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.handleRequest(request, response);
}
protected void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<Book,Integer> map = (Map<Book, Integer>) request.getAttribute("map");
Set<Entry<Book, Integer>> entries = map.entrySet();
float totalPrice = 0;
for (Entry<Book, Integer> entry : entries)
{
Book key = entry.getKey();
int quantity = entry.getValue();
totalPrice = totalPrice + key.getPrice() * quantity;
}
try( PrintWriter out = response.getWriter())
{
out.println("Total Price : "+totalPrice);
out.println("<input type='submit' value='Logout'/>");
}
}
}
|
package network;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Logger;
import settings.Settings;
public class ConnectionAcceptor extends Thread{
private ConnectionCallback callback;
private ServerSocket socket;
public ConnectionAcceptor(ConnectionCallback callback)
{
this.callback = callback;
}
public void run()
{
while(true)
{
try
{
if(socket == null)
{
//START LISTENING
socket = new ServerSocket(Network.PORT);
}
//CHECK IF WE HAVE MAX CONNECTIONS CONNECTIONS
if(Settings.getInstance().getMaxConnections() <= callback.getActiveConnections().size())
{
//IF SOCKET IS OPEN CLOSE IT
if(!socket.isClosed())
{
socket.close();
}
Thread.sleep(100);
}
else
{
//REOPEN SOCKET
if(socket.isClosed())
{
socket = new ServerSocket(Network.PORT);
}
//ACCEPT CONNECTION
Socket connectionSocket = socket.accept();
//CHECK IF SOCKET IS NOT LOCALHOST || WE ARE ALREADY CONNECTED TO THAT SOCKET || BLACKLISTED
if(/*connectionSocket.getInetAddress().isSiteLocalAddress() || connectionSocket.getInetAddress().isAnyLocalAddress() || connectionSocket.getInetAddress().isLoopbackAddress() ||*/ callback.isConnectedTo(connectionSocket.getInetAddress()) || PeerManager.getInstance().isBlacklisted(connectionSocket.getInetAddress()))
{
//DO NOT CONNECT TO OURSELF/EXISTING CONNECTION
connectionSocket.close();
}
else
{
//CREATE PEER
new Peer(callback, connectionSocket);
}
}
}
catch(Exception e)
{
e.printStackTrace();
Logger.getGlobal().warning("Error accepting new connection");
}
}
}
}
|
////////////////////////////////////////////////////////////////////////////////////
// MIT License //
// //
// Copyright (c) 2020 Utkarsh Priyam //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in all //
// copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //
// SOFTWARE. //
////////////////////////////////////////////////////////////////////////////////////
import hangouts_history_reader.elements.HangoutsChat;
import java.io.*;
import java.util.*;
public class Main {
private static long time;
private static void markStartTime() {
time = System.nanoTime();
}
private static long readAndPrintTime(String message) {
long delta = System.nanoTime() - time;
if (message != null) {
System.out.println(message + ": " + delta / 1_000_000.0 + " ms");
System.out.println(message + ": " + delta / 1_000_000_000.0 + " s");
}
return delta;
}
public static void main(String[] args) throws IOException {
dumpChats();
// liveDataParse();
}
private static void dumpChats() throws IOException {
markStartTime();
int i = 0;
for (HangoutsChat chat : loadChats("Hangouts.json")) {
String filename = "chat log dump/" + fixDirectoryName(chat.CHAT_NAME) + " (" + chat.CHAT_ID + ").txt";
PrintStream out = new PrintStream(new FileOutputStream(filename));
chat.print(out);
out.close();
System.out.println("Done Printing Chat #" + ++i);
}
readAndPrintTime("Printed " + i + " Chat Logs to files");
}
private static String fixDirectoryName(String name) {
return name.replace('/', '_').replace(':', '_');
}
private static void liveDataParse() throws IOException {
Map<String, HangoutsChat> chatIDToChatMap = new HashMap<>();
Map<String, List<String>> chatNameToIDMap = new HashMap<>();
for (HangoutsChat chat : loadChats("Hangouts.json")) {
chatIDToChatMap.put(chat.CHAT_ID, chat);
chatNameToIDMap.computeIfAbsent(chat.CHAT_NAME, k -> new LinkedList<>()).add(chat.CHAT_ID);
}
System.out.println("Finished processing data. Ready to search.");
System.out.println();
java.util.Scanner scanner = new java.util.Scanner(System.in);
System.out.println("Please enter a search mode. Use \"HELP\" to access the help menu.");
outsideLoop:
while (true) {
switch (scanner.nextLine().toUpperCase()) {
case "HELP":
printHelpMenu();
break;
case "CHAT":
searchChats(scanner, chatNameToIDMap, chatIDToChatMap);
break;
case "QUIT":
break outsideLoop;
default:
System.err.print("Invalid search mode. ");
System.out.println("Use \"HELP\" to access the help menu.");
break;
}
System.out.println("Please enter a search mode.");
}
System.out.println("Terminating processes...");
}
private static void searchChats(java.util.Scanner s, Map<String, List<String>> chatNameToIDMap,
Map<String, HangoutsChat> chatIDToChatMap) {
throw new RuntimeException("Complete searchChats(...)");
}
private static void printHelpMenu() {
System.out.println("Hangouts History Parser Help Menu");
System.out.println("---------------------------------");
System.out.println("\"CHAT\" - Search chats");
System.out.println("\"QUIT\" - Quit program");
System.out.println("\"HELP\" - Access this menu");
}
private static Set<HangoutsChat> loadChats(String filename) throws IOException {
Scanner scanner = new Scanner(new FileInputStream(filename));
System.out.println("Loading Hangouts data from \"" + filename + "\"...");
JSONValue json = JSONParser.parseNonRecursive(scanner);
System.out.println("Finished loading data. Resolving Chat IDs...");
Collection<JSONValue> conversations = json.findElements("conversations[*]");
Set<HangoutsChat> chats = new HashSet<>();
for (JSONValue conversation : conversations)
if (conversation.type() == JSONValue.ValueType.OBJECT)
chats.add(generateChatLog((JSONObject) conversation));
return chats;
}
private static HangoutsChat generateChatLog(JSONObject hangoutsConversation) {
JSONObject conversation = (JSONObject) hangoutsConversation.getValue("conversation");
JSONArray events = (JSONArray) hangoutsConversation.getValue("events");
return new HangoutsChat(conversation, events);
}
private static void parsingBenchmark() throws IOException {
System.out.println("Starting JSON Parsing Benchmark\n");
Scanner scanner = new Scanner(new FileInputStream("Hangouts.json"));
markStartTime();
JSONValue json = JSONParser.parseNonRecursive(scanner);
long t = readAndPrintTime("Time to parse JSON");
System.out.println("Average time per token: " + t / 1000.0 / scanner.tokensPassed() + " μs");
Collection<JSONValue> conversations = json.findElements("conversations[*]");
System.out.println();
markStartTime();
Set<HangoutsChat> chats = new HashSet<>();
for (JSONValue conversation : conversations)
if (conversation.type() == JSONValue.ValueType.OBJECT)
chats.add(generateChatLog((JSONObject) conversation));
readAndPrintTime("Time to process chats");
System.out.println();
System.out.println("Number of Chats: " + chats.size());
}
private static void scanningBenchmark() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("Hangouts.json")));
String s;
char[] arr;
markStartTime();
while ((s = br.readLine()) != null) {
arr = s.toCharArray();
for (char c : arr) ;
}
readAndPrintTime("BufferedReader");
System.out.println();
Scanner sc = new Scanner(new FileInputStream("Hangouts.json"));
markStartTime();
while (sc.hasMore())
sc.advance();
long t = readAndPrintTime("Scanner");
System.out.println();
System.out.println("Number of tokens: " + sc.tokensPassed());
System.out.println("Time per token: " + t / 1000.0 / sc.tokensPassed() + " μs");
}
}
|
package tinkoff.androidcourse.model.db;
import com.raizlabs.android.dbflow.annotation.Database;
/**
* Created by entr0x on 23.04.2017.
*/
@Database(name = ChatDatabase.DB_NAME, version = ChatDatabase.VERSION)
public final class ChatDatabase {
public static final String DB_NAME = "CHAT_DB";
public static final int VERSION = 1;
}
|
package com.danielvizzini.util;
/**
* Interface to standardize how pertinent information is ascertained to solve Knapsack problems
*/
public interface KnapsackItem {
/**
* @return the profit of the knapsack item (e.g. the value of a jug of olive oil)
*/
public abstract Double getProfit();
/**
* @return the weight of the knapsack item (e.g. the weight of a jug of olive oil)
*/
public abstract Integer getWeight();
}
|
package co.aca.model.response;
import co.aca.model.Course;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.util.List;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ResponseCourse {
private String isSuccessful;
private Course course;
private List<Course> courseList;
private String errorMessage;
private String successMessage;
public ResponseCourse(Course course) {
setIsSuccessful("1");
setCourse(course);
}
public ResponseCourse(List<Course> courseList) {
setIsSuccessful("1");
setCourseList(courseList);
}
public ResponseCourse(String message, String isSuccess) {
if(isSuccess.equals("1")){
setSuccessMessage(message);
}else{
setErrorMessage(message);
}
setIsSuccessful(isSuccess);
}
public Course getCourse() {
return course;
}
public List<Course> getCourseList() {
return courseList;
}
public void setCourseList(List<Course> courseList) {
this.courseList = courseList;
}
public void setCourse(Course course) {
this.course = course;
}
public String getIsSuccessful() {
return isSuccessful;
}
public void setIsSuccessful(String isSuccessful) {
this.isSuccessful = isSuccessful;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public String getSuccessMessage() {
return successMessage;
}
public void setSuccessMessage(String successMessage) {
this.successMessage = successMessage;
}
}
|
/*
* 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 crawlers;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerAM;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerAR;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerAYM;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerBG;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerBN;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerCA;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerCS;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerDA;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerDE;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerEL;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerEN;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerEO;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerES;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerFA;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerFIL;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerFR;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerHE;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerHI;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerHU;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerID;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerIT;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerJA;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerKM;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerKO;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerMG;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerMK;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerNE;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerOR;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerPA;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerPL;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerPS;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerPT;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerRO;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerRU;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerSQ;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerSR;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerSV;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerSW;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerTET;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerTR;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerUR;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerZHS;
import crawlers.publishers.globalVoices.GlobalVoicesCrawlerZHT;
/**
*
* @author zua
*/
public class GlobalVoicesAggregator {
public void aggregate() {
try {
new GlobalVoicesCrawlerAM().crawl();
new GlobalVoicesCrawlerAR().crawl();
new GlobalVoicesCrawlerAYM().crawl();
new GlobalVoicesCrawlerBG().crawl();
new GlobalVoicesCrawlerBN().crawl();
new GlobalVoicesCrawlerCA().crawl();
new GlobalVoicesCrawlerCS().crawl();
new GlobalVoicesCrawlerDA().crawl();
new GlobalVoicesCrawlerDE().crawl();
new GlobalVoicesCrawlerEL().crawl();
new GlobalVoicesCrawlerEN().crawl();
new GlobalVoicesCrawlerEO().crawl();
new GlobalVoicesCrawlerES().crawl();
new GlobalVoicesCrawlerFA().crawl();
new GlobalVoicesCrawlerFIL().crawl();
new GlobalVoicesCrawlerFR().crawl();
new GlobalVoicesCrawlerHE().crawl();
new GlobalVoicesCrawlerHI().crawl();
new GlobalVoicesCrawlerHU().crawl();
new GlobalVoicesCrawlerID().crawl();
new GlobalVoicesCrawlerIT().crawl();
new GlobalVoicesCrawlerJA().crawl();
new GlobalVoicesCrawlerKM().crawl();
new GlobalVoicesCrawlerKO().crawl();
//new GlobalVoicesCrawlerMG().crawl();
new GlobalVoicesCrawlerMK().crawl();
new GlobalVoicesCrawlerNE().crawl();
new GlobalVoicesCrawlerOR().crawl();
new GlobalVoicesCrawlerPA().crawl();
new GlobalVoicesCrawlerPL().crawl();
new GlobalVoicesCrawlerPS().crawl();
new GlobalVoicesCrawlerPT().crawl();
new GlobalVoicesCrawlerRO().crawl();
new GlobalVoicesCrawlerRU().crawl();
new GlobalVoicesCrawlerSQ().crawl();
new GlobalVoicesCrawlerSR().crawl();
new GlobalVoicesCrawlerSV().crawl();
new GlobalVoicesCrawlerSW().crawl();
new GlobalVoicesCrawlerTET().crawl();
new GlobalVoicesCrawlerTR().crawl();
new GlobalVoicesCrawlerUR().crawl();
new GlobalVoicesCrawlerZHS().crawl();
new GlobalVoicesCrawlerZHT().crawl();
} catch(Throwable t) {}
}
}
|
package mx.redts.simoc.model.entities;
// Generated 27/10/2013 05:02:01 PM by Hibernate Tools 3.4.0.CR1
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Parametros generated by hbm2java
*/
@Entity
@Table(name = "parametros", schema = "public")
public class Parametros implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 7056457490755130056L;
private String paramName;
private String paramValue;
private String paramDesc;
public Parametros() {
}
public Parametros(String paramName) {
this.paramName = paramName;
}
public Parametros(String paramName, String paramValue, String paramDesc) {
this.paramName = paramName;
this.paramValue = paramValue;
this.paramDesc = paramDesc;
}
@Column(name = "param_desc", length = 100)
public String getParamDesc() {
return this.paramDesc;
}
@Id
@Column(name = "param_name", unique = true, nullable = false, length = 30)
public String getParamName() {
return this.paramName;
}
@Column(name = "param_value", length = 250)
public String getParamValue() {
return this.paramValue;
}
public void setParamDesc(String paramDesc) {
this.paramDesc = paramDesc;
}
public void setParamName(String paramName) {
this.paramName = paramName;
}
public void setParamValue(String paramValue) {
this.paramValue = paramValue;
}
}
|
package net.sf.throughglass.templates;
/**
* Created by guang_hik on 14-8-10.
*/
public class MemoryCache<T> {
}
|
package com.baopinghui.bin.mapper.app;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import com.baopinghui.bin.dto.ResultDto;
import com.baopinghui.bin.entity.DianMianEntity;
import com.baopinghui.bin.util.MyMapper;
public interface DianMianMapper extends MyMapper<DianMianEntity> {
//新增店铺
Integer insertDianMian(DianMianEntity dm);
//更新店的消息
Integer updateDianMian(DianMianEntity dm);
//删除店铺
Integer deleteDianMain(@Param(value="id")int id);
//查询所有店面
List<Map<String,Object>> selectDianMian();
//id查询
Map<String,Object> selectDianMian2(@Param(value="id")int id);
}
|
package com.jwebsite.dao;
import java.util.List;
import com.jwebsite.vo.Model;
public interface ModelDao {
//根据ID删除模型
public void delModel(int ID) throws Exception;
//更新记录
public void updateModel(Model md) throws Exception;
//添加模型
public void insertModel(Model md) throws Exception;
//查询模型
public List<Model> queryModel(int SiteID)throws Exception;
public List<Model> queryModel(String sql)throws Exception;
//获取一个模型
public Model queryAModel(String ID)throws Exception;
//执行一个sql
public int ExecuteSQL(String sql)throws Exception;
//修改状态
public int UpdateState(String Action,String ID)throws Exception;
}
|
package com.sndo.fcm.demo4;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import com.sndo.fcm.demo4.util.FcmUtil;
import com.sndo.fcm.demo4.util.LContext;
import com.sndo.fcm.demo4.util.ToastUtil;
import java.lang.reflect.Method;
/**
* @author 张全
*/
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static int ID = 1;
/**
* 监控令牌的生成
* <p>
* FCM SDK 会为客户端应用实例生成一个注册令牌。如果您希望指定单一目标设备或者创建设备组,则需要通过继承 FirebaseMessagingService 并重写 onNewToken 来获取此令牌。
* 获取该令牌后,您可以将其发送到应用服务器,并使用您偏好的方法进行存储。
*
* @param token
*/
@Override
public void onNewToken(@NonNull String token) {
super.onNewToken(token);
FcmUtil.log("MyFirebaseMessagingService onNewToken, token=" + token);
FcmUtil.saveToken(token);
}
@Override
public void onMessageReceived(@NonNull final RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
// [START_EXCLUDE]
// There are two types of messages data messages and notification messages. Data messages
// are handled
// here in onMessageReceived whether the app is in the foreground or background. Data
// messages are the type
// traditionally used with GCM. Notification messages are only received here in
// onMessageReceived when the app
// is in the foreground. When the app is in the background an automatically generated
// notification is displayed.
// When the user taps on the notification they are returned to the app. Messages
// containing both notification
// and data payloads are treated as notification messages. The Firebase console always
// sends notification
// messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
// [END_EXCLUDE]
// TODO(developer): Handle FCM messages here.
// Not getting messages here? See why this may be: https://goo.gl/39bRNJ
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
ToastUtil.show("onMessageReceived msg=" + remoteMessage);
}
});
FcmUtil.log("==================RemoteMessage==============");
Class<? extends RemoteMessage> aClass = remoteMessage.getClass();
Method[] declaredMethods = aClass.getDeclaredMethods();
for (Method method : declaredMethods) {
method.setAccessible(true);
if (method.getName().startsWith("get")) {
Object value = null;
try {
value = method.invoke(remoteMessage);
FcmUtil.log(method.getName() + "=" + value);
} catch (Exception e) {
e.printStackTrace();
}
}
}
FcmUtil.log("==================RemoteMessage==============");
// Check if message contains a data payload. 检查是否包含data
if (remoteMessage.getData().size() > 0) {
FcmUtil.log("MyFirebaseMessagingService onMessageReceived, data: " + remoteMessage.getData());
//do something
}
// Check if message contains a notification payload. 检查是否包含notification
if (remoteMessage.getNotification() != null) {
final String title = remoteMessage.getNotification().getTitle();
final String body = remoteMessage.getNotification().getBody();
FcmUtil.log("MyFirebaseMessagingService onMessageReceived, Notification[title: " + title + ",body=" + body + "]");
//发送notification
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
sendNotification(MyFirebaseMessagingService.this, title, body);
}
});
}
}
public static void sendNotification(Context ctx, String title, String messageBody) {
FcmUtil.log("发送通知 title=" + title + ",content=" + messageBody);
if (TextUtils.isEmpty(messageBody)) return;
Intent intent = new Intent(ctx, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = LContext.getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(ctx, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) LContext.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
// Since android O notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
LContext.getString(R.string.app_name),
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(ID, notificationBuilder.build());
ID++;
}
// public static void sendNotification(Context ctx, String content) {
// NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
// NotificationCompat.Builder mBuilder;
// String channelId = "1";
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// NotificationChannel channel = new NotificationChannel(channelId,
// "Channel1", NotificationManager.IMPORTANCE_DEFAULT);
// channel.enableLights(false);
// channel.enableVibration(false);
// channel.setVibrationPattern(new long[]{0});
// channel.setSound(null, null);
// channel.setLightColor(Color.RED); //小红点颜色
// channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
// channel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
// mBuilder = new NotificationCompat.Builder(ctx, channelId);
// notificationManager.createNotificationChannel(channel);
// } else {
// mBuilder = new NotificationCompat.Builder(ctx);
// mBuilder.setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE)
// .setVibrate(new long[]{0})
// .setSound(null);
// }
//
// Intent intent = new Intent(ctx, MainActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, intent,
// PendingIntent.FLAG_UPDATE_CURRENT);
// mBuilder.setContentTitle(LContext.getString(R.string.app_name))
// .setContentText(content)
// .setContentIntent(pendingIntent)
// .setWhen(System.currentTimeMillis())
// .setSmallIcon(R.mipmap.ic_launcher)
// .setAutoCancel(true);
//
// Notification notify = mBuilder.build();
// notificationManager.notify(ID, notify);
// ID++;
// }
}
|
package by.partymaker.dto;
import by.partymaker.entities.Account;
import by.partymaker.entities.Event;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.sun.xml.internal.stream.Entity;
import java.util.Date;
/**
* Created on 15.07.2016
*
* @author user
*/
public class EventDto {
private String name;
private String description;
private Date eventTime;
private String meetupPlace;
private Integer minPeople;
private Integer maxPeople;
@JsonIgnore
public Event getEntity(Account account) {
Event event = new Event(name, description, eventTime, meetupPlace, minPeople, maxPeople);
event.setOwner(account);
return event;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public Date getEventTime() {
return eventTime;
}
public String getMeetupPlace() {
return meetupPlace;
}
public Integer getMinPeople() {
return minPeople;
}
public Integer getMaxPeople() {
return maxPeople;
}
}
|
package server.sport.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import server.sport.model.Location;
import server.sport.service.LocationService;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.List;
import java.util.Map;
@CrossOrigin
@RestController
@RequestMapping("/api/locations")
public class LocationController {
@Autowired
LocationService locationService;
//////Getting all locations based on start date and end date ??
@GetMapping("/all")
public ResponseEntity<List<Location>> getAllLocations (@RequestParam(required = false) Timestamp startAt, @RequestParam(required = false) Timestamp endAt) throws ParseException { //how to handle exception???
return locationService.getAllLocations(startAt, endAt);
}
@GetMapping
public ResponseEntity<Map<String, Object>> getPageOfLocations (
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "3") int size,
@RequestParam(defaultValue = "courtName,desc") String[] sort) {
return locationService.getPageOfLocations(page, size, sort);
}
@PostMapping
public ResponseEntity<Location> createLocation(@RequestBody Location location){
return locationService.createLocation(location);
}
@PutMapping("/{location_id}")
public ResponseEntity<Location> updateLocation(@PathVariable("location_id") int locationId, @RequestBody Location location){
return locationService.updateLocation(locationId, location);
}
@DeleteMapping("/{location_id}")
public ResponseEntity<HttpStatus> deleteLocation (@PathVariable("location_id") int locationId){
return locationService.deleteLocation(locationId);
}
}
|
package com.karya.bean;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
public class BankReconcileBean {
private int bankrecId;
@NotNull
@NotEmpty(message = "Please enter the bank account")
private String bankAccount;
@NotNull
@NotEmpty(message = "Please mention the posting date")
private String postingDate;
@NotNull
@NotEmpty(message = "Please enter the payment entry")
private String entrySeries;
@NotNull
@NotEmpty(message = "Please enter debit")
private String debit;
@NotNull
@NotEmpty(message = "Please enter credit")
private String credit;
@NotNull
@NotEmpty(message = "Please enter the against account")
private String againstAccount;
@NotNull
@NotEmpty(message = "Please enter the reference name")
private String referenceName;
@NotNull
@NotEmpty(message = "Please enter the reference date")
private String referenceDate;
@NotNull
@NotEmpty(message = "Please enter the clearance date")
private String clearanceDate;
@NotNull
@NotEmpty(message = "Please enter the currency")
private String currency;
public int getBankrecId() {
return bankrecId;
}
public void setBankrecId(int bankrecId) {
this.bankrecId = bankrecId;
}
public String getBankAccount() {
return bankAccount;
}
public void setBankAccount(String bankAccount) {
this.bankAccount = bankAccount;
}
public String getPostingDate() {
return postingDate;
}
public void setPostingDate(String postingDate) {
this.postingDate = postingDate;
}
public String getEntrySeries() {
return entrySeries;
}
public void setEntrySeries(String entrySeries) {
this.entrySeries = entrySeries;
}
public String getDebit() {
return debit;
}
public void setDebit(String debit) {
this.debit = debit;
}
public String getCredit() {
return credit;
}
public void setCredit(String credit) {
this.credit = credit;
}
public String getAgainstAccount() {
return againstAccount;
}
public void setAgainstAccount(String againstAccount) {
this.againstAccount = againstAccount;
}
public String getReferenceName() {
return referenceName;
}
public void setReferenceName(String referenceName) {
this.referenceName = referenceName;
}
public String getReferenceDate() {
return referenceDate;
}
public void setReferenceDate(String referenceDate) {
this.referenceDate = referenceDate;
}
public String getClearanceDate() {
return clearanceDate;
}
public void setClearanceDate(String clearanceDate) {
this.clearanceDate = clearanceDate;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
}
|
import java.math.BigInteger;
import java.util.*;
public class FibonacciLastDigit {
private static int getFibonacciLastDigitNaive(int n) {
if (n <= 1)
return n;
int previous = 0;
int current = 1;
for (int i = 0; i < n - 1; ++i) {
int tmp_previous = previous;
previous = current;
current = tmp_previous + current;
}
return current % 10;
}
private static int getFibonaciLastDigiItteration(int n) {
if (n <= 1)
return n;
int previous = 0;
int current = 1;
for (int i = 0; i < n - 1; ++i) {
int tmp_previous = previous;
previous = current;
current = (tmp_previous + current) % 10;
}
return current;
}
private static int getFibonaciLastDigiFastDoubling(int n) {
BigInteger a = BigInteger.ZERO;
BigInteger b = BigInteger.ONE;
for (int bit = Integer.highestOneBit(n); bit != 0; bit >>>= 1) {
// Loop invariant: a = F(m), b = F(m+1)
// Double it
BigInteger d = multiply(a, b.shiftLeft(1).subtract(a));
BigInteger e = multiply(a, a).add(multiply(b, b));
a = d;
b = e;
// Advance by one conditionally
if ((n & bit) != 0) {
BigInteger c = a.add(b);
a = b;
b = c;
}
}
return a.mod(BigInteger.TEN).intValue();
}
private static BigInteger multiply(BigInteger x, BigInteger y) {
return x.multiply(y);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
long startTime = System.nanoTime();
int r1 = getFibonaciLastDigiItteration(n);
long endTime = System.nanoTime();
long duration = (endTime - startTime) / 1000;
System.out.println(String.format("Reslut: %s , It take: %s ms", r1, duration));
startTime = System.nanoTime();
int r2 = getFibonaciLastDigiFastDoubling(n);
endTime = System.nanoTime();
duration = (endTime - startTime) / 1000;
System.out.println(String.format("Reslut: %s , It take: %s ms", r2, duration));
}
}
|
package travel.api.ws;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import travel.api.dto.response.user.UserInfoResponseDTO;
import travel.api.table.entity.PrivateMsg;
import travel.api.table.mapper.PrivateMsgMapper;
import travel.api.table.mapper.UserMapper;
import travel.api.util.Constant;
import travel.api.util.TimeUtil;
import travel.api.ws.dto.CommonMsgRequestDTO;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author Administrator
* @ServerEndpoint 这个注解有什么作用?
* <p>
* 这个注解用于标识作用在类上,它的主要功能是把当前类标识成一个WebSocket的服务端
* 注解的值用户客户端连接访问的URL地址
*/
@Slf4j
@Component
@ServerEndpoint("/websocket/{name}")
public class WebSocket {
@Resource
UserMapper userMapper;
@Resource
PrivateMsgMapper privateMsgMapper;
private static WebSocket webSocket;
@PostConstruct
public void init() {
webSocket = this;
// 初使化时将已静态化的configParam实例化
webSocket.userMapper = this.userMapper;
webSocket.privateMsgMapper = this.privateMsgMapper;
}
/**
* 与某个客户端的连接对话,需要通过它来给客户端发送消息
*/
private Session session;
/**
* 标识当前连接客户端的用户名
*/
private String name;
/**
* 用于存所有的连接服务的客户端,这个对象存储是安全的
*/
private static ConcurrentHashMap<String, WebSocket> webSocketSet = new ConcurrentHashMap<>();
@OnOpen
public void OnOpen(Session session, @PathParam(value = "name") String name) {
this.session = session;
this.name = name;
// name是用来表示唯一客户端,如果需要指定发送,需要指定发送通过name来区分
webSocketSet.put(name, this);
log.info("[WebSocket] 连接成功,当前连接人数为:{}", webSocketSet.size());
}
@OnClose
public void OnClose() {
webSocketSet.remove(this.name);
log.info("[WebSocket] 退出成功,当前连接人数为:{}", webSocketSet.size());
}
@OnMessage
public void OnMessage(String message) {
CommonMsgRequestDTO dto = JSONObject.parseObject(message, CommonMsgRequestDTO.class);
log.info("[WebSocket] 收到消息:{}", message);
// 私聊
if (1 == dto.getMsgType()) {
PrivateMsg privateMsg = new PrivateMsg();
privateMsg.setFromUser(dto.getFromUser());
privateMsg.setToUser(dto.getToUser());
privateMsg.setMessage(dto.getMessage());
privateMsg.setType(dto.getType());
privateMsg.setIsDelete("N");
privateMsg.setIsRead("N");
privateMsg.setIsOld("N");
privateMsg.setTime(TimeUtil.getNormalTime());
webSocket.privateMsgMapper.insert(privateMsg);
JSONObject fromMsg = JSONObject.parseObject(message);
JSONObject toMsg = JSONObject.parseObject(message);
UserInfoResponseDTO from = webSocket.userMapper.userInfo(dto.getFromUser());
toMsg.put("isMy", "N");
toMsg.put("avatar", from.getAvatar());
toMsg.put("time", privateMsg.getTime());
toMsg.put("id",privateMsg.getId());
AppointSending(dto.getToUser().toString(), toMsg.toJSONString());
fromMsg.put("isMy", "Y");
fromMsg.put("avatar", from.getAvatar());
fromMsg.put("id",privateMsg.getId());
fromMsg.put("time", privateMsg.getTime());
AppointSending(dto.getFromUser().toString(), fromMsg.toJSONString());
}
// 群聊
if (2 == dto.getMsgType()) {
log.info("[WebSocket] 群聊开发中");
}
}
/**
* 群发
*
* @param message
*/
public void GroupSending(String message) {
for (String name : webSocketSet.keySet()) {
try {
webSocketSet.get(name).session.getBasicRemote().sendText(message);
} catch (Exception e) {
log.info("[WebSocket] 发送私聊失败 --> " + e.getMessage());
}
}
}
/**
* 指定发送
*
* @param name
* @param message
*/
public void AppointSending(String name, String message) {
try {
webSocketSet.get(name).session.getBasicRemote().sendText(message);
log.info("[WebSocket] 发送私聊成功");
} catch (Exception e) {
log.info("[WebSocket] 不在线 ");
e.printStackTrace();
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.ss
*/
package com.pmm.sdgc.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
*
* @author setinf
*/
@Entity
@Table(name = "escala_incompativel")
public class EscalaIncompativel implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@ManyToOne
@JoinColumn(name = "id_escala_tipo_01", referencedColumnName = "id")
private EscalaTipo escalaTipo1;
@ManyToOne
@JoinColumn(name = "id_escala_tipo_02", referencedColumnName = "id")
private EscalaTipo escalaTipo2;
//GET_SET
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public EscalaTipo getEscalaTipo1() {
return escalaTipo1;
}
public void setEscalaTipo1(EscalaTipo escalaTipo1) {
this.escalaTipo1 = escalaTipo1;
}
public EscalaTipo getEscalaTipo2() {
return escalaTipo2;
}
public void setEscalaTipo2(EscalaTipo escalaTipo2) {
this.escalaTipo2 = escalaTipo2;
}
}
|
package net.lantrack.framework.jms.kafka;
import java.io.IOException;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.support.PropertiesLoaderUtils;
/**
* KafKa Client Properties Config
* @date 2019年5月13日
*/
public class PropertiesConfig {
private static Logger logger = LoggerFactory.getLogger(PropertiesConfig.class);
private static volatile Properties properties;
public static Properties getProperties() {
if(properties==null) {
synchronized(PropertiesConfig.class) {
if(properties==null) {
try {
properties = PropertiesLoaderUtils.loadAllProperties("properties/kafka.properties");
} catch (IOException e) {
logger.error("KafKa Properties load error:{}",e.getMessage());
}
}
}
}
return properties;
}
}
|
package com.spreadtrum.android.eng;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.nio.charset.Charset;
public class PhaseCheck extends Activity {
private engfetch mEf;
private String mText;
private TextView mTextView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.phasecheck);
this.mTextView = (TextView) findViewById(R.id.text_view);
this.mEf = new engfetch();
byte[] inputBytes = new byte[2048];
this.mText = new String(inputBytes, 0, this.mEf.enggetphasecheck(inputBytes, 2048), Charset.defaultCharset());
String str = getIntent().getStringExtra("textFilter");
if (str == null || !str.equals("filter")) {
this.mTextView.setText(this.mText);
return;
}
this.mTextView.setText(this.mText.replaceAll("(?s)DOWNLOAD.*", "").trim());
}
}
|
package com.ipincloud.iotbj.srv.service.impl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import com.alibaba.fastjson.JSONObject;
import com.ipincloud.iotbj.srv.domain.SensorTrigger;
import com.ipincloud.iotbj.srv.dao.*;
import com.ipincloud.iotbj.srv.service.SensorTriggerService;
import com.ipincloud.iotbj.utils.ParaUtils;
//(SensorTrigger)触发器管理 服务实现类
//generate by redcloud,2020-07-24 19:59:20
@Service("SensorTriggerService")
public class SensorTriggerServiceImpl implements SensorTriggerService {
@Resource
private SensorTriggerDao sensorTriggerDao;
//@param id 主键
//@return 实例对象SensorTrigger
@Override
public SensorTrigger queryById(Long id){
return this.sensorTriggerDao.queryById(id);
}
//@param jsonObj 过滤条件等
//@return 对象查询SensorTrigger 分页
@Override
public Map sensorTriggerList(JSONObject jsonObj){
int totalRec = this.sensorTriggerDao.countSensorTriggerList(jsonObj);
jsonObj = ParaUtils.checkStartIndex(jsonObj,totalRec);
List<Map> pageData = this.sensorTriggerDao.sensorTriggerList(jsonObj);
Map retMap = new HashMap();
retMap.put("pageData",pageData);
retMap.put("totalRec",totalRec);
retMap.put("cp",jsonObj.get("cp"));
retMap.put("rop",jsonObj.get("rop"));
return retMap;
}
//@param jsonObj 调用参数
//@return 影响记录数
@Override
@Transactional(isolation = Isolation.REPEATABLE_READ,propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
public Integer deletesSensorTriggerInst(JSONObject jsonObj){
Integer delNum1 = this.sensorTriggerDao.deletesInst(jsonObj);
return delNum1;
}
//@param jsonObj 调用参数
//@return 实例对象SensorTrigger
@Override
public JSONObject addInst( JSONObject jsonObj){
jsonObj = ParaUtils.removeSurplusCol(jsonObj,"id,titel,stream_id,cond,dataval,pushway,created,updated,stream_title");
this.sensorTriggerDao.addInst(jsonObj);
// jsonObj.put("id",genId);
return jsonObj;
}
//@param jsonObj 调用参数
//@return 影响记录数SensorTrigger
@Override
public void updateInst(JSONObject jsonObj){
jsonObj = ParaUtils.removeSurplusCol(jsonObj,"id,titel,stream_id,cond,dataval,pushway,created,updated,stream_title"); this.sensorTriggerDao.updateInst(jsonObj);
}
}
|
package com.Action;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;
import com.dao.zzglDao;
import com.model.UpRate;
public class UpRateAction {
private List<UpRate> list;
public List<UpRate> getList() {
return list;
}
public void setList(List<UpRate> list) {
this.list = list;
}
public String toList() throws Exception {
UpRate ur = new UpRate();
zzglDao gl = new zzglDao();
JSONObject jsonObj = new JSONObject();
JSONArray rows = new JSONArray();
JSONObject cell = new JSONObject();
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse res = ServletActionContext.getResponse();
String ouser = request.getParameter("ouser");
String begin = request.getParameter("begin");
String end = request.getParameter("end");
if(ouser.length()<=0 && begin.length()<=0){
ur.setFlag("y");
ur.setDlogdate("logdate");
ur.setDseq("seq");
}else{
ur.setFlag2("n");
ur.setOuser(ouser);
ur.setBegin(begin);
ur.setEnd(end);
ur.setDlogdate("logdate");
ur.setDseq("seq");
}
list=gl.UpRate(ur);
int noOfRows = Integer.parseInt(request.getParameter("rows"));
int page = Integer.parseInt(request.getParameter("page"));
jsonObj.put("page", page);
jsonObj.put("total",
Math.ceil((double) list.size() / (double) noOfRows));
jsonObj.put("records", list.size());
for (int j = (page - 1) * noOfRows; j < Math.min(list.size(), page
* noOfRows); j++) {
int size = list.size();
for (int i = 0; i < size; i++) {
cell.put("ourl", list.get(j).getOurl());
cell.put("ouser", list.get(j).getOuser());
cell.put("logdate", list.get(j).getLogdate());
cell.put("seq", list.get(j).getSeq());
}
rows.add(cell);
}
jsonObj.put("rows", rows);
res.setContentType("text/html;charset=utf-8");
res.getWriter().print(jsonObj);
res.getWriter().close();
return null;
}
}
|
package com.gen.serve;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//import com.mysql.jdbc.Connection;
/**
* Servlet implementation class Insertuser
*/
@WebServlet("/Insertuser")
public class Insertuser extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Insertuser() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "world";
String driver = "com.mysql.jdbc.Driver";
try {
String Fname = request.getParameter("fname");
String Lname = request.getParameter("lname");
String Uname = request.getParameter("username");
String Emailid = request.getParameter("emailid");
String Mobno = request.getParameter("mobno");
String Password1 = request.getParameter("password1");
String Password2 = request.getParameter("password2");
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url
+ dbName, "root", "1415");
String sql1 = "INSERT INTO users(fname,lname,username,emailid,mobno,password1,password2)";
String sql2 = "VALUES('" + Fname + "','" + Lname
+ "','" + Uname + "','" + Emailid + "','"
+ Mobno + "','" + Password1 + "','"
+ Password2 + "');";
String sql = sql1 + sql2;
Statement st = conn.createStatement();
st.executeUpdate(sql);
RequestDispatcher RequetsDispatcherObj =request.getRequestDispatcher("/signupsuccessful.jsp");
RequetsDispatcherObj.forward(request, response);
} // try end
catch (Exception e) {
pw.println(e);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.