blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 410 | content_id stringlengths 40 40 | detected_licenses listlengths 0 51 | license_type stringclasses 2 values | repo_name stringlengths 5 132 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 80 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 131 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 9.45M | extension stringclasses 32 values | content stringlengths 3 9.45M | authors listlengths 1 1 | author_id stringlengths 0 313 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
88fa2c94871e0ed30a29de44ceaa2a917d764b56 | 895184a634b269e1688d51e323cc9eb8860d0392 | /app/src/main/java/com/qianfeng/yyz/zhonghuasuan/apublic/ShareUtils.java | 86965d0cdb38ee599df26d35ee6c2477160396db | [] | no_license | yzzAndroid/ZhongHuaSuan | 414af1d51c66d5783b38bab26e161accd1cc7de7 | 861e74012e20e5131354486bf08ff00b9d6c61d2 | refs/heads/master | 2020-02-26T15:55:29.156701 | 2016-10-25T09:06:26 | 2016-10-25T09:06:26 | 70,892,820 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,128 | java | package com.qianfeng.yyz.zhonghuasuan.apublic;
import android.content.Context;
import android.content.res.AssetManager;
import com.qianfeng.yyz.zhonghuasuan.bean.GoodsDetail;
import java.io.InputStream;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
/**
* Created by Administrator on 2016/10/22 0022.
*/
public class ShareUtils {
public static void showShare(Context context, GoodsDetail goodsDetail) {
ShareSDK.initSDK(context);
OnekeyShare oks = new OnekeyShare();
//关闭sso授权
oks.disableSSOWhenAuthorize();
// 分享时Notification的图标和文字 2.5.9以后的版本不调用此方法
//oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
// title标题,印象笔记、邮箱、信息、微信、人人网和QQ空间使用
oks.setTitle(goodsDetail.getData().getTitle());
// titleUrl是标题的网络链接,仅在人人网和QQ空间使用
oks.setTitleUrl(goodsDetail.getData().getUrl());
// text是分享文本,所有平台都需要这个字段
oks.setText(goodsDetail.getData().getTitle());
//分享网络图片,新浪微博分享网络图片需要通过审核后申请高级写入接口,否则请注释掉测试新浪微博
oks.setImageUrl(goodsDetail.getData().getImgs().get(0).getImg());
// imagePath是图片的本地路径,Linked-In以外的平台都支持此参数
//oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
// url仅在微信(包括好友和朋友圈)中使用
oks.setUrl(goodsDetail.getData().getUrl());
// comment是我对这条分享的评论,仅在人人网和QQ空间使用
oks.setComment(goodsDetail.getData().getTitle());
// site是分享此内容的网站名称,仅在QQ空间使用
oks.setSite("yzzShare");
// siteUrl是分享此内容的网站地址,仅在QQ空间使用
oks.setSiteUrl(goodsDetail.getData().getUrl());
// 启动分享GUI
oks.show(context);
}
}
| [
"1316234380@qq.com"
] | 1316234380@qq.com |
9000e7b01c9ee88bb4acb46685f35b40ce0cb343 | af3a52c2378777d8db121745ae2e8ceb64c257fd | /src/main/java/com/tts/ECommerce/Services/BookService.java | abdd9087f31c89a3ca2a10ed27a4a897d8e6e4cc | [] | no_license | mmmobley/BookEcommerce | 9b20951fba14efe0233c25765775a35efdfa67d5 | 1d28ffc0ec49c0ea6c9a7cec2b5fb2d322ac903c | refs/heads/master | 2022-11-24T17:55:06.360805 | 2020-08-04T19:45:08 | 2020-08-04T19:45:08 | 285,082,998 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,333 | java | package com.tts.ECommerce.Services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tts.ECommerce.Models.Book;
import com.tts.ECommerce.Repositories.BookRepository;
@Service
public class BookService {
@Autowired
private BookRepository bookRepository;
public List<Book> findAll() {
return bookRepository.findAll();
}
public Book findById(long id) {
return bookRepository.findById(id);
}
public List<String> findDistinctAuthors() {
return bookRepository.findDistinctAuthors();
}
public List<String> findDistinctGenres() {
return bookRepository.findDistinctGenres();
}
public void save(Book book) {
bookRepository.save(book);
}
public void deleteById(long id) {
bookRepository.deleteById(id);
}
public List<Book> findByAuthorAndOrGenre(String author, String genre) {
if(genre == null && author == null)
return bookRepository.findAll();
else if(genre == null)
return bookRepository.findByAuthor(author);
else if(author == null)
return bookRepository.findByGenre(genre);
else
return bookRepository.findByAuthorAndGenre(author, genre);
}
} | [
"mobleym23@outlook.com"
] | mobleym23@outlook.com |
7c879c51bf3504823d8a026275ac6b8ad5e7debc | b641e97d985535e4f1d52c7891aa907f3eb0a254 | /src/Components/animatefx/animation/BounceOut.java | 0cd719ed4230fbad85593ffc60f39b7cc72a3e25 | [] | no_license | mmaciag1991/HarnessDesignSystemInterfaceDiagram | 7e6f5dc078205475700dc2f63abc3f1e88e62728 | 4569676541a80dff1ffb5df6080799367e835065 | refs/heads/main | 2023-05-19T00:43:10.113472 | 2021-06-11T21:54:03 | 2021-06-11T21:54:03 | 375,101,913 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,014 | java | package Components.animatefx.animation;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.scene.Node;
import javafx.util.Duration;
/**
* @author Loïc Sculier aka typhon0
*/
public class BounceOut extends AnimationFX {
/**
* Create new BounceOut animation
*
* @param node The node to affect
*/
public BounceOut(final Node node) {
super(node);
}
public BounceOut() {
}
@Override
AnimationFX resetNode() {
getNode().setOpacity(1);
getNode().setScaleX(1);
getNode().setScaleY(1);
return this;
}
@Override
void initTimeline() {
setTimeline(new Timeline(
new KeyFrame(Duration.millis(0),
new KeyValue(getNode().scaleXProperty(), 1, AnimateFXInterpolator.EASE),
new KeyValue(getNode().scaleYProperty(), 1, AnimateFXInterpolator.EASE)
),
new KeyFrame(Duration.millis(200),
new KeyValue(getNode().scaleXProperty(), 0.9, AnimateFXInterpolator.EASE),
new KeyValue(getNode().scaleYProperty(), 0.9, AnimateFXInterpolator.EASE)
),
new KeyFrame(Duration.millis(550),
new KeyValue(getNode().opacityProperty(), 1, AnimateFXInterpolator.EASE),
new KeyValue(getNode().scaleXProperty(), 1.1, AnimateFXInterpolator.EASE),
new KeyValue(getNode().scaleYProperty(), 1.1, AnimateFXInterpolator.EASE)
),
new KeyFrame(Duration.millis(1000),
new KeyValue(getNode().opacityProperty(), 0, AnimateFXInterpolator.EASE),
new KeyValue(getNode().scaleXProperty(), 0.3, AnimateFXInterpolator.EASE),
new KeyValue(getNode().scaleYProperty(), 0.3, AnimateFXInterpolator.EASE)
)
));
}
}
| [
"mateo.m@wp.pl"
] | mateo.m@wp.pl |
6636b8462aa1124047478c4e02a8504f75824fb4 | dc2db5d31bd731ffd08c3c1f4fb3e01716a269ea | /src/SoundManager.java | aa1ed09a068db3d957794c445f5f337ac64c80ea | [] | no_license | katb11/DiscordSpiritBot | 790d35cf3c1f6a1279270f402868340946294f8b | ccc34a4c58e440bbc4dc102fdd230d4ff8131a7d | refs/heads/master | 2023-03-30T07:57:03.198406 | 2021-03-15T03:15:00 | 2021-03-15T03:15:00 | 347,809,059 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 671 | java | import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager;
public class SoundManager {
/**
* Audio player for the guild.
*/
public final AudioPlayer player;
/**
* Track scheduler for the player.
*/
public final TrackScheduler scheduler;
/**
* Creates a player and a track scheduler.
* @param manager Audio player manager to use for creating the player.
*/
public SoundManager(AudioPlayerManager manager) {
player = manager.createPlayer();
scheduler = new TrackScheduler(player);
player.addListener(scheduler);
}
} | [
"kathryn.blecher@gmail.com"
] | kathryn.blecher@gmail.com |
9c05e37db0cef2c06a9350e27a3fa9adabb1e9bc | ba35d24b415155e81e2e360370d1bc49004eac64 | /src/main/java/com/java4all/strategy/Arithmetic.java | 695e13e21539a49691d2766e586afac22d2a6956 | [
"Apache-2.0"
] | permissive | lightClouds917/designMode | f2e574ccf106444b76e80b26b074324be9dd38d1 | 30b596f8f94792aecc2db8710cec4a6f78589eb3 | refs/heads/master | 2021-06-21T02:16:46.926381 | 2020-06-10T12:38:07 | 2020-06-10T12:38:07 | 190,321,621 | 1 | 1 | Apache-2.0 | 2021-03-31T21:35:04 | 2019-06-05T03:44:56 | Java | UTF-8 | Java | false | false | 282 | java | package com.java4all.strategy;
/**
* 算法
* @author IT云清
* @date 2019年01月01日 11:11:11
*/
public interface Arithmetic {
/**
* 算法抽象执行
* @param num1
* @param num2
* @return
*/
Integer execute(Integer num1,Integer num2);
}
| [
"1186355422@qq.com"
] | 1186355422@qq.com |
7e9de2f11631da61410c103db058985778289044 | 87533f6fddca62f1107bc015b81777cc7f9170db | /gullimall-coupon/src/main/java/com/raymondz/gullimallcoupon/coupon/GullimallCouponApplication.java | eedcaddb2cd8ebd17a266d0aae63f7724bc8262d | [
"Apache-2.0"
] | permissive | qddoctor/gullimall | df18fe3cce089a3477be7991511de31c147e8013 | b05050ceea4aa69f83920e5662f6b2218952be1a | refs/heads/main | 2023-06-25T07:13:02.979555 | 2021-07-18T08:14:24 | 2021-07-18T08:14:24 | 385,852,947 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 358 | java | package com.raymondz.gullimallcoupon.coupon;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GullimallCouponApplication {
public static void main(String[] args) {
SpringApplication.run(GullimallCouponApplication.class, args);
}
}
| [
"qddoctor@hotmail.com"
] | qddoctor@hotmail.com |
de8ca08846a758f7a57e5f0f1fd963ffcdbaec5c | 9f8304a649e04670403f5dc1cb049f81266ba685 | /web-in/src/main/java/com/cmcc/vrp/province/webin/controller/GxCallBackController.java | 258bb2563f6c9938616385a9466538636ebb9110 | [] | no_license | hasone/pdata | 632d2d0df9ddd9e8c79aca61a87f52fc4aa35840 | 0a9cfd988e8a414f3bdbf82ae96b82b61d8cccc2 | refs/heads/master | 2020-03-25T04:28:17.354582 | 2018-04-09T00:13:55 | 2018-04-09T00:13:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,702 | java | package com.cmcc.vrp.province.webin.controller;
import java.io.IOException;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.cmcc.vrp.boss.guangxi.enums.CallbackResult;
import com.cmcc.vrp.boss.guangxi.enums.CallbackStatus;
import com.cmcc.vrp.boss.guangxi.model.AdditionResult;
import com.cmcc.vrp.boss.guangxi.model.BIPType;
import com.cmcc.vrp.boss.guangxi.model.GxCallbackBody;
import com.cmcc.vrp.boss.guangxi.model.GxCallbackHeader;
import com.cmcc.vrp.boss.guangxi.model.GxCallbackResp;
import com.cmcc.vrp.boss.guangxi.model.Response;
import com.cmcc.vrp.boss.guangxi.model.Routing;
import com.cmcc.vrp.boss.guangxi.model.RoutingInfo;
import com.cmcc.vrp.boss.guangxi.model.TransInfoResp;
import com.cmcc.vrp.charge.ChargeResult;
import com.cmcc.vrp.ec.utils.SerialNumGenerator;
import com.cmcc.vrp.enums.ChargeRecordStatus;
import com.cmcc.vrp.enums.FinanceStatus;
import com.cmcc.vrp.province.model.ChargeRecord;
import com.cmcc.vrp.province.model.SerialNum;
import com.cmcc.vrp.province.service.AccountService;
import com.cmcc.vrp.province.service.ChargeRecordService;
import com.cmcc.vrp.province.service.SerialNumService;
import com.cmcc.vrp.queue.TaskProducer;
import com.cmcc.vrp.queue.pojo.CallbackPojo;
import com.cmcc.vrp.util.DateUtil;
import com.thoughtworks.xstream.XStream;
/**
* Created by leelyn on 2016/9/18.
*/
@Controller
@RequestMapping(value = "/guangxi/charge")
public class GxCallBackController {
private static final Logger LOGGER = LoggerFactory.getLogger(GxCallBackController.class);
private static final String XMLHEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
@Autowired
private ChargeRecordService recordService;
@Autowired
private AccountService accountService;
@Autowired
private TaskProducer taskProducer;
@Autowired
private SerialNumService serialNumService;
@RequestMapping(value = "callback", method = RequestMethod.POST)
public void callback(HttpServletRequest request, HttpServletResponse response) throws IOException {
LOGGER.info("广西回调来了");
String xmlhead = request.getParameter("xmlhead");
String xmlbody = request.getParameter("xmlbody");
LOGGER.info("广西回调xmlhead:{},广西回调xmlbody:{}", xmlhead, xmlbody);
GxCallbackHeader cbHeader;
GxCallbackBody cbBody;
String svcCont;
AdditionResult result;
try {
if ((cbHeader = xml2Obj(GxCallbackHeader.class, "InterBOSS", xmlhead)) != null
&& (cbBody = xml2Obj(GxCallbackBody.class, "InterBOSS", xmlbody)) != null
&& StringUtils.isNotBlank(svcCont = cbBody.getSvcCont())
&& (result = xml2Obj(AdditionResult.class, "AdditionResult", svcCont)) != null) {
if (updateRecordStatus(result)) {
LOGGER.info("广西回调后更新充值记录成功");
} else {
LOGGER.info("广西回调后更新充值记录失败");
}
GxCallbackResp resp = buildCbResp(CallbackResult.SUCCESS.getRspCode(), CallbackResult.SUCCESS.getRspDsc(), cbHeader);
XStream xStream = new XStream();
xStream.autodetectAnnotations(true);
xStream.alias("InterBOSS", GxCallbackResp.class);
String respStr = composeXML(xStream.toXML(resp));
response.setCharacterEncoding("UTF-8");
response.getWriter().write(respStr);
LOGGER.info("响应广西回调成功");
return;
}
} catch (Exception e) {
LOGGER.error("广西回调解析包体异常:{}", e);
}
}
private <T> T xml2Obj(Class<T> cls, String rootTag, String data) {
XStream xStream = new XStream();
xStream.autodetectAnnotations(true);
xStream.alias(rootTag, cls);
return (T) xStream.fromXML(data);
}
private String composeXML(String body) {
StringBuffer SB = new StringBuffer();
SB.append(XMLHEADER);
SB.append(body);
return SB.toString();
}
private GxCallbackResp buildCbResp(String rspCode, String rspDesc, GxCallbackHeader cbHeader) {
GxCallbackResp resp = new GxCallbackResp();
resp.setVersion("0100");
resp.setTestFlag("1");
resp.setbIPType(buildBIPType());
resp.setRoutingInfo(buildRoutInfo());
resp.setTransInfo(buildTransInfo(cbHeader));
resp.setResponse(buidlResp(rspCode, rspDesc));
return resp;
}
private Response buidlResp(String rspCode, String rspDesc) {
Response response = new Response();
response.setRspCode(rspCode);
response.setRspDesc(rspDesc);
response.setRspType("0");
return response;
}
private BIPType buildBIPType() {
BIPType type = new BIPType();
type.setbIPCode("BIP4B877");
type.setActivityCode("T4011138");
type.setActionCode("1");
return type;
}
private RoutingInfo buildRoutInfo() {
RoutingInfo routingInfo = new RoutingInfo();
routingInfo.setOrigDomain("BBSS");
routingInfo.setRouteType("00");
routingInfo.setRouting(buildRouting());
return routingInfo;
}
private Routing buildRouting() {
Routing routing = new Routing();
routing.setHomeDomain("STKP");
routing.setRouteValue("998");
return routing;
}
private TransInfoResp buildTransInfo(GxCallbackHeader cbHeader) {
TransInfoResp transInfoResp = new TransInfoResp();
transInfoResp.setSessionID(cbHeader.getTransInfo().getSessionID());
transInfoResp.setTransIDO(cbHeader.getTransInfo().getTransIDO());
transInfoResp.setTransIDOTime(cbHeader.getTransInfo().getTransIDOTime());
transInfoResp.setTransIDH(SerialNumGenerator.buildNormalBossReqNum("ZYXX", 25));
transInfoResp.setTransIDHTime(DateUtil.getGxBossTime());
return transInfoResp;
}
//获取到充值结果后更新记录状态
private boolean updateRecordStatus(AdditionResult result) {
//String bossRespNum = result.getOperSeq();
String bossRespNum = result.getTransIDO();
String successNum = result.getSuccNum();
String status = result.getStatus();
SerialNum serialNum;
String systemNum;
ChargeRecord record;
if ((serialNum = serialNumService.getByBossRespSerialNum(bossRespNum)) == null
|| StringUtils.isBlank(systemNum = serialNum.getPlatformSerialNum())
|| (record = recordService.getRecordBySN(systemNum)) == null) {
LOGGER.error("未找到相应的订单,更新失败");
return false;
}
Long entId = record.getEnterId();
ChargeResult chargeResult;
Date updateChargeTime = new Date();
Integer financeStatus = null;
if (!"00".equals(status)) {
chargeResult = new ChargeResult(ChargeResult.ChargeResultCode.FAILURE);
if (result.getFailInfo() != null
&& !StringUtils.isEmpty(result.getFailInfo().getRspDesc())) {
chargeResult.setFailureReason(result.getFailInfo().getRspDesc());
} else {
chargeResult.setFailureReason(CallbackStatus.getRspDsc(status));
}
if (!accountService.returnFunds(systemNum)) {
LOGGER.error("充值serialNum{},entId{}失败时账户返还失败", systemNum, entId);
}else{
financeStatus = FinanceStatus.IN.getCode();
}
} else if (StringUtils.isNotBlank(successNum)
&& !"0".equals(successNum)) {
chargeResult = new ChargeResult(ChargeResult.ChargeResultCode.SUCCESS);
} else {
chargeResult = new ChargeResult(ChargeResult.ChargeResultCode.FAILURE);
if (result.getFailInfo() != null
&& !StringUtils.isEmpty(result.getFailInfo().getRspDesc())) {
chargeResult.setFailureReason(result.getFailInfo().getRspDesc());
} else {
chargeResult.setFailureReason("充值失败");
}
if (!accountService.returnFunds(systemNum)) {
LOGGER.error("充值serialNum{},entId{}失败时账户返还失败", systemNum, entId);
}else{
financeStatus = FinanceStatus.IN.getCode();
}
}
chargeResult.setFinanceStatus(financeStatus);
chargeResult.setUpdateChargeTime(updateChargeTime);
boolean isUpdate = updateRecordStatus(record, chargeResult);
// 将回调EC消息放入消息队列中
callbackEC(entId, systemNum);
return isUpdate;
}
/**
* 回掉EC平台
*
* @param entId
* @param systemNum
*/
private void callbackEC(Long entId, String systemNum) {
// 将消息入列,实现回调EC平台
CallbackPojo callbackPojo = new CallbackPojo();
callbackPojo.setEntId(entId);
callbackPojo.setSerialNum(systemNum);
taskProducer.productPlatformCallbackMsg(callbackPojo);
}
//获取到充值结果后更新记录状态
private boolean updateRecordStatus(ChargeRecord chargeRecord, ChargeResult chargeResult) {
ChargeRecordStatus chargeStatus = null;
String errorMsg = null;
if (chargeResult.isSuccess()) {
if (chargeResult.getCode().equals(ChargeResult.ChargeResultCode.SUCCESS)) {
chargeStatus = ChargeRecordStatus.COMPLETE;
errorMsg = ChargeRecordStatus.COMPLETE.getMessage();
} else {
chargeStatus = ChargeRecordStatus.PROCESSING;
errorMsg = ChargeRecordStatus.PROCESSING.getMessage();
}
} else {
chargeStatus = ChargeRecordStatus.FAILED;
errorMsg = chargeResult.getFailureReason();
}
chargeStatus.setFinanceStatus(chargeResult.getFinanceStatus());
chargeStatus.setUpdateChargeTime(chargeResult.getUpdateChargeTime());
return recordService.updateStatus(chargeRecord.getId(), chargeStatus, errorMsg);
}
}
| [
"fromluozuwu@qq.com"
] | fromluozuwu@qq.com |
b28ba235a6a8a6c1174c97c6439336824594f8c9 | 0e4015a5f33c42bf6f8b2a6e3d267fab1bcca450 | /trainbackend/src/main/java/com/train/service/impl/CategoryServiceImpl.java | c1a780bd33334966d98443d8c794f8fa56d43db4 | [
"MIT"
] | permissive | fsuleman2/revature-project3 | 3faa9d510d7682952d245822982c9d12c95022a2 | 7e94af5ed0986c93ebd30dc9b56b0c25e8d4b9d5 | refs/heads/master | 2023-08-16T09:51:01.062728 | 2021-10-21T10:36:30 | 2021-10-21T10:36:30 | 404,339,424 | 0 | 18 | null | 2021-09-18T03:43:10 | 2021-09-08T12:28:44 | TypeScript | UTF-8 | Java | false | false | 1,222 | java | package com.train.service.impl;
import java.util.LinkedHashSet;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.train.model.Category;
import com.train.repository.CategoryRepository;
import com.train.service.CategoryService;
@Service
public class CategoryServiceImpl implements CategoryService{
@Autowired
private CategoryRepository categoryRepository;
@Override
public Category addCategory(Category category) {
return this.categoryRepository.save(category);
}
@Override
public Category updateCategory(Category category) {
return this.categoryRepository.save(category);
}
@Override
public Set<Category> getCategories() {
return new LinkedHashSet<>(this.categoryRepository.findAll());
}
@Override
public Category getCategory(Long categoryId) {
return this.categoryRepository.findById(categoryId).get();
}
@Override
public void deleteCategory(Long categoryId) {
Category category = new Category();
category.setCatId(categoryId);
this.categoryRepository.delete(category);
}
}
| [
"mohantulabandhu@gmail.com"
] | mohantulabandhu@gmail.com |
1f0586ed2a4782e407f8865775cd19346ac3c1ca | ef064369167a6678c8d3fe50659014f3528d39b5 | /bus-core/src/main/java/org/aoju/bus/core/lang/WeightRandom.java | 2481b2134f76fd5d43f0fb46a7464838f85ced34 | [
"MIT"
] | permissive | lihai211/bus | 49d5d19b3d3ad3a714b11a462915297fa9563dc4 | 220aa13c81871c94ece20fbffc7798db0c01a67d | refs/heads/master | 2020-07-03T07:43:51.947462 | 2019-08-11T14:11:10 | 2019-08-11T14:11:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,843 | java | /*
* The MIT License
*
* Copyright (c) 2017, aoju.org All rights reserved.
*
* 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.
*/
package org.aoju.bus.core.lang;
import org.aoju.bus.core.utils.CollUtils;
import org.aoju.bus.core.utils.MapUtils;
import org.aoju.bus.core.utils.RandomUtils;
import java.io.Serializable;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* 权重随机算法实现<br>
* <p>
* 平时,经常会遇到权重随机算法,从不同权重的N个元素中随机选择一个,并使得总体选择结果是按照权重分布的。如广告投放、负载均衡等。
* </p>
* <p>
* 如有4个元素A、B、C、D,权重分别为1、2、3、4,随机结果中A:B:C:D的比例要为1:2:3:4。<br>
* </p>
* 总体思路:累加每个元素的权重A(1)-B(3)-C(6)-D(10),则4个元素的的权重管辖区间分别为[0,1)、[1,3)、[3,6)、[6,10)。<br>
* 然后随机出一个[0,10)之间的随机数。落在哪个区间,则该区间之后的元素即为按权重命中的元素。<br>
*
* @param <T> 权重随机获取的对象类型
* @author Kimi Liu
* @version 3.0.5
* @since JDK 1.8
*/
public class WeightRandom<T> implements Serializable {
private static final long serialVersionUID = -8244697995702786499L;
private TreeMap<Double, T> weightMap;
private Random random;
/**
* 构造
*/
public WeightRandom() {
weightMap = new TreeMap<>();
random = RandomUtils.getRandom();
}
/**
* 构造
*
* @param weightObj 带有权重的对象
*/
public WeightRandom(WeightObj<T> weightObj) {
this();
if (null != weightObj) {
add(weightObj);
}
}
/**
* 构造
*
* @param weightObjs 带有权重的对象
*/
public WeightRandom(Iterable<WeightObj<T>> weightObjs) {
this();
if (CollUtils.isNotEmpty(weightObjs)) {
for (WeightObj<T> weightObj : weightObjs) {
add(weightObj);
}
}
}
/**
* 构造
*
* @param weightObjs 带有权重的对象
*/
public WeightRandom(WeightObj<T>[] weightObjs) {
this();
for (WeightObj<T> weightObj : weightObjs) {
add(weightObj);
}
}
/**
* 创建权重随机获取器
*
* @param <T> 对象
* @return {@link WeightRandom}
*/
public static <T> WeightRandom<T> create() {
return new WeightRandom<>();
}
/**
* 增加对象
*
* @param obj 对象
* @param weight 权重
* @return this
*/
public WeightRandom<T> add(T obj, double weight) {
return add(new WeightObj<T>(obj, weight));
}
/**
* 增加对象权重
*
* @param weightObj 权重对象
* @return this
*/
public WeightRandom<T> add(WeightObj<T> weightObj) {
double lastWeight = (this.weightMap.size() == 0) ? 0 : this.weightMap.lastKey();
this.weightMap.put(weightObj.getWeight() + lastWeight, weightObj.getObj());// 权重累加
return this;
}
/**
* 清空权重表
*
* @return this
*/
public WeightRandom<T> clear() {
if (null != this.weightMap) {
this.weightMap.clear();
}
return this;
}
/**
* 下一个随机对象
*
* @return 随机对象
*/
public T next() {
if (MapUtils.isEmpty(this.weightMap)) {
return null;
}
double randomWeight = this.weightMap.lastKey() * random.nextDouble();
final SortedMap<Double, T> tailMap = this.weightMap.tailMap(randomWeight, false);
return this.weightMap.get(tailMap.firstKey());
}
/**
* 带有权重的对象包装
*
* @param <T> 对象类型
*/
public static class WeightObj<T> {
/**
* 对象
*/
private T obj;
/**
* 权重
*/
private double weight;
/**
* 构造
*
* @param obj 对象
* @param weight 权重
*/
public WeightObj(T obj, double weight) {
this.obj = obj;
this.weight = weight;
}
/**
* 获取对象
*
* @return 对象
*/
public T getObj() {
return obj;
}
/**
* 设置对象
*
* @param obj 对象
*/
public void setObj(T obj) {
this.obj = obj;
}
/**
* 获取权重
*
* @return 权重
*/
public double getWeight() {
return weight;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((obj == null) ? 0 : obj.hashCode());
long temp;
temp = Double.doubleToLongBits(weight);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
WeightObj<?> other = (WeightObj<?>) obj;
if (this.obj == null) {
if (other.obj != null) {
return false;
}
} else if (!this.obj.equals(other.obj)) {
return false;
}
return Double.doubleToLongBits(weight) == Double.doubleToLongBits(other.weight);
}
}
}
| [
"839536@QQ.COM"
] | 839536@QQ.COM |
9bf5713996fbb9e4fab4075b5d599542f611d926 | aed2e5114a1ac06c9c2da81a3327c34fcc82604c | /app/src/main/java/practiceandroidapplication/android/com/meetmeup/Entity/Nationality.java | 6335203051e1b76b4de0cd54c949405e3fd3da44 | [] | no_license | spoofermark21/MeetMeUp | f2c606b8c4fe9d1ccf4e82813831dad18167fd65 | 6b076b84ca9fc0ebb01c3a13f76ab0d276ddbcd2 | refs/heads/master | 2021-01-10T03:42:45.982153 | 2016-02-22T08:09:46 | 2016-02-22T08:09:46 | 45,920,263 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,145 | java | package practiceandroidapplication.android.com.meetmeup.Entity;
/**
* Created by sibimark on 07/12/2015.
*/
public class Nationality {
private int id;
private String nationality;
/*
constructors
*/
public Nationality() {
}
public Nationality(int id) {
this.id = id;
}
public Nationality(int id, String nationality) {
this.id = id;
this.nationality = nationality;
}
public void setId(int id){
this.id = id;
}
public int getId(){
return id;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public String getNationality(){
return nationality;
}
public String getNatioNalityName(){
ListNationalities listNationalities = ListNationalities.getInstanceListNationalities();
for(Nationality nationality1 : listNationalities.nationalities ) {
if(nationality1.getId() == this.id) {
this.nationality = nationality1.getNationality();
break;
}
}
return this.nationality;
}
}
| [
"sibi.mark21@gmail.com"
] | sibi.mark21@gmail.com |
978fbb8b0c61e8a245107fd22f144d406e45e478 | ceda897b48d0a00dd6a1963dd0580e46cabc2531 | /src/main/java/fr/uvsq/poo/Builder_Composite_Iterator/InterfaceDAO.java | 4d39625e1fdf5de51fad5b73ae8a0fe9296d1ec7 | [] | no_license | uvsq21922702/principes_Java-Design_Pattern | 116153eea841ee1a0ee6f71131b6499713217ad5 | 30a7b395b869d3f6757574259bffb0e641f6e5fd | refs/heads/master | 2023-06-29T12:38:46.803550 | 2021-04-18T21:17:51 | 2021-04-18T21:17:51 | 390,708,675 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 269 | java | package fr.uvsq.poo.Builder_Composite_Iterator;
public interface InterfaceDAO <T>{
/**
* Les methodes CRUD
* @param objet
* @return
* //
*/
T create(T objet);
T read(String id);
T update(T objet);
void delete(T objet);
} | [
"yacine.yousfi@ens.uvsq.fr"
] | yacine.yousfi@ens.uvsq.fr |
11b28036ebf5938bbc684d3ddf1cbe7f7e4c2844 | 07012020981d9c3b8f584e1285a21eeab4e8acae | /src/test/java/movies/spring/data/neo4j/repositories/GroupRepositoryTest.java | 8ec078e86e69b7d69ae2a8982b91d3af1030072b | [] | no_license | blackstar10/luowang-spring-data-neo4j | 263dc7aca7f7986b907ef179f39cd6b2fffec3ef | a4a03116fb18be09c793839ff1ee8fd797756369 | refs/heads/master | 2020-03-24T02:55:10.928311 | 2018-08-16T05:55:32 | 2018-08-16T05:55:32 | 142,395,967 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,024 | java | package movies.spring.data.neo4j.repositories;
import movies.spring.data.neo4j.domain.Group;
import movies.spring.data.neo4j.domain.Human;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
/**
* Create on 2018/8/7 15:30
*
* @author sunqiu@cmss.chinamobile.com
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@EnableNeo4jRepositories("movies.spring.data.neo4j.repositories")
@Transactional
public class GroupRepositoryTest {
private Logger logger = LoggerFactory.getLogger(GroupRepositoryTest.class);
@Autowired
private GroupRepository groupRepository;
@Autowired
private HumanRepository humanRepository;
@Before
public void setUp() {
Group group1 = new Group("testCompany");
Human human1 = new Human("human1", "1999-01-02", "", true, "male");
Human human2 = new Human("human2", "1999-04-07", "", true, "female");
Human human3 = new Human("human3", "1999-03-22", "", false, "female");
Human human4 = new Human("human4", "1999-02-12", "", false, "male");
human1.addGroupList(group1);
human2.addGroupList(group1);
human3.addGroupList(group1);
humanRepository.save(human1);
humanRepository.save(human2);
humanRepository.save(human3);
humanRepository.save(human4);
}
@Test
public void testGroupExist() {
Assert.assertEquals(1, groupRepository.findByGroupName("testCompany").size());
Assert.assertEquals(0, groupRepository.findByGroupName("testCompany2").size());
}
@Test
public void testRelationship() {
int count = 0;
for (Human human : humanRepository.findByName("human1")) {
Assert.assertEquals(1, human.getGroupList().size());
Assert.assertEquals("testCompany", human.getGroupList().get(0).getGroupName());
count += 1;
}
Assert.assertEquals(1, count);
}
@Test
public void testAddRelationship() {
for (Human human : humanRepository.findByName("human1")) {
Group group2 = new Group("testCompany2");
human.addGroupList(group2);
humanRepository.save(human);
}
int count = 0;
for (Human human : humanRepository.findByName("human1")) {
Assert.assertEquals(2, human.getGroupList().size());
for (Group group : human.getGroupList()) {
logger.info(group.getGroupName());
}
count += 1;
}
Assert.assertEquals(1, count);
}
}
| [
"sunqiu@cmss.chinamobile.com"
] | sunqiu@cmss.chinamobile.com |
33ea76734a8f5eb3441bd9df2490609caf108a47 | 1604603345d0dfccade236df9fd128990b61e42e | /practice/src/main/java/com/github/my_study/concurrent/package-info.java | 268dfbb50ee67dd6cef61b46167b4db22acaf93e | [] | no_license | Lowrry/my_study | 60bafea8e227f4cc01f95101dba26c15b09c2892 | 74a46ece8366d8a79e9834165e2d4ea1e9642a95 | refs/heads/master | 2021-10-12T00:55:01.226814 | 2019-01-31T08:53:38 | 2019-01-31T08:53:38 | 115,987,763 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,067 | java | /**
* // 对各种类型的数据进行合并后处理
// 每隔一段时间提交一次
// 或每隔一段时间提交一次
// 某种消息,第一次进来会立马执行
// 主要应对canal消息,进行合并后处理
// 设计目标在并发写入的时候, 可以定时cas的合并消息,然后提交;
// 消息不会源源不断的来的, 如果尝试几次失败了的话, 就强制加锁提交消息. 类似于ConcurrentHashMap
// 高性能的系统,很多结构都要自己定制的.
// 供应商那边会有价格消息定时导入 以及 汇率商品定时批量更新的问题
// 上次我的设计是想利用读写锁?
// 还有想利用cas的工具类,进行cas的修改,避免加锁.
// todo getAndUpdate
// segment数和线程数关系的影响也可以测试下. 这应该是个相对固定的值,因为lts的线程数是可控的.
// 继承读写锁,是想对对象整体加锁
// 这个send动作,其实就是插入的意思,就是都是增量的消息.
// 更多的利用cas而不是锁,两种方案一起比较下看看呢.
// 这个可以写个Blog. 比较下不同方案的处理量.
// 还有关于价格多级缓存的,后面也要做一下,不一定要上线,但是要实现出来.
// 没有消息的,会有一个线程主动扫描一次.判断消息的上次发送时间,先CAS更新时间,再发送一次.
// 在发送消息的时候,先对AtomicReference.
// 这里主要是用来做共享锁和独占锁来使用的
// 往里面添加数据,是用的cas,因为只会新增,所以cas没有aba的风险
// 删除对象也可以使用cas吧? 不行? 需要删除对象
// 是否也可以将开始结束时间更新为null呢? 这样下次就没有数据要更新了, 就是更新为null, 也是用cas.
// 但是这样有个不好的情况,就是会有残留的对象, 怎么清除呢?
// 还是最好在提交的时候, 对每个id对象进行加锁, 然后进行清理.
// 这个锁, 当然最好最好是加在每个对象上了, 这样就没有全局的锁
*/
package com.github.my_study.concurrent; | [
"luxiaochun@lvmama.com"
] | luxiaochun@lvmama.com |
3845cf9184eb9f10022bbef1ec432259328cf446 | e977c424543422f49a25695665eb85bfc0700784 | /benchmark/icse15/1366883/buggy-version/lucene/dev/branches/branch_4x/lucene/core/src/java/org/apache/lucene/index/SegmentInfo.java | f841baa845edba203075ef9e878ef1358e26bc62 | [] | no_license | amir9979/pattern-detector-experiment | 17fcb8934cef379fb96002450d11fac62e002dd3 | db67691e536e1550245e76d7d1c8dced181df496 | refs/heads/master | 2022-02-18T10:24:32.235975 | 2019-09-13T15:42:55 | 2019-09-13T15:42:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,697 | java | package org.apache.lucene.index;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.lucene.codecs.Codec;
import org.apache.lucene.codecs.lucene3x.Lucene3xSegmentInfoFormat;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.TrackingDirectoryWrapper;
/**
* Information about a segment such as it's name, directory, and files related
* to the segment.
*
* @lucene.experimental
*/
public final class SegmentInfo {
// TODO: remove these from this class, for now this is the representation
public static final int NO = -1; // e.g. no norms; no deletes;
public static final int YES = 1; // e.g. have norms; have deletes;
public final String name; // unique name in dir
private int docCount; // number of docs in seg
public final Directory dir; // where segment resides
private boolean isCompoundFile;
private volatile long sizeInBytes = -1; // total byte size of all files (computed on demand)
private Codec codec;
private Map<String,String> diagnostics;
private Map<String,String> attributes;
// Tracks the Lucene version this segment was created with, since 3.1. Null
// indicates an older than 3.0 index, and it's used to detect a too old index.
// The format expected is "x.y" - "2.x" for pre-3.0 indexes (or null), and
// specific versions afterwards ("3.0", "3.1" etc.).
// see Constants.LUCENE_MAIN_VERSION.
private String version;
void setDiagnostics(Map<String, String> diagnostics) {
this.diagnostics = diagnostics;
}
public Map<String, String> getDiagnostics() {
return diagnostics;
}
/**
* Construct a new complete SegmentInfo instance from input.
* <p>Note: this is public only to allow access from
* the codecs package.</p>
*/
public SegmentInfo(Directory dir, String version, String name, int docCount,
boolean isCompoundFile, Codec codec, Map<String,String> diagnostics, Map<String,String> attributes) {
assert !(dir instanceof TrackingDirectoryWrapper);
this.dir = dir;
this.version = version;
this.name = name;
this.docCount = docCount;
this.isCompoundFile = isCompoundFile;
this.codec = codec;
this.diagnostics = diagnostics;
this.attributes = attributes;
}
/**
* Returns total size in bytes of all of files used by
* this segment. Note that this will not include any live
* docs for the segment; to include that use {@link
* SegmentInfoPerCommit#sizeInBytes()} instead.
*/
public long sizeInBytes() throws IOException {
if (sizeInBytes == -1) {
long sum = 0;
for (final String fileName : files()) {
sum += dir.fileLength(fileName);
}
sizeInBytes = sum;
}
return sizeInBytes;
}
/**
* @deprecated separate norms are not supported in >= 4.0
*/
@Deprecated
boolean hasSeparateNorms() {
return getAttribute(Lucene3xSegmentInfoFormat.NORMGEN_KEY) != null;
}
/**
* Mark whether this segment is stored as a compound file.
*
* @param isCompoundFile true if this is a compound file;
* else, false
*/
void setUseCompoundFile(boolean isCompoundFile) {
this.isCompoundFile = isCompoundFile;
}
/**
* Returns true if this segment is stored as a compound
* file; else, false.
*/
public boolean getUseCompoundFile() {
return isCompoundFile;
}
/** Can only be called once. */
public void setCodec(Codec codec) {
assert this.codec == null;
if (codec == null) {
throw new IllegalArgumentException("segmentCodecs must be non-null");
}
this.codec = codec;
}
public Codec getCodec() {
return codec;
}
public int getDocCount() {
if (this.docCount == -1) {
throw new IllegalStateException("docCount isn't set yet");
}
return docCount;
}
// NOTE: leave package private
void setDocCount(int docCount) {
if (this.docCount != -1) {
throw new IllegalStateException("docCount was already set");
}
this.docCount = docCount;
}
/*
* Return all files referenced by this SegmentInfo. The
* returns List is a locally cached List so you should not
* modify it.
*/
public Set<String> files() {
if (setFiles == null) {
throw new IllegalStateException("files were not computed yet");
}
return Collections.unmodifiableSet(setFiles);
}
/** {@inheritDoc} */
@Override
public String toString() {
return toString(dir, 0);
}
/** Used for debugging. Format may suddenly change.
*
* <p>Current format looks like
* <code>_a(3.1):c45/4</code>, which means the segment's
* name is <code>_a</code>; it was created with Lucene 3.1 (or
* '?' if it's unknown); it's using compound file
* format (would be <code>C</code> if not compound); it
* has 45 documents; it has 4 deletions (this part is
* left off when there are no deletions).</p>
*/
public String toString(Directory dir, int delCount) {
StringBuilder s = new StringBuilder();
s.append(name).append('(').append(version == null ? "?" : version).append(')').append(':');
char cfs = getUseCompoundFile() ? 'c' : 'C';
s.append(cfs);
if (this.dir != dir) {
s.append('x');
}
s.append(docCount);
if (delCount != 0) {
s.append('/').append(delCount);
}
// TODO: we could append toString of attributes() here?
return s.toString();
}
/** We consider another SegmentInfo instance equal if it
* has the same dir and same name. */
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj instanceof SegmentInfo) {
final SegmentInfo other = (SegmentInfo) obj;
return other.dir == dir && other.name.equals(name);
} else {
return false;
}
}
@Override
public int hashCode() {
return dir.hashCode() + name.hashCode();
}
/**
* Used by DefaultSegmentInfosReader to upgrade a 3.0 segment to record its
* version is "3.0". This method can be removed when we're not required to
* support 3x indexes anymore, e.g. in 5.0.
* <p>
* <b>NOTE:</b> this method is used for internal purposes only - you should
* not modify the version of a SegmentInfo, or it may result in unexpected
* exceptions thrown when you attempt to open the index.
*
* @lucene.internal
*/
public void setVersion(String version) {
this.version = version;
}
/** Returns the version of the code which wrote the segment. */
public String getVersion() {
return version;
}
private Set<String> setFiles;
public void setFiles(Set<String> files) {
setFiles = files;
sizeInBytes = -1;
}
public void addFiles(Collection<String> files) {
setFiles.addAll(files);
}
public void addFile(String file) {
setFiles.add(file);
}
/**
* Get a codec attribute value, or null if it does not exist
*/
public String getAttribute(String key) {
if (attributes == null) {
return null;
} else {
return attributes.get(key);
}
}
/**
* Puts a codec attribute value.
* <p>
* This is a key-value mapping for the field that the codec can use
* to store additional metadata, and will be available to the codec
* when reading the segment via {@link #getAttribute(String)}
* <p>
* If a value already exists for the field, it will be replaced with
* the new value.
*/
public String putAttribute(String key, String value) {
if (attributes == null) {
attributes = new HashMap<String,String>();
}
return attributes.put(key, value);
}
/**
* @return internal codec attributes map. May be null if no mappings exist.
*/
public Map<String,String> attributes() {
return attributes;
}
}
| [
"durieuxthomas@hotmail.com"
] | durieuxthomas@hotmail.com |
14e47783598be6bac3d8394e27454828ae92801b | ad6220d2e90deb54f7e3fcfacfa3ed423d915d36 | /Practice programe/FncnCircleAreaCircumference.java | 635369fa8a3c18238f5efaf29d2756730e4d8103 | [] | no_license | Chitresh2126/JavaProgramming | 54c502ec7741db5d3d7d53efefb0e643e2d17afc | aae68a1fc5bd0bd30d907f5c0abf36751675c15d | refs/heads/master | 2023-07-28T08:04:41.425287 | 2021-09-14T05:03:12 | 2021-09-14T05:03:12 | 401,681,955 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 713 | java | import java.util.Scanner;
public class FncnCircleAreaCircumference {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter radius of circle ");
int rad = scanner.nextInt();
float circum = circumference(rad);
float area = areacircle(rad);
System.out.println("Area of a circle is " + area);
System.out.println("Circumference of a circle is " + circum);
}
private static float areacircle(int rad) {
float a = (float) (3.14 * rad * rad);
return a;
}
private static float circumference(int rad) {
float b = (float) ( 2 * 3.14 * rad);
return b;
}
}
| [
"chitreshkumar.bsr@gmail.com"
] | chitreshkumar.bsr@gmail.com |
6fe14dee82585e2424b9476ab4a0b5309f086a3b | 6bb7b08cbe3c8e199247a912929af666fc177956 | /src/main/java/baseline/MainApp.java | 985398bf984588ced5123384be4d3e2344b96929 | [] | no_license | pothyn/davis-app1-design | ff3a1a1b15fcbbb44a86ef19cf948e7cd720c18e | c131ab693422cce340b6871775d94551974b9971 | refs/heads/main | 2023-08-23T09:45:24.661555 | 2021-11-02T15:57:30 | 2021-11-02T15:57:30 | 420,228,903 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,134 | java | /*
* UCF COP3330 Summer 2021 Application Assignment 1 Solution
* Copyright 2021 Hunter Davis
*/
package baseline;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
import java.util.Objects;
public class MainApp extends javafx.application.Application {
private AllToDoLists app;
@FXML
@Override
public void start(Stage stage) throws IOException {
// Initialize app
app = new AllToDoLists();
sceneSetup(stage, "OpenApp", "To Do List App");
// while
// wait for user to select either Create New List or Load Existing List
// if clicked on "Create New"
// call sceneSetup() using stage, "HomePage", "To Do List App"
// homePage(stage)
}
@FXML
public static void main(String[] args) {
launch(args);
}
@FXML
public void sceneSetup(Stage stage, String fileName, String windowTitle) throws IOException {
// Open <fileName>.fxml file
Parent root = FXMLLoader.load(Objects.requireNonNull(getClass().getResource(fileName + ".fxml")));
// attach file to scene
Scene scene = new Scene(root);
// change title
stage.setTitle(windowTitle);
// attach scene to the stage
stage.setScene(scene);
// display stage to user
stage.show();
}
public void homePage(Scene scene) {
// while
// check for the AddButton press
// move to AddToDo.fxml and wait for input (data must be entered before!)
// addToDoFxml(<entered data>)
// check for the ViewListButton press
// move to ViewList.fxml
// viewListFxml()
}
public void addToDoFxml(String listTitle) {
// Allow user to input data about the list
// Create a new ToDoList in app using the listTitle and now this information
}
public void viewListFxml() {
// wait for input to go back
}
}
| [
"pothyne@outlook.com"
] | pothyne@outlook.com |
90620e21c317049e295bd95bb79006b2ec0cc6fb | 647ec12ce50f06e7380fdbfb5b71e9e2d1ac03b4 | /com.tencent.mobileqqi/classes.jar/fuq.java | cacbdbb072be32d31498a180d837865f57d0382d | [] | no_license | tsuzcx/qq_apk | 0d5e792c3c7351ab781957bac465c55c505caf61 | afe46ef5640d0ba6850cdefd3c11badbd725a3f6 | refs/heads/main | 2022-07-02T10:32:11.651957 | 2022-02-01T12:41:38 | 2022-02-01T12:41:38 | 453,860,108 | 36 | 9 | null | 2022-01-31T09:46:26 | 2022-01-31T02:43:22 | Java | UTF-8 | Java | false | false | 564 | java | import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import com.tencent.mobileqq.filemanager.core.OnlineFileSessionCenter;
public class fuq
extends Handler
{
public fuq(OnlineFileSessionCenter paramOnlineFileSessionCenter, Looper paramLooper)
{
super(paramLooper);
}
public void handleMessage(Message paramMessage)
{
this.a.d();
}
}
/* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mobileqqi\classes2.jar
* Qualified Name: fuq
* JD-Core Version: 0.7.0.1
*/ | [
"98632993+tsuzcx@users.noreply.github.com"
] | 98632993+tsuzcx@users.noreply.github.com |
81faf660dc27c6df1260368db1cd3629eec467c1 | ba6938c311f1e1d26ff6126e30d3a6a5a5ff06d8 | /src/org/starexec/app/RESTHelpers.java | ba7833acfb2b0d84a913645d2ab208d3c4ecd9c4 | [
"MIT"
] | permissive | StarExec/StarExec | 12fb3b7b2f6349468e7e99172f0da345abadc4a3 | fa1f7ff3dad53e70606c73b57cd5aac17fe7b829 | refs/heads/fb1 | 2023-08-17T14:14:02.427349 | 2023-08-10T02:46:01 | 2023-08-10T02:46:01 | 121,437,220 | 16 | 5 | MIT | 2023-08-10T02:46:03 | 2018-02-13T21:12:01 | Java | UTF-8 | Java | false | false | 97,992 | java | package org.starexec.app;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.annotations.Expose;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.apache.commons.lang3.tuple.Triple;
import org.starexec.app.RESTHelpers.JSTreeItem;
import org.starexec.command.C;
import org.starexec.command.Connection;
import org.starexec.command.JsonHandler;
import org.starexec.constants.R;
import org.starexec.data.database.*;
import org.starexec.data.database.AnonymousLinks.PrimitivesToAnonymize;
import org.starexec.data.security.JobSecurity;
import org.starexec.data.security.ValidatorStatusCode;
import org.starexec.data.to.*;
import org.starexec.data.to.Queue;
import org.starexec.data.to.enums.Primitive;
import org.starexec.data.to.enums.ProcessorType;
import org.starexec.data.to.pipelines.JoblineStage;
import org.starexec.data.to.tuples.AttributesTableData;
import org.starexec.data.to.tuples.AttributesTableRow;
import org.starexec.data.to.tuples.Locatable;
import org.starexec.data.to.tuples.SolverConfig;
import org.starexec.exceptions.RESTException;
import org.starexec.exceptions.StarExecDatabaseException;
import org.starexec.logger.StarLogger;
import org.starexec.test.integration.TestResult;
import org.starexec.test.integration.TestSequence;
import org.starexec.util.*;
//import org.starexec.data.database.Common;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.SQLException;
//import java.sql.CallableStatement;
//import java.sql.ResultSet;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
/**
* Holds all helper methods and classes for our restful web services
*/
public class RESTHelpers {
private static final StarLogger log = StarLogger.getLogger(RESTHelpers.class);
private static final String SEARCH_QUERY = "sSearch";
private static final String SORT_DIRECTION = "sSortDir_0";
private static final String SYNC_VALUE = "sEcho";
private static final String SORT_COLUMN = "iSortCol_0";
private static final String SORT_COLUMN_OVERRIDE = "sort_by";
private static final String SORT_COLUMN_OVERRIDE_DIR = "sort_dir";
private static final String STARTING_RECORD = "iDisplayStart";
private static final String RECORDS_PER_PAGE = "iDisplayLength";
/**
* Used to display the 'total entries' information at the bottom of
* the DataTable; also indirectly controls whether or not the
* pagination buttons are toggle-able
*/
private static final String TOTAL_RECORDS = "iTotalRecords";
private static final String TOTAL_RECORDS_AFTER_QUERY = "iTotalDisplayRecords";
private static final Gson gson = new Gson();
/**
* Takes in a list of spaces and converts it into a list of JSTreeItems
* suitable for being displayed on the client side with the jsTree plugin.
*
* @param spaceList The list of spaces to convert
* @param userID The ID of the user making this request, which is used to tell whether nodes are leaves or not
* @return List of JSTreeItems to be serialized and sent to client
* @author Tyler Jensen
*/
protected static List<JSTreeItem> toSpaceTree(List<Space> spaceList, int userID) {
List<JSTreeItem> list = new LinkedList<>();
for (Space space : spaceList) {
String isOpen = Spaces.getCountInSpace(space.getId(), userID, true) > 0 ? "closed" : "leaf";
list.add(new JSTreeItem(space.getName(), space.getId(), isOpen, R.SPACE));
}
return list;
}
/*
* This just calls the Queue.getDescription. This choice was made so only this
* class needs to know about queues i.e RestServices dosen't need to know about
* queues.
*/
public static String getQueueDescription(int qid) {
return Queues.getDescForQueue(qid);
}
/**
* Takes in a list of spaces and converts it into a list of JSTreeItems
* suitable for being displayed on the client side with the jsTree plugin.
*
* @param jobSpaceList list of JobSpace to convert
* @return List of JSTreeItems to be serialized and sent to client
* @author Tyler Jensen
*/
protected static List<JSTreeItem> toJobSpaceTree(List<JobSpace> jobSpaceList) {
List<JSTreeItem> list = new LinkedList<>();
for (JobSpace space : jobSpaceList) {
String isOpen = Spaces.getCountInJobSpace(space.getId()) > 0 ? "closed" : "leaf";
list.add(new JSTreeItem(space.getName(), space.getId(), isOpen, R.SPACE, space.getMaxStages()));
}
return list;
}
/**
* Takes in a list of worker nodes and converts it into a list of
* JSTreeItems suitable for being displayed on the client side with the
* jsTree plugin.
*
* @param nodes The list of worker nodes to convert
* @return List of JSTreeItems to be serialized and sent to client
* @author Tyler Jensen
*/
protected static List<JSTreeItem> toNodeList(List<WorkerNode> nodes) {
List<JSTreeItem> list = new LinkedList<>();
for (WorkerNode n : nodes) {
// Only take the first part of the host name, the full one is too
// int to display on the client
JSTreeItem t = new JSTreeItem(n.getName().split("\\.")[0], n.getId(), "leaf", n.getStatus().equals("ACTIVE") ? "enabled_node" : "disabled_node");
list.add(t);
}
return list;
}
/**
* Takes in a list of queues and converts it into a list of JSTreeItems
* suitable for being displayed on the client side with the jsTree plugin.
*
* @param queues The list of queues to convert
* @return List of JSTreeItems to be serialized and sent to client
* @author Tyler Jensen
*/
protected static List<JSTreeItem> toQueueList(List<Queue> queues) {
List<JSTreeItem> list = new LinkedList<>();
for (Queue q : queues) {
//status might be null, so we don't want a null pointer in that case
String status = q.getStatus();
if (status == null) {
status = "";
}
String isOpen = !Queues.getNodes(q.getId()).isEmpty() ? "closed" : "leaf";
list.add(new JSTreeItem(q.getName(), q.getId(), isOpen, status.equals("ACTIVE") ? "active_queue" : "inactive_queue"));
}
return list;
}
/**
* Takes in a list of spaces (communities) and converts it into a list of
* JSTreeItems suitable for being displayed on the client side with the
* jsTree plugin.
*
* @param communities The list of communities to convert
* @return List of JSTreeItems to be serialized and sent to client
* @author Tyler Jensen
*/
protected static List<JSTreeItem> toCommunityList(List<Space> communities) {
List<JSTreeItem> list = new LinkedList<>();
for (Space space : communities) {
JSTreeItem t = new JSTreeItem(space.getName(), space.getId(), "leaf", R.SPACE);
list.add(t);
}
return list;
}
/**
* Validate the parameters of a request for a DataTable page
*
* @param type the primitive type being queried for
* @param request the object containing the parameters to validate
* @return an attribute map containing the valid parameters parsed from the request object,<br>
* or null if parameter validation fails
* @author Todd Elvers
*/
private static DataTablesQuery getAttrMap(Primitive type, HttpServletRequest request) {
DataTablesQuery query = new DataTablesQuery();
try {
// Parameters from the DataTable object
String iDisplayStart = (String) request.getParameter(STARTING_RECORD);
String iDisplayLength = (String) request.getParameter(RECORDS_PER_PAGE);
String sEcho = (String) request.getParameter(SYNC_VALUE);
String iSortCol = (String) request.getParameter(SORT_COLUMN);
String sDir = (String) request.getParameter(SORT_DIRECTION);
String sSearch = (String) request.getParameter(SEARCH_QUERY);
// Validates the starting record, the number of records per page,
// and the sync value
if (Util.isNullOrEmpty(iDisplayStart) || Util.isNullOrEmpty(iDisplayLength) || Util.isNullOrEmpty(sEcho) || Integer.parseInt(iDisplayStart) < 0 || Integer.parseInt(sEcho) < 0) {
return null;
}
if (Util.isNullOrEmpty(iSortCol)) {
// Allow jobs datatable to have a sort column null, then set
// the column to sort by column 5, which doesn't exist on the screen but represents the creation date
if (type == Primitive.JOB) {
query.setSortColumn(5);
} else {
return null;
}
} else {
int sortColumnIndex = Integer.parseInt(iSortCol);
query.setSortColumn(sortColumnIndex);
}
//set the sortASC flag
if (Util.isNullOrEmpty(sDir)) {
//WARNING: if you don't do this check, sometimes null gets passed, and this
//causes null pointer exception. This is extremely hard to debug. DO NOT REMOVE!
query.setSortASC(false);
}
else if (sDir.contains("asc")) {
query.setSortASC(true);
} else if (sDir.contains("desc")) {
query.setSortASC(false);
} else {
log.warn("getAttrMap", "sDir is not 'asc' or 'desc': "+sDir);
return null;
}
// Depending on if the search/filter is empty or not, this will be 0 or 1
if (Util.isNullOrEmpty(sSearch)) {
sSearch = null;
}
query.setSearchQuery(sSearch);
// The request is valid if it makes it this far;
// Finish the validation by adding the remaining attributes to the
// map
query.setNumRecords(Integer.parseInt(iDisplayLength));
query.setStartingRecord(Integer.parseInt(iDisplayStart));
query.setSyncValue(Integer.parseInt(sEcho));
return query;
} catch (Exception e) {
log.error("There was a problem getting the paramaters for the datatables query:" + e.getCause());
}
return null;
}
/**
* Add tag for the image representing a link that will popout.
*
* @param sb the StringBuilder to add the tag with.
* @author Aaron Stump
*/
public static void addImg(StringBuilder sb) {
sb.append("<img class=\"extLink\" src=\"");
sb.append(Util.docRoot("images/external.png"));
sb.append("\"/></a>");
}
/**
* Returns the HTML representing a job pair's status
*
* @param statType 'asc' or 'desc'
* @param value a job pair's completePairs, pendingPairs, or errorPairs variable
* @param percentage a job pair's totalPairs variable
* @return HTML representing a job pair's status
* @author Todd Elvers
*/
public static String getPercentStatHtml(String statType, int value, Boolean percentage) {
StringBuilder sb = new StringBuilder();
sb.append("<p class=\"stat ");
sb.append(statType);
sb.append("\">");
sb.append(value);
if (percentage) {
sb.append(" %");
}
sb.append("</p>");
return sb.toString();
}
/**
* Gets a datatables JSON object for job pairs in a jobspace.
*
* @param jobSpaceId The jobspace to get the pairs from
* @param wallclock Whether to use wallclock (true) or CPU time (false)
* @param syncResults
* @param stageNumber The pipeline stage number to filter jobs by.
* @param primitivesToAnonymize A PrimitivesToAnonymize enum describing which primitives to anonymize
* @param request The HttpRequest asking to get the JSON object
* @return a JSON object for the job pairs in a job space.
* @author Albert Giegerich and Todd Elvers
*/
protected static String getJobPairsPaginatedJson(int jobSpaceId, boolean wallclock, boolean syncResults, int stageNumber, PrimitivesToAnonymize primitivesToAnonymize, HttpServletRequest request) {
final String methodName = "getJobPairsPaginatedJson";
log.entry(methodName);
// Query for the next page of job pairs and return them to the user
JsonObject nextDataTablesPage = RESTHelpers.getNextDataTablesPageOfPairsInJobSpace(jobSpaceId, request, wallclock, syncResults, stageNumber, primitivesToAnonymize);
if (nextDataTablesPage == null) {
log.debug(methodName, "There was a database error while trying to get paginated job pairs for table.");
return gson.toJson(RESTServices.ERROR_DATABASE);
} else if (nextDataTablesPage.has("maxpairs")) {
log.debug(methodName, "User had too many job pairs for data table to be populated.");
return gson.toJson(RESTServices.ERROR_TOO_MANY_JOB_PAIRS);
}
return gson.toJson(nextDataTablesPage);
}
/**
* Gets the space overview graph for a given jobspace.
*
* @param jobId the job to get the graph for.
*/
protected static String getPairTimeGraphJson(int jobId) {
String chartPath = Statistics.makeJobTimeGraph(jobId);
if (chartPath.equals(Statistics.OVERSIZED_GRAPH_ERROR)) {
return gson.toJson(RESTServices.ERROR_TOO_MANY_JOB_PAIRS);
}
log.debug("chartPath = " + chartPath);
return chartPath == null ? gson.toJson(RESTServices.ERROR_DATABASE) : chartPath;
}
/**
* Gets the space overview graph for a given jobspace.
*
* @param stageNumber which stage to filter solvers by.
* @param jobSpaceId the jobSpace to get the graph for.
* @param request the HTTP request that is requesting the graph.
* @param primitivesToAnonymize a PrimitivesToAnonymize enum describing which primitives to anonymize for the graph.
*/
protected static String getSpaceOverviewGraphJson(int stageNumber, int jobSpaceId, HttpServletRequest request, PrimitivesToAnonymize primitivesToAnonymize) {
List<Integer> configIds = Util.toIntegerList(request.getParameterValues("selectedIds[]"));
boolean logX = false;
boolean logY = false;
if (Util.paramExists("logX", request)) {
if (Boolean.parseBoolean((String) request.getParameter("logX"))) {
logX = true;
}
}
if (Util.paramExists("logY", request)) {
if (Boolean.parseBoolean((String) request.getParameter("logY"))) {
logY = true;
}
}
String chartPath = null;
if (configIds.size() <= R.MAXIMUM_SOLVER_CONFIG_PAIRS) {
chartPath = Statistics.makeSpaceOverviewChart(jobSpaceId, logX, logY, configIds, stageNumber, primitivesToAnonymize);
if (chartPath.equals(Statistics.OVERSIZED_GRAPH_ERROR)) {
return gson.toJson(RESTServices.ERROR_TOO_MANY_JOB_PAIRS);
}
} else {
return gson.toJson(RESTServices.ERROR_TOO_MANY_SOLVER_CONFIG_PAIRS);
}
log.debug("chartPath = " + chartPath);
return chartPath == null ? gson.toJson(RESTServices.ERROR_DATABASE) : chartPath;
}
/**
* Gets the next data table page of job solver stats.
*
* @param stageNumber The stagenumber associated with the solver stats we want.
* @param jobSpace The jobspace associated with the solver stats we want.
* @param primitivesToAnonymize a PrimitivesToAnonymize enum describing which primitives should be given anonymous names.
* @param shortFormat Whether to use the abbreviated short format.
* @param wallclock Whether times should be in wallclock time or cpu time.
* @param includeUnknown True to include pairs with unknown status in time calculation
* @author Albert Giegerich
*/
protected static String getNextDataTablePageForJobStats(int stageNumber, JobSpace jobSpace, PrimitivesToAnonymize primitivesToAnonymize, boolean shortFormat, boolean wallclock, boolean includeUnknown) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
// changed this from Jobs.getAllJobStatsInJobSpaceHierarchy() to Jobs.getAllJobStatsInJobSpaceHierarchyIncludeDeletedConfigs()
// had to split up a function call chain to one version that includes configs marked as deleted and another that does not
// this includes them; used to construct the solver summary table in the job space view
// Alexander Brown, 9/20
Collection<SolverStats> solverStats = Jobs.getAllJobStatsInJobSpaceHierarchyIncludeDeletedConfigs(jobSpace, stageNumber, primitivesToAnonymize, includeUnknown);
stopWatch.stop();
log.debug("getNextDataTablePageForJobStats", "Time taken to get all jobs: " + stopWatch.toString());
if (solverStats == null) {
return gson.toJson(RESTServices.ERROR_DATABASE);
}
JsonObject nextDataTablesPage = RESTHelpers.convertSolverStatsToJsonObject(solverStats, new DataTablesQuery(solverStats.size(), solverStats.size(), 1), jobSpace.getId(), jobSpace.getJobId(), shortFormat, wallclock, primitivesToAnonymize);
return gson.toJson(nextDataTablesPage);
}
/**
* Gets the next page of job pairs as a JsonObject in the given jobSpaceId, with info populated from the given stage.
*
* @param jobSpaceId The ID of the job space
* @param request
* @param wallclock True to use wallclock time, false to use CPU time
* @param syncResults If true, excludes job pairs for which the benchmark has not been worked on by every solver in the space
* @param stageNumber If greater than or equal to 0, gets the primary stage
* @param primitivesToAnonymize a PrimitivesToAnonymize enum describing how the job paris should be anonymized.
* @return JsonObject encapsulating pairs to display in the next table page
*/
public static JsonObject getNextDataTablesPageOfPairsInJobSpace(int jobSpaceId, HttpServletRequest request, boolean wallclock, boolean syncResults, int stageNumber, PrimitivesToAnonymize primitivesToAnonymize) {
final String methodName = "getNextDataTablesPageOfPairsInJobSpace";
log.entry(methodName);
log.debug("beginningGetNextDataTablesPageOfPairsInJobSpace with stage = " + stageNumber);
DataTablesQuery query = RESTHelpers.getAttrMap(Primitive.JOB_PAIR, request);
if (query == null) {
return null;
}
query.setTotalRecords(Jobs.getJobPairCountInJobSpaceByStage(jobSpaceId, stageNumber));
if (query.getTotalRecords() > R.MAXIMUM_JOB_PAIRS) {
//there are too many job pairs to display quickly, so just don't query for them
JsonObject ob = new JsonObject();
ob.addProperty("maxpairs", true);
return ob;
}
String sortOverride = request.getParameter(SORT_COLUMN_OVERRIDE);
if (sortOverride != null) {
query.setSortColumn(Integer.parseInt(sortOverride));
query.setSortASC(Boolean.parseBoolean(request.getParameter(SORT_COLUMN_OVERRIDE_DIR)));
}
List<JobPair> jobPairsToDisplay;
// Retrieves the relevant Job objects to use in constructing the JSON to
// send to the client
int[] totals = new int[2];
if (!syncResults) {
jobPairsToDisplay = Jobs.getJobPairsForNextPageInJobSpace(query, jobSpaceId, stageNumber, wallclock, primitivesToAnonymize);
if (!query.hasSearchQuery()) {
query.setTotalRecordsAfterQuery(query.getTotalRecords());
} else {
query.setTotalRecordsAfterQuery(Jobs.getJobPairCountInJobSpaceByStage(jobSpaceId, query.getSearchQuery(), stageNumber));
}
} else {
log.debug("returning synchronized results");
jobPairsToDisplay = Jobs.getSynchronizedJobPairsForNextPageInJobSpace(query, jobSpaceId, wallclock, stageNumber, totals, primitivesToAnonymize);
query.setTotalRecords(totals[0]);
query.setTotalRecordsAfterQuery(totals[1]);
}
return convertJobPairsToJsonObject(jobPairsToDisplay, query, wallclock, 0, primitivesToAnonymize);
}
/**
* Gets the next page of Benchmarks that the given use can see. This includes Benchmarks the user owns,
* Benchmarks in public spaces, and Benchmarks in spaces the user is also in.
*
* @param userId
* @param request
* @return JsonObject encapsulating next page of benchmarks to display
*/
public static JsonObject getNextDataTablesPageOfBenchmarksByUser(int userId, HttpServletRequest request) {
log.debug("called getNextDataTablesPageOfBenchmarksByUser");
try {
DataTablesQuery query = RESTHelpers.getAttrMap(Primitive.BENCHMARK, request);
if (query == null) {
return null;
}
// Retrieves the relevant Job objects to use in constructing the JSON to
// send to the client
int[] totals = new int[2];
List<Benchmark> BenchmarksToDisplay = Benchmarks.getBenchmarksForNextPageByUser(query, userId, totals);
query.setTotalRecords(totals[0]);
query.setTotalRecordsAfterQuery(totals[1]);
return convertBenchmarksToJsonObject(BenchmarksToDisplay, query);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
/**
* Copies a benchmark from StarExec to StarDev
*
* @param commandConnection a logged in StarExecCommand connection.
* @param benchmarkId the benchmark to be copied from StarExec.
* @param spaceId the space to copy the benchmark to on StarDev.
* @return a status code indicating success or failure.
*/
protected static ValidatorStatusCode copyBenchmarkToStarDev(Connection commandConnection, int benchmarkId, int spaceId, int benchProcessorId) {
Benchmark benchmarkToCopy = Benchmarks.get(benchmarkId);
File sandbox = Util.getRandomSandboxDirectory();
try {
File tempFile = copyPrimitiveToSandbox(sandbox, benchmarkToCopy);
int uploadStatus = commandConnection.uploadBenchmarksToSingleSpace(tempFile.getAbsolutePath(), benchProcessorId, spaceId, true);
return outputStatus(commandConnection.getLastError(), uploadStatus, "Successfully copied benchmark to StarDev");
} catch (IOException e) {
log.warn("Could not copy benchmark to sandbox for copying to StarDev.", e);
return new ValidatorStatusCode(false, "Could not copy benchmark.");
} finally {
deleteSandbox(sandbox);
}
}
/**
* Copies a solver from StarExec to StarDev
*
* @param commandConnection a logged-in connection to StarDev
* @param solverId the ID of the solver to copy on StarExec.
* @param spaceId the ID of the space to copy to on StarDev.
* @return a ValidatorStatusCode indicating success or failure.
*/
protected static ValidatorStatusCode copySolverToStarDev(Connection commandConnection, int solverId, int spaceId) {
Solver solverToCopy = Solvers.get(solverId);
File sandbox = Util.getRandomSandboxDirectory();
try {
File tempFile = copyPrimitiveToSandbox(sandbox, solverToCopy);
int uploadStatus = commandConnection.uploadSolver(solverToCopy.getName(), solverToCopy.getDescription(), spaceId, tempFile.getAbsolutePath(), true, // downloadable
false, // run test job
null, // default settings ID for test job
C.DEFAULT_SOLVER_TYPE);
return outputStatus(commandConnection.getLastError(), uploadStatus, "Successfully copied solver to StarDev");
} catch (IOException e) {
log.warn("Could not copy solver to sandbox for copying to StarDev.", e);
return new ValidatorStatusCode(false, "Could not copy solver.");
} finally {
deleteSandbox(sandbox);
}
}
/**
* Copies a processor to a StarDev instance.
*
* @param commandConnection an open StarExecCommand connection.
* @param processorId the processor to copy.
* @param communityId the community to copy the processor to (on stardev).
* @return ValidatorStatusCode representing success or failure
*/
protected static ValidatorStatusCode copyProcessorToStarDev(Connection commandConnection, int processorId, int communityId) {
Processor processorToCopy = Processors.get(processorId);
ProcessorType procType = processorToCopy.getType();
File sandbox = Util.getRandomSandboxDirectory();
try {
// Copy and zip the processor to the sandbox.
File tempFile = copyPrimitiveToSandbox(sandbox, processorToCopy);
// Upload the processor using the connection.
// The upload status will be a status code on failure or the id of the new processor on success.
int uploadStatus;
switch (procType) {
case POST:
uploadStatus = commandConnection.uploadPostProc(processorToCopy.getName(), processorToCopy.getDescription(), tempFile.getAbsolutePath(), communityId);
break;
case PRE:
uploadStatus = commandConnection.uploadPreProc(processorToCopy.getName(), processorToCopy.getDescription(), tempFile.getAbsolutePath(), communityId);
break;
case BENCH:
uploadStatus = commandConnection.uploadBenchProc(processorToCopy.getName(), processorToCopy.getDescription(), tempFile.getAbsolutePath(), communityId);
break;
default:
return new ValidatorStatusCode(false, "This processor type is not yet supported.");
}
return outputStatus(commandConnection.getLastError(), uploadStatus, "Successfully copied processor to StarDev");
} catch (IOException e) {
log.warn("Could not copy solver to sandbox for copying to StarDev.", e);
return new ValidatorStatusCode(false, "Could not copy processor.", Util.getStackTrace(e));
} finally {
deleteSandbox(sandbox);
}
}
/**
* Validates a copy to stardev request when copying a benchmark with it's processor.
*
* @param request the http reuquest.
* @return a ValidatorStatusCode indicating success/failure.
*/
protected static ValidatorStatusCode validateCopyBenchWithProcessorToStardev(HttpServletRequest request) {
ValidatorStatusCode isValid = validateAllCopyToStardev(request);
if (!isValid.isSuccess()) {
return isValid;
}
return new ValidatorStatusCode(true);
}
public static Connection instantiateConnectionForCopyToStardev(String instance, HttpServletRequest request) {
final String username = request.getParameter(R.COPY_TO_STARDEV_USERNAME_PARAM);
final String password = request.getParameter(R.COPY_TO_STARDEV_PASSWORD_PARAM);
// Login to StarDev
String url = "https://stardev.cs.uiowa.edu/" + instance + "/";
return new Connection(username, password, url);
}
/**
* Validates a copy to stardev request
*
* @param request the copy to stardev request.
* @param primType the primitive type
* @return ValidatorStatusCode representing success or failure
*/
public static ValidatorStatusCode validateCopyToStardev(HttpServletRequest request, final String primType) {
ValidatorStatusCode isValid = validateAllCopyToStardev(request);
if (!isValid.isSuccess()) {
return isValid;
}
// The primitive type must correspond to one of the Primitive enums.
boolean validPrimitive = Util.isLegalEnumValue(primType, Primitive.class);
if (!validPrimitive) {
return new ValidatorStatusCode(false, "The given primitive type is not valid.");
}
Primitive primitive = Primitive.valueOf(primType);
if (primitive == Primitive.BENCHMARK) {
// For benchmark copies a processor must be specified.
if (!Util.paramExists(R.COPY_TO_STARDEV_PROC_ID_PARAM, request)) {
return new ValidatorStatusCode(false, "The processor ID parameter was not present in the request.");
}
// The processor ID must be an integer
if (!Validator.isValidInteger(request.getParameter(R.COPY_TO_STARDEV_PROC_ID_PARAM))) {
return new ValidatorStatusCode(false, "The processor ID was not a valid integer: " + request.getParameter(R.COPY_TO_STARDEV_PROC_ID_PARAM));
}
}
return new ValidatorStatusCode(true);
}
private static ValidatorStatusCode validateAllCopyToStardev(HttpServletRequest request) {
// Only developers and admins can do a copy to stardev request.
int userId = SessionUtil.getUserId(request);
if (!Users.isAdmin(userId) && !Users.isDeveloper(userId)) {
return new ValidatorStatusCode(false, "You must be an admin or developer to do this.");
}
// There must be a username and password parameter.
if (!Util.paramExists(R.COPY_TO_STARDEV_USERNAME_PARAM, request) || !Util.paramExists(R.COPY_TO_STARDEV_PASSWORD_PARAM, request)) {
return new ValidatorStatusCode(false, "The username or password parameter was not found.");
}
// Space/community ID must be present for non-benchmark copies.
boolean isSpaceIdParamPresent = Util.paramExists(R.COPY_TO_STARDEV_SPACE_ID_PARAM, request);
if (!isSpaceIdParamPresent) {
return new ValidatorStatusCode(false, "A space ID parameter was not present in request.");
}
// The space ID parameter must be an integer if it exists.
if (!Validator.isValidInteger(request.getParameter(R.COPY_TO_STARDEV_SPACE_ID_PARAM))) {
return new ValidatorStatusCode(false, "The space ID parameter was not in integer format.");
}
return new ValidatorStatusCode(true);
}
/**
* Outputs a ValidatorStatusCode based on a StarExecCOmmand status code.
*
* @param lastError the last error returned by a StarExecCommand connection.
* @param uploadStatus the Command status code to convert to a ValidatorStatusCode.
* @param successMessage message to use in ValidatorStatusCode on success.
* @return a ValidatorStatusCode based on the given Command status code.
*/
private static ValidatorStatusCode outputStatus(String lastError, int uploadStatus, String successMessage) {
if (uploadStatus < 0) {
log.warn("Command failed to upload primitive: " + org.starexec.command.Status.getStatusMessage(uploadStatus) + "\n" + lastError);
return new ValidatorStatusCode(false, org.starexec.command.Status.getStatusMessage(uploadStatus), lastError);
}
// on success the upload status will be the id of the new processor
return new ValidatorStatusCode(true, successMessage, uploadStatus);
}
// Helper method for copying primitive to StarDev.
public static ValidatorStatusCode copyPrimitiveToStarDev(Connection commandConnection, Primitive primType, Integer primitiveId, HttpServletRequest request) {
final int spaceId = Integer.parseInt(request.getParameter(R.COPY_TO_STARDEV_SPACE_ID_PARAM));
switch (primType) {
case BENCHMARK:
final int benchProcessorId = Integer.parseInt(request.getParameter(R.COPY_TO_STARDEV_PROC_ID_PARAM));
return RESTHelpers.copyBenchmarkToStarDev(commandConnection, primitiveId, spaceId, benchProcessorId);
case SOLVER:
return RESTHelpers.copySolverToStarDev(commandConnection, primitiveId, spaceId);
case PROCESSOR:
return RESTHelpers.copyProcessorToStarDev(commandConnection, primitiveId, spaceId);
default:
return new ValidatorStatusCode(false, "That type is not yet supported.");
}
}
/**
* Zips a primitive into the given Sandbox.
*
* @param sandbox the sandbox to place the zip file in.
* @param primitive the primitive to zip into the sandbox.
* @return the zip file.
* @throws IOException if something goes wrong with copying or zipping.
*/
private static File copyPrimitiveToSandbox(final File sandbox, final Locatable primitive) throws IOException {
// Use this sandbox as the directory that will be zipped and placed into the input sandbox directory.
File tempSandbox = Util.getRandomSandboxDirectory();
try {
// place the file in the temp sandbox.
File primitiveFile = new File(primitive.getPath());
if (primitiveFile.isDirectory()) {
FileUtils.copyDirectory(primitiveFile, tempSandbox);
} else {
FileUtils.copyFileToDirectory(primitiveFile, tempSandbox);
}
// This name doesn't really matter since it's only used internally.
String archiveName = "temp.zip";
File outputFile = new File(sandbox, archiveName);
// Zip the temp sandbox into the input sandbox.
ArchiveUtil.createAndOutputZip(tempSandbox, new FileOutputStream(outputFile), archiveName, true);
return outputFile;
} finally {
deleteSandbox(tempSandbox);
}
}
// Deletes a sandbox directory.
private static void deleteSandbox(File sandbox) {
try {
FileUtils.deleteDirectory(sandbox);
} catch (IOException e) {
log.error("Caught IOException while deleting directory: " + sandbox.getAbsolutePath() + "\nDirectory may not have been deleted", e);
}
}
/**
* Gets the next page of solvers that the given user can see. This includes solvers the user owns,
* solvers in public spaces, and solvers in spaces the user is also in.
*
* @param userId
* @param request
* @return JsonObject encapsulating next page of solvers to display
*/
public static JsonObject getNextDataTablesPageOfSolversByUser(int userId, HttpServletRequest request) {
try {
DataTablesQuery query = RESTHelpers.getAttrMap(Primitive.SOLVER, request);
if (query == null) {
return null;
}
// Retrieves the relevant Job objects to use in constructing the JSON to
// send to the client
int[] totals = new int[2];
List<Solver> solversToDisplay = Solvers.getSolversForNextPageByUser(query, userId, totals);
query.setTotalRecords(totals[0]);
query.setTotalRecordsAfterQuery(totals[1]);
return convertSolversToJsonObject(solversToDisplay, query);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
/**
* Returns the next page of SolverComparison objects needed for a DataTables page in a job space
*
* @param jobSpaceId
* @param configId1
* @param configId2
* @param request
* @param wallclock
* @param stageNumber
* @return JsonObject encapsulating next page of solver comparisons to display
*/
public static JsonObject getNextDataTablesPageOfSolverComparisonsInSpaceHierarchy(int jobSpaceId, int configId1, int configId2, HttpServletRequest request, boolean wallclock, int stageNumber) {
try {
DataTablesQuery query = RESTHelpers.getAttrMap(Primitive.JOB_PAIR, request);
if (query == null) {
return null;
}
// Retrieves the relevant Job objects to use in constructing the JSON to
// send to the client
int[] totals = new int[2];
List<SolverComparison> solverComparisonsToDisplay = Jobs.getSolverComparisonsForNextPageByConfigInJobSpaceHierarchy(query, jobSpaceId, configId1, configId2, totals, wallclock, stageNumber);
query.setTotalRecords(totals[0]);
query.setTotalRecordsAfterQuery(totals[1]);
return convertSolverComparisonsToJsonObject(solverComparisonsToDisplay, query, wallclock, stageNumber, jobSpaceId);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
public static JsonObject getNextDataTablesPageOfPairsByConfigInSpaceHierarchy(int jobSpaceId, int configId, HttpServletRequest request, String type, boolean wallclock, int stageNumber) {
DataTablesQuery query = RESTHelpers.getAttrMap(Primitive.JOB_PAIR, request);
if (query == null) {
return null;
}
String sortOverride = request.getParameter(SORT_COLUMN_OVERRIDE);
if (sortOverride != null) {
query.setSortColumn(Integer.parseInt(sortOverride));
query.setSortASC(Boolean.parseBoolean(request.getParameter(SORT_COLUMN_OVERRIDE_DIR)));
}
// Retrieves the relevant Job objects to use in constructing the JSON to
// send to the client
List<JobPair> jobPairsToDisplay = Jobs.getJobPairsForNextPageByConfigInJobSpaceHierarchy(query, jobSpaceId, configId, type, stageNumber);
query.setTotalRecords(Jobs.getCountOfJobPairsByConfigInJobSpaceHierarchy(jobSpaceId, configId, type, stageNumber));
query.setTotalRecordsAfterQuery(Jobs.getCountOfJobPairsByConfigInJobSpaceHierarchy(jobSpaceId, configId, type, query.getSearchQuery(), stageNumber));
return convertJobPairsToJsonObject(jobPairsToDisplay, query, wallclock, stageNumber, PrimitivesToAnonymize.NONE);
}
/**
* Gets the next page of job_pair entries for a DataTable object on cluster
* Status page
*
* @param type either queue or node
* @param id the id of the queue/node to get job pairs for
* @param request the object containing all the DataTable parameters
* @return a JSON object representing the next page of primitives to return
* to the client,<br>
* or null if the parameters of the request fail validation
* @author Wyatt Kaiser
*/
public static JsonObject getNextDataTablesPageCluster(String type, int id, int userId, HttpServletRequest request) {
try {
// Parameter validation
DataTablesQuery query = RESTHelpers.getAttrMap(Primitive.NODE, request);
if (query == null) {
return null;
}
if (type.equals("queue")) {
// Retrieves the relevant Job objects to use in constructing the
// JSON to send to the client
List<JobPair> jobPairsToDisplay = Queues.getJobPairsForNextClusterPage(query, id);
query.setTotalRecords(Queues.getCountOfEnqueuedPairsByQueue(id));
// there is no filter function on this table, so this is always equal to the above
query.setTotalRecordsAfterQuery(query.getTotalRecords());
return convertJobPairsToJsonObjectCluster(jobPairsToDisplay, query, userId);
} else if (type.equals("node")) {
// Retrieves the relevant Job objects to use in constructing the
// JSON to send to the client
List<JobPair> jobPairsToDisplay = Queues.getPairsRunningOnNode(id);
query.setTotalRecords(jobPairsToDisplay.size());
// there is no filter function on this table, so this is always equal to the above
query.setTotalRecordsAfterQuery(query.getTotalRecords());
return convertJobPairsToJsonObjectCluster(jobPairsToDisplay, query, userId);
}
return null;
} catch (Exception e) {
log.error("getNextDataTablesPageCluster", e);
}
return null;
}
/**
* Gets the next page of entries for a DataTable Object (ALL regardless of
* space)
*
* @param request the object containing all the DataTable parameters
* @return a JSON object representing the next page of primitives to return
* to the client, <br>
* or null if the parameters of the request fail validation
* @author Wyatt Kaiser
*/
protected static JsonObject getNextUsersPageAdmin(HttpServletRequest request) {
// Parameter Validation
int currentUserId = SessionUtil.getUserId(request);
DataTablesQuery query = RESTHelpers.getAttrMap(Primitive.USER, request);
if (query == null) {
return null;
}
query.setTotalRecords(Users.getCount());
// Retrieves the relevant User objects to use in constructing the
// JSON to send to the client
List<User> usersToDisplay = Users.getUsersForNextPageAdmin(query);
// If no search is provided, TOTAL_RECORDS_AFTER_QUERY =
// TOTAL_RECORDS
if (!query.hasSearchQuery()) {
query.setTotalRecordsAfterQuery(query.getTotalRecords());
}
// Otherwise, TOTAL_RECORDS_AFTER_QUERY < TOTAL_RECORDS
else {
query.setTotalRecordsAfterQuery(usersToDisplay.size());
}
return convertUsersToJsonObject(usersToDisplay, query, currentUserId);
}
public static JsonObject getNextBenchmarkPageForSpaceExplorer(int id, HttpServletRequest request) {
// Parameter validation
DataTablesQuery query = RESTHelpers.getAttrMap(Primitive.BENCHMARK, request);
if (query == null) {
return null;
}
String sortOverride = request.getParameter(SORT_COLUMN_OVERRIDE);
if (sortOverride != null) {
query.setSortColumn(Integer.parseInt(sortOverride));
query.setSortASC(Boolean.parseBoolean(request.getParameter(SORT_COLUMN_OVERRIDE_DIR)));
}
// Retrieves the relevant Benchmark objects to use in constructing the JSON to send to the client
List<Benchmark> benchmarksToDisplay = Benchmarks.getBenchmarksForNextPage(query, id);
query.setTotalRecords(Benchmarks.getCountInSpace(id));
// If no search is provided, TOTAL_RECORDS_AFTER_QUERY = TOTAL_RECORDS
if (!query.hasSearchQuery()) {
query.setTotalRecordsAfterQuery(query.getTotalRecords());
} else {
query.setTotalRecordsAfterQuery(Benchmarks.getCountInSpace(id, query.getSearchQuery()));
}
return convertBenchmarksToJsonObject(benchmarksToDisplay, query);
}
public static JsonObject getNextJobPageForSpaceExplorer(int id, HttpServletRequest request) {
// Parameter validation
DataTablesQuery query = RESTHelpers.getAttrMap(Primitive.JOB, request);
if (query == null) {
return null;
}
// Retrieves the relevant Job objects to use in constructing the
// JSON to send to the client
List<Job> jobsToDisplay = Jobs.getJobsForNextPage(query, id);
query.setTotalRecords(Jobs.getCountInSpace(id));
if (!query.hasSearchQuery()) {
query.setTotalRecordsAfterQuery(query.getTotalRecords());
} else {
query.setTotalRecordsAfterQuery(Jobs.getCountInSpace(id, query.getSearchQuery()));
}
// If no search is provided, TOTAL_RECORDS_AFTER_QUERY = TOTAL_RECORDS
return convertJobsToJsonObject(jobsToDisplay, query, false);
}
public static JsonObject getNextUserPageForSpaceExplorer(int id, HttpServletRequest request) {
// Parameter validation
DataTablesQuery query = RESTHelpers.getAttrMap(Primitive.USER, request);
if (query == null) {
return null;
}
query.setTotalRecords(Users.getCountInSpace(id));
// Retrieves the relevant User objects to use in constructing the JSON to send to the client
List<User> usersToDisplay = Users.getUsersForNextPage(query, id);
// If no search is provided, TOTAL_RECORDS_AFTER_QUERY = TOTAL_RECORDS
if (!query.hasSearchQuery()) {
query.setTotalRecordsAfterQuery(query.getTotalRecords());
}
// Otherwise, TOTAL_RECORDS_AFTER_QUERY < TOTAL_RECORDS
else {
query.setTotalRecordsAfterQuery(Users.getCountInSpace(id, query.getSearchQuery()));
}
return convertUsersToJsonObject(usersToDisplay, query, SessionUtil.getUserId(request));
}
public static JsonObject getNextSolverPageForSpaceExplorer(int id, HttpServletRequest request) {
// Parameter validation
DataTablesQuery query = RESTHelpers.getAttrMap(Primitive.SOLVER, request);
if (query == null) {
return null;
}
// Retrieves the relevant Solver objects to use in constructing the JSON to send to the client
List<Solver> solversToDisplay = Solvers.getSolversForNextPage(query, id);
query.setTotalRecords(Solvers.getCountInSpace(id));
if (!query.hasSearchQuery()) {
query.setTotalRecordsAfterQuery(query.getTotalRecords());
}
// Otherwise, TOTAL_RECORDS_AFTER_QUERY < TOTAL_RECORDS
else {
query.setTotalRecordsAfterQuery(Solvers.getCountInSpace(id, query.getSearchQuery()));
}
return convertSolversToJsonObject(solversToDisplay, query);
}
public static JsonObject getNextSpacePageForSpaceExplorer(int id, HttpServletRequest request) {
// Parameter validation
DataTablesQuery query = RESTHelpers.getAttrMap(Primitive.SPACE, request);
if (query == null) {
return null;
}
int userId = SessionUtil.getUserId(request);
query.setTotalRecords(Spaces.getCountInSpace(id, userId, false));
// Retrieves the relevant Benchmark objects to use in constructing the JSON to send to the client
List<Space> spacesToDisplay = Spaces.getSpacesForNextPage(query, id, userId);
// If no search is provided, TOTAL_RECORDS_AFTER_QUERY = TOTAL_RECORDS
if (!query.hasSearchQuery()) {
query.setTotalRecordsAfterQuery(query.getTotalRecords());
}
// Otherwise, TOTAL_RECORDS_AFTER_QUERY < TOTAL_RECORDS
else {
query.setTotalRecordsAfterQuery(Spaces.getCountInSpace(id, userId, query.getSearchQuery()));
}
return convertSpacesToJsonObject(spacesToDisplay, query);
}
/*
* Given data about a request, return a json object representing the next page
* Docs by @aguo2
* @author ArchieKipp
*
*/
public static JsonObject getNextDataTablesPageForUserDetails(Primitive type, int id, HttpServletRequest request, boolean recycled, boolean dataAsObjects) {
// Parameter validation
DataTablesQuery query = RESTHelpers.getAttrMap(type, request);
if (query == null) {
return null;
}
switch (type) {
case JOB:
// Retrieves the relevant Job objects to use in constructing the
// JSON to send to the client
List<Job> jobsToDisplay = Jobs.getJobsByUserForNextPage(query, id);
query.setTotalRecords(Jobs.getJobCountByUser(id));
if (!query.hasSearchQuery()) {
query.setTotalRecordsAfterQuery(query.getTotalRecords());
} else {
query.setTotalRecordsAfterQuery(Jobs.getJobCountByUser(id, query.getSearchQuery()));
}
// If no search is provided, TOTAL_RECORDS_AFTER_QUERY = TOTAL_RECORDS
return convertJobsToJsonObject(jobsToDisplay, query, dataAsObjects);
case SOLVER:
// Retrieves the relevant Solver objects to use in constructing the JSON to send to the client
List<Solver> solversToDisplay = Solvers.getSolversByUserForNextPage(query, id, recycled);
if (!recycled) {
query.setTotalRecords(Solvers.getSolverCountByUser(id));
} else {
query.setTotalRecords(Solvers.getRecycledSolverCountByUser(id));
}
// If no search is provided, TOTAL_RECORDS_AFTER_QUERY = TOTAL_RECORDS
if (!query.hasSearchQuery()) {
query.setTotalRecordsAfterQuery(query.getTotalRecords());
}
// Otherwise, TOTAL_RECORDS_AFTER_QUERY < TOTAL_RECORDS
else {
if (!recycled) {
query.setTotalRecordsAfterQuery(Solvers.getSolverCountByUser(id, query.getSearchQuery()));
} else {
query.setTotalRecordsAfterQuery(Solvers.getRecycledSolverCountByUser(id, query.getSearchQuery()));
}
}
return convertSolversToJsonObject(solversToDisplay, query);
case UPLOAD:
query.setTotalRecords(Uploads.getUploadCountByUser(id));
if (!query.hasSearchQuery()) {
query.setTotalRecordsAfterQuery(query.getTotalRecords());
} else {
query.setTotalRecordsAfterQuery(Uploads.getUploadCountByUser(id, query.getSearchQuery()));
}
query.setSortASC(!query.isSortASC());
List<BenchmarkUploadStatus> uploadsToDisplay = Uploads.getUploadsByUserForNextPage(query, id);
JsonObject obj = convertUploadsToJsonObject(uploadsToDisplay, query);
return obj;
case BENCHMARK:
String sortOverride = request.getParameter(SORT_COLUMN_OVERRIDE);
if (sortOverride != null) {
query.setSortColumn(Integer.parseInt(sortOverride));
query.setSortASC(Boolean.parseBoolean(request.getParameter(SORT_COLUMN_OVERRIDE_DIR)));
}
List<Benchmark> benchmarksToDisplay = Benchmarks.getBenchmarksByUserForNextPage(query, id, recycled);
if (!recycled) {
query.setTotalRecords(Benchmarks.getBenchmarkCountByUser(id));
} else {
query.setTotalRecords(Benchmarks.getRecycledBenchmarkCountByUser(id));
}
// If no search is provided, TOTAL_RECORDS_AFTER_QUERY = TOTAL_RECORDS
if (!query.hasSearchQuery()) {
query.setTotalRecordsAfterQuery(query.getTotalRecords());
} else {
if (!recycled) {
query.setTotalRecordsAfterQuery(Benchmarks.getBenchmarkCountByUser(id, query.getSearchQuery()));
} else {
query.setTotalRecordsAfterQuery(Benchmarks.getRecycledBenchmarkCountByUser(id, query.getSearchQuery()));
}
}
return convertBenchmarksToJsonObject(benchmarksToDisplay, query);
default:
log.error("invalid type given = " + type);
}
return null;
}
/**
* Generate the HTML for the next DataTable page of entries
*
* @param pairs The job pairs to convert
* @param query a DataTablesQuery object
* @param userId The ID of the user making this request
* @return JsonObject a JsonObject representing the pairs + other DataTables fields.
*/
public static JsonObject convertJobPairsToJsonObjectCluster(List<JobPair> pairs, DataTablesQuery query, int userId) {
JsonArray dataTablePageEntries = new JsonArray();
final String baseUrl = Util.docRoot("secure/details/job.jsp?id=");
for (JobPair j : pairs) {
final String pairLink = j.getQueueSubmitTimeSafe().toString();
// Create the job link
//Job job = Jobs.get(j.getJobId());
StringBuilder sb = new StringBuilder();
sb.append("<a href='");
sb.append(baseUrl);
sb.append(j.getJobId());
sb.append("' target='_blank'>");
sb.append(j.getOwningJob().getName());
RESTHelpers.addImg(sb);
sb.append(getHiddenJobPairLink(j.getId()));
String jobLink = sb.toString();
User user = j.getOwningUser();
String userLink = getUserLink(user.getId(), user.getFullName(), userId);
String benchLink = getBenchLinkWithHiddenPairId(j.getBench(), j.getId(), PrimitivesToAnonymize.NONE);
// Create the solver link
String solverLink = getSolverLink(j.getPrimarySolver().getId(), j.getPrimarySolver().getName(), PrimitivesToAnonymize.NONE);
// Create the configuration link
String configLink = getConfigLink(j.getPrimarySolver().getConfigurations().get(0).getId(), j.getPrimarySolver().getConfigurations().get(0).getName(), PrimitivesToAnonymize.NONE);
// Create an object, and inject the above HTML, to represent an entry in the DataTable
JsonArray entry = new JsonArray();
entry.add(new JsonPrimitive(pairLink));
entry.add(new JsonPrimitive(jobLink));
entry.add(new JsonPrimitive(userLink));
entry.add(new JsonPrimitive(benchLink));
entry.add(new JsonPrimitive(solverLink));
entry.add(new JsonPrimitive(configLink));
entry.add(new JsonPrimitive(j.getPath()));
dataTablePageEntries.add(entry);
}
return createPageDataJsonObject(query, dataTablePageEntries);
}
/**
* Generate the HTML for the next DataTable page of entries
*/
public static JsonObject convertSolverComparisonsToJsonObject(List<SolverComparison> comparisons, DataTablesQuery query, boolean useWallclock, int stageNumber, int jobSpaceId) {
JsonArray dataTablePageEntries = new JsonArray();
for (SolverComparison c : comparisons) {
// Create the benchmark link and append the hidden input element
String benchLink = getBenchLink(c.getBenchmark());
// Create an object, and inject the above HTML, to represent an
// entry in the DataTable
JsonArray entry = new JsonArray();
entry.add(new JsonPrimitive(benchLink));
if (useWallclock) {
double displayWC1 = Math.round(c.getFirstPair().getStageFromNumber(stageNumber).getWallclockTime() * 100) / 100.0;
double displayWC2 = Math.round(c.getSecondPair().getStageFromNumber(stageNumber).getWallclockTime() * 100) / 100.0;
double displayDiff = Math.round(c.getWallclockDifference(stageNumber) * 100) / 100.0;
entry.add(new JsonPrimitive(displayWC1 + " s"));
entry.add(new JsonPrimitive(displayWC2 + " s"));
entry.add(new JsonPrimitive(displayDiff + " s"));
} else {
double display1 = Math.round(c.getFirstPair().getStageFromNumber(stageNumber).getCpuTime() * 100) / 100.0;
double display2 = Math.round(c.getSecondPair().getStageFromNumber(stageNumber).getCpuTime() * 100) / 100.0;
double displayDiff = Math.round(c.getCpuDifference(stageNumber) * 100) / 100.0;
entry.add(new JsonPrimitive(display1 + " s"));
entry.add(new JsonPrimitive(display2 + " s"));
entry.add(new JsonPrimitive(displayDiff + " s"));
}
String link1 = getPairsInSpaceHtml(jobSpaceId, c.getFirstPair().getPrimaryConfiguration().getId(), c.getFirstPair().getStageFromNumber(stageNumber).getStarexecResult());
String link2 = getPairsInSpaceHtml(jobSpaceId, c.getSecondPair().getPrimaryConfiguration().getId(), c.getSecondPair().getStageFromNumber(stageNumber).getStarexecResult());
entry.add(new JsonPrimitive(link1));
entry.add(new JsonPrimitive(link2));
if (c.doResultsMatch(stageNumber)) {
entry.add(new JsonPrimitive(1));
} else {
entry.add(new JsonPrimitive(0));
}
dataTablePageEntries.add(entry);
}
return createPageDataJsonObject(query, dataTablePageEntries);
}
private static String getConfigLink(int configId, String configName, PrimitivesToAnonymize primitivesToAnonymize) {
StringBuilder sb = new StringBuilder();
sb.append("<a class=\"configLink\" title=\"");
sb.append(configName).append("\"");
// Add the link to the solver if we don't need to be an anoymous config.
if (!AnonymousLinks.areSolversAnonymized(primitivesToAnonymize)) {
// If the config has been marked as delted, use the link for the delted config page instead
try {
Configuration configuration = Solvers.getConfigurationIncludeDeleted( configId );
if ( configuration.getDeleted() == 1 ) {
sb.append( " href=\"" ).append( Util.docRoot( "secure/details/configDeleted.jsp?id=" ) );
sb.append(configId).append("\" target=\"_blank\"");
} else {
sb.append(" href=\"").append(Util.docRoot("secure/details/configuration.jsp?id="));
sb.append(configId).append("\" target=\"_blank\"");
}
} catch ( Exception e ) {
sb.append(" href=\"").append(Util.docRoot("secure/details/configuration.jsp?id="));
sb.append(configId).append("\" target=\"_blank\"");
}
}
sb.append(" id=\"");
sb.append(configId);
sb.append("\">");
sb.append(configName);
// Add link image to the solver if we don't need to be an anoymous config.
if (!AnonymousLinks.areSolversAnonymized(primitivesToAnonymize)) {
RESTHelpers.addImg(sb);
}
return sb.toString();
}
private static String getHiddenJobPairLink(int pairId) {
// Create the hidden input tag containing the jobpair id
return "<input type=\"hidden\" value=\"" + pairId + "\" name=\"pid\"/>";
}
private static String getHiddenBenchLink(Benchmark bench) {
// Create the hidden input tag containing the benchmark id
return "<input name=\"bench\" type=\"hidden\" value=\"" + bench.getId() + "\" prim=\"benchmark\" userId=\"" +
bench.getUserId() + "\" deleted=\"" + bench.isDeleted() + "\" recycled=\"" + bench.isRecycled() +
"\"/>";
}
private static StringBuilder getBenchLinkPrefix(Benchmark bench, PrimitivesToAnonymize primitivesToAnonymize) {
StringBuilder sb = new StringBuilder();
sb.append("<a");
// Set the tooltip to be the benchmark's description
if (!AnonymousLinks.areBenchmarksAnonymized(primitivesToAnonymize)) {
sb.append(" title=\"");
sb.append(bench.getDescription());
sb.append("\" ");
sb.append("href=\"").append(Util.docRoot("secure/details/benchmark.jsp?id="));
sb.append(bench.getId());
sb.append("\" target=\"_blank\"");
}
sb.append(">");
sb.append(bench.getName());
if (!AnonymousLinks.areBenchmarksAnonymized(primitivesToAnonymize)) {
RESTHelpers.addImg(sb);
}
return sb;
}
private static String getBenchLinkWithHiddenPairId(Benchmark bench, int pairId, PrimitivesToAnonymize primitivesToAnonymize) {
StringBuilder sb = getBenchLinkPrefix(bench, primitivesToAnonymize);
sb.append(getHiddenJobPairLink(pairId));
return sb.toString();
}
private static String getBenchLink(Benchmark bench) {
StringBuilder sb = getBenchLinkPrefix(bench, PrimitivesToAnonymize.NONE);
sb.append(getHiddenBenchLink(bench));
return sb.toString();
}
private static String getSpaceLink(Space space) {
StringBuilder sb = new StringBuilder();
sb.append("<input type=\"hidden\" value=\"");
sb.append(space.getId());
sb.append("\" prim=\"space\" />");
String hiddenSpaceId = sb.toString();
// Create the space "details" link and append the hidden input
// element
sb = new StringBuilder();
sb.append("<a class=\"spaceLink\" onclick=\"openSpace(");
sb.append(space.getParentSpace());
sb.append(",");
sb.append(space.getId());
sb.append(")\">");
sb.append(space.getName());
RESTHelpers.addImg(sb);
sb.append(hiddenSpaceId);
return sb.toString();
}
private static String getSolverLink(int solverId, String solverName, PrimitivesToAnonymize primitivesToAnonymize) {
StringBuilder sb = new StringBuilder();
sb.append("<a title=\"");
sb.append(solverName);
sb.append("\" ");
if (!AnonymousLinks.areSolversAnonymized(primitivesToAnonymize)) {
sb.append("href=\"").append(Util.docRoot("secure/details/solver.jsp?id="));
sb.append(solverId);
sb.append("\" target=\"_blank\"");
}
sb.append(">");
sb.append(solverName);
if (AnonymousLinks.areSolversAnonymized(primitivesToAnonymize)) {
sb.append("</a>");
} else {
RESTHelpers.addImg(sb);
}
return sb.toString();
}
private static String getUserLink(int userId, String name, int callerId) {
StringBuilder sb = new StringBuilder();
String hiddenUserId;
// Create the hidden input tag containing the user id
sb.append("<input type=\"hidden\" value=\"");
sb.append(userId);
if (userId == callerId) {
sb.append("\" name=\"currentUser\" id=\"uid").append(userId).append("\" prim=\"user\"/>");
} else {
sb.append("\" id=\"uid").append(userId).append("\" prim=\"user\"/>");
}
hiddenUserId = sb.toString();
// Create the user "details" link and append the hidden input
// element
sb = new StringBuilder();
sb.append("<a href=\"").append(Util.docRoot("secure/details/user.jsp?id="));
sb.append(userId);
sb.append("\" target=\"_blank\">");
sb.append(name);
RESTHelpers.addImg(sb);
sb.append(hiddenUserId);
return sb.toString();
}
/**
* Given a list of job pairs, creates a JsonObject that can be used to populate a datatable client-side
* It seems this is used to populate the job pairs table in the job view page
*
* @param pairs The pairs that will be the rows of the table
* @param query a DataTables query object
* @param useWallclock Whether to use wallclock time (true) or cpu time (false)
* @param stageNumber The number of the stage to use the data from for each pair
* @param primitivesToAnonymize PrimitivesToAnonymize object representing whether benchmarks, solvers, or both
* should be anonymized.
* @return A JsonObject that can be used to populate a datatable
* @author Eric Burns
*/
public static JsonObject convertJobPairsToJsonObject(List<JobPair> pairs, DataTablesQuery query, boolean useWallclock, int stageNumber, PrimitivesToAnonymize primitivesToAnonymize) {
/*
Generate the HTML for the next DataTable page of entries
*/
JsonArray dataTablePageEntries = new JsonArray();
String solverLink = null;
String configLink = null;
for (JobPair jp : pairs) {
JoblineStage stage = jp.getStageFromNumber(stageNumber);
String benchLink = getBenchLinkWithHiddenPairId(jp.getBench(), jp.getId(), primitivesToAnonymize);
// Create the solver link
solverLink = getSolverLink(stage.getSolver().getId(), stage.getSolver().getName(), primitivesToAnonymize);
// Create the configuration link
configLink = getConfigLink(stage.getSolver().getConfigurations().get(0).getId(), stage.getSolver().getConfigurations().get(0).getName(), primitivesToAnonymize);
// Create the status field
String status =
"<a title=\"" + stage.getStatus().getDescription() + "\">" + stage.getStatus().getStatus() + " (" +
stage.getStatus().getCode().getVal() + ")" + "</a>";
// Create an object, and inject the above HTML, to represent an
// entry in the DataTable
JsonArray entry = new JsonArray();
entry.add(new JsonPrimitive(benchLink));
entry.add(new JsonPrimitive(solverLink));
entry.add(new JsonPrimitive(configLink));
entry.add(new JsonPrimitive(status));
if (useWallclock) {
double displayWC = Math.round(stage.getWallclockTime() * 100) / 100.0;
entry.add(new JsonPrimitive(displayWC + " s"));
} else {
double displayCpu = Math.round(stage.getCpuTime() * 100) / 100.0;
entry.add(new JsonPrimitive(displayCpu + " s"));
}
entry.add(new JsonPrimitive(stage.getStarexecResult()));
dataTablePageEntries.add(entry);
}
return createPageDataJsonObject(query, dataTablePageEntries);
}
/**
* Given a list of jobs, creates a JsonObject that can be used to populate a
* datatable client-side
*
* @param jobs The jobs that will be the rows of the table
* @param query A DataTablesQuery object
* @return A JsonObject that can be used to populate a datatable
* @author Eric Burns
*/
public static JsonObject convertJobsToJsonObject(List<Job> jobs, DataTablesQuery query, boolean dataAsObjects) {
/*
Generate the HTML for the next DataTable page of entries
*/
JsonArray dataTablePageEntries = new JsonArray();
for (Job job : jobs) {
StringBuilder sb = new StringBuilder();
String hiddenJobId;
// Create the hidden input tag containing the job id
sb.append("<input type=\"hidden\" value=\"");
sb.append(job.getId());
sb.append("\" prim=\"job\" userId=\"").append(job.getUserId()).append("\" deleted=\"")
.append(job.isDeleted()).append("\"/>");
hiddenJobId = sb.toString();
// Create the job "details" link and append the hidden input element
sb = new StringBuilder();
sb.append("<a href=\"").append(Util.docRoot("secure/details/job.jsp?id="));
sb.append(job.getId());
sb.append("\" target=\"_blank\">");
sb.append(job.getName());
RESTHelpers.addImg(sb);
sb.append(hiddenJobId);
String jobLink = sb.toString();
final String status = job.getStatus();
if (dataAsObjects) {
dataTablePageEntries.add(getEntryAsObject(jobLink, status, job));
} else {
dataTablePageEntries.add(getEntryAsArray(jobLink, status, job));
}
}
return createPageDataJsonObject(query, dataTablePageEntries);
}
/**
* Convert a List of Job into a detailed JsonArray
*
* @param jobs The jobs that will be the rows of the table
* @return A JsonObject that can be used to populate a datatable
*/
public static JsonArray convertJobsToJsonArray(List<Job> jobs) {
final Map<Integer, JsonObject> users = new HashMap<>();
final JsonArray out = new JsonArray();
for (Job job : jobs) {
final JsonObject j = new JsonObject();
j.addProperty("name", job.getName());
j.addProperty("id", job.getId());
j.addProperty("status", job.getStatus());
j.addProperty("created", job.getCreateTime().getTime());
j.addProperty("totalPairs", job.getLiteJobPairStats().get("totalPairs"));
j.addProperty("pendingPairs", job.getLiteJobPairStats().get("pendingPairs"));
final int userId = job.getUserId();
if (!users.containsKey(userId)) {
final JsonObject o = new JsonObject();
final User jobUser = Users.get(userId);
o.addProperty("name", jobUser.getFullName());
o.addProperty("id", jobUser.getId());
users.put(userId, o);
}
j.add("user", users.get(userId));
try {
final JsonObject queue = new JsonObject();
queue.addProperty("name", job.getQueue().getName());
queue.addProperty("id", job.getQueue().getId());
j.add("queue", queue);
} catch (NullPointerException e) {
// Not all jobs have queues
}
out.add(j);
}
return out;
}
private static JsonArray getEntryAsArray(String jobLink, String status, Job job) {
// Create an object, and inject the above HTML, to represent an
// entry in the DataTable
JsonArray entry = new JsonArray();
entry.add(new JsonPrimitive(jobLink));
entry.add(new JsonPrimitive(status));
entry.add(new JsonPrimitive(getPercentStatHtml("asc", job.getLiteJobPairStats().get("completionPercentage"), true)));
entry.add(new JsonPrimitive(getPercentStatHtml("static", job.getLiteJobPairStats().get("totalPairs"), false)));
entry.add(new JsonPrimitive(getPercentStatHtml("desc", job.getLiteJobPairStats().get("errorPercentage"), true)));
entry.add(new JsonPrimitive(job.getCreateTime().toString()));
entry.add(new JsonPrimitive(Util.byteCountToDisplaySize(job.getDiskSize())));
return entry;
}
private static JsonObject getEntryAsObject(String jobLink, String status, Job job) {
// Create an object, and inject the above HTML, to represent an
// entry in the DataTable
JsonObject entry = new JsonObject();
entry.add("jobLink", new JsonPrimitive(jobLink));
entry.add("status", new JsonPrimitive(status));
entry.add("completion", new JsonPrimitive(getPercentStatHtml("asc", job.getLiteJobPairStats().get("completionPercentage"), true)));
entry.add("totalPairs", new JsonPrimitive(getPercentStatHtml("static", job.getLiteJobPairStats().get("totalPairs"), false)));
entry.add("errorPercentage", new JsonPrimitive(getPercentStatHtml("desc", job.getLiteJobPairStats().get("errorPercentage"), true)));
entry.add("createTime", new JsonPrimitive(job.getCreateTime().toString()));
JsonObject diskSize = new JsonObject();
diskSize.add("display", new JsonPrimitive(Util.byteCountToDisplaySize(job.getDiskSize())));
diskSize.add("bytes", new JsonPrimitive(job.getDiskSize()));
entry.add("diskSize", diskSize);
return entry;
}
/**
* Generate the HTML for the next DataTable page of entries
* Given a list of users, creates a JsonObject that can be used to populate
* a datatable client-side
*
* @param users The users that will be the rows of the table
* @param query a DataTablesQuery object
* @param currentUserId the ID of the user making the request for this datatable
* @return A JsonObject that can be used to populate a datatable
* @author Eric Burns
*/
public static JsonObject convertUsersToJsonObject(List<User> users, DataTablesQuery query, int currentUserId) {
/*
Generate the HTML for the next DataTable page of entries
*/
JsonArray dataTablePageEntries = new JsonArray();
for (User user : users) {
String userLink = getUserLink(user.getId(), user.getFullName(), currentUserId);
StringBuilder sb = new StringBuilder();
sb.append("<a href=\"mailto:");
sb.append(user.getEmail());
sb.append("\">");
sb.append(user.getEmail());
RESTHelpers.addImg(sb);
String emailLink = sb.toString();
sb = new StringBuilder();
sb.append("<input type=\"button\" onclick=\"editPermissions(").append(user.getId())
.append(")\" value=\"Edit\"/>");
String permissionButton = sb.toString();
// Create an object, and inject the above HTML, to represent an
// entry in the DataTable
JsonArray entry = new JsonArray();
entry.add(new JsonPrimitive(userLink));
entry.add(new JsonPrimitive(user.getInstitution()));
entry.add(new JsonPrimitive(emailLink));
entry.add(new JsonPrimitive(permissionButton));
String suspendButton = "";
if (Users.isAdmin(user.getId()) || Users.isUnauthorized(user.getId())) {
suspendButton = "N/A";
} else if (Users.isSuspended(user.getId())) {
sb = new StringBuilder();
sb.append("<input type=\"button\" onclick=\"reinstateUser(").append(user.getId())
.append(")\" value=\"Reinstate\"/>");
suspendButton = sb.toString();
} else if (Users.isNormalUser(user.getId())) {
sb = new StringBuilder();
sb.append("<input type=\"button\" onclick=\"suspendUser(").append(user.getId())
.append(")\" value=\"Suspend\"/>");
suspendButton = sb.toString();
}
entry.add(new JsonPrimitive(suspendButton));
String subscribeButton = "";
if (Users.isUnauthorized(user.getId())) {
subscribeButton = "N/A";
} else if (user.isSubscribedToReports()) {
subscribeButton = "<input type=\"button\" onclick=\"unsubscribeUserFromReports(" + user.getId() + ")\" value=\"Unsubscribe\"/>";
} else {
subscribeButton = "<input type=\"button\" onclick=\"subscribeUserToReports(" + user.getId() + ")\" value=\"Subscribe\"/>";
}
entry.add(new JsonPrimitive(subscribeButton));
String developerButton = "";
if (Users.isAdmin(user.getId()) || Users.isUnauthorized(user.getId()) || Users.isSuspended(user.getId())) {
developerButton = "N/A";
} else if (Users.isDeveloper(user.getId())) {
developerButton = "<input type=\"button\" onclick=\"suspendDeveloperStatus(" + user.getId() + ")\"value=\"Suspend\"/>";
} else {
developerButton = "<input type=\"button\" onclick=\"grantDeveloperStatus(" + user.getId() + ")\"value=\"Grant\"/>";
}
entry.add(new JsonPrimitive(developerButton));
dataTablePageEntries.add(entry);
}
return createPageDataJsonObject(query, dataTablePageEntries);
}
/**
* Generate the HTML for the next DataTable page of entries
* Given a list of TestSequences, creates a JsonObject that can be used to populate
* a datatable client-side
*
* @param tests The tests that will be the rows of the table
* @param query a DataTablesQuery object
* @return A JsonObject that can be used to populate a datatable
* @author Eric Burns
*/
public static JsonObject convertTestSequencesToJsonObject(List<TestSequence> tests, DataTablesQuery query) {
/*
Generate the HTML for the next DataTable page of entries
*/
JsonArray dataTablePageEntries = new JsonArray();
for (TestSequence test : tests) {
// Create an object, and inject the above HTML, to represent an
// entry in the DataTable
JsonArray entry = new JsonArray();
StringBuilder sb = new StringBuilder();
sb.append("<a name=\"").append(test.getName()).append("\" href=\"")
.append(Util.docRoot("secure/admin/testResults.jsp?sequenceName="));
sb.append(test.getName());
sb.append("\" target=\"_blank\">");
sb.append(test.getName());
RESTHelpers.addImg(sb);
entry.add(new JsonPrimitive(sb.toString()));
entry.add(new JsonPrimitive(test.getTestCount()));
entry.add(new JsonPrimitive(test.getTestsPassed()));
entry.add(new JsonPrimitive(test.getTestsFailed()));
entry.add(new JsonPrimitive(test.getStatus().getStatus()));
entry.add(new JsonPrimitive(test.getErrorTrace()));
dataTablePageEntries.add(entry);
}
return createPageDataJsonObject(query, dataTablePageEntries);
}
/**
* Generate the HTML for the next DataTable page of entries
* Given a HashMap mapping the names of tests to messages, creates a JsonObject that can be used to populate
* a datatable client-side
*
* @param tests A HashMap of tests, where each test will be a row of a table
* @param query A DataTablesQuery object
* @return A JsonObject that can be used to populate a datatable
* @author Eric Burns
*/
public static JsonObject convertTestResultsToJsonObject(List<TestResult> tests, DataTablesQuery query) {
/*
Generate the HTML for the next DataTable page of entries
*/
JsonArray dataTablePageEntries = new JsonArray();
for (TestResult test : tests) {
// Create an object, and inject the above HTML, to represent an
// entry in the DataTable
JsonArray entry = new JsonArray();
entry.add(new JsonPrimitive(test.getName()));
entry.add(new JsonPrimitive(test.getStatus().getStatus()));
//replacing newlines with HTML line breaks
entry.add(new JsonPrimitive(test.getAllMessages().replace("\n", "<br/>")));
entry.add(new JsonPrimitive(test.getErrorTrace()));
entry.add(new JsonPrimitive(test.getTime()));
dataTablePageEntries.add(entry);
}
return createPageDataJsonObject(query, dataTablePageEntries);
}
/**
* Given a list of spaces, creates a JsonObject that can be used to populate
* a datatable client-side
*
* @param spaces The spaces that will be the rows of the table
* @param query a DataTablesQuery object
* @return A JsonObject that can be used to populate a datatable
* @author Eric Burns
*/
public static JsonObject convertSpacesToJsonObject(List<Space> spaces, DataTablesQuery query) {
/*
Generate the HTML for the next DataTable page of entries
*/
JsonArray dataTablePageEntries = new JsonArray();
for (Space space : spaces) {
String spaceLink = getSpaceLink(space);
// Create an object, and inject the above HTML, to represent an
// entry in the DataTable
JsonArray entry = new JsonArray();
entry.add(new JsonPrimitive(spaceLink));
entry.add(new JsonPrimitive(space.getDescription()));
dataTablePageEntries.add(entry);
}
return createPageDataJsonObject(query, dataTablePageEntries);
}
/**
* Given a list of solvers, creates a JsonObject that can be used to
* populate a datatable client-side
*
* @param solvers The solvers that will be the rows of the table
* @param query DataTablesQuery object
* @return A JsonObject that can be used to populate a datatable
* @author Eric Burns
*/
public static JsonObject convertSolversToJsonObject(List<Solver> solvers, DataTablesQuery query) {
/*
Generate the HTML for the next DataTable page of entries
*/
JsonArray dataTablePageEntries = new JsonArray();
for (Solver solver : solvers) {
StringBuilder sb = new StringBuilder();
// Create the hidden input tag containing the solver id
sb.append("<input type=\"hidden\" value=\"");
sb.append(solver.getId());
sb.append("\" prim=\"solver\" userId=\"").append(solver.getUserId()).append("\" deleted=\"")
.append(solver.isDeleted()).append("\" recycled=\"").append(solver.isRecycled()).append("\"/>");
String hiddenSolverId = sb.toString();
// Create the solver "details" link and append the hidden input
// element
sb = new StringBuilder();
sb.append(getSolverLink(solver.getId(), solver.getName(), PrimitivesToAnonymize.NONE));
sb.append(hiddenSolverId);
String solverLink = sb.toString();
// Create an object, and inject the above HTML, to represent an
// entry in the DataTable
JsonArray entry = new JsonArray();
entry.add(new JsonPrimitive(solverLink));
entry.add(new JsonPrimitive(solver.getDescription()));
entry.add(new JsonPrimitive(solver.getType().toString().toLowerCase()));
dataTablePageEntries.add(entry);
}
return createPageDataJsonObject(query, dataTablePageEntries);
}
/*given a list of the current page of benchmark uploads for some user, convert this to a json object
* @param uploads List of the uploads
* @param query Data about the query
* Documentation by @aguo2
* @author unknown
*/
public static JsonObject convertUploadsToJsonObject(List<BenchmarkUploadStatus> uploads, DataTablesQuery query) {
JsonArray dataTablePageEntries = new JsonArray();
for (BenchmarkUploadStatus upload: uploads) {
StringBuilder sb = new StringBuilder();
sb.append("<input type=\"hidden\" value =\"");
sb.append(upload.getId());
sb.append("\" prim=\"upload\" userId=\"").append(upload.getUserId()).append("\"/>");
String hiddenUploadId = sb.toString();
sb = new StringBuilder();
sb.append("<a href =\"").append(Util.docRoot("secure/details/uploadStatus.jsp?id="));
sb.append(upload.getId());
sb.append("\" target=\"_blank\">");
sb.append(upload.getUploadDate().toString());
RESTHelpers.addImg(sb);
sb.append(hiddenUploadId);
String uploadLink = sb.toString();
JsonArray entry = new JsonArray();
entry.add(new JsonPrimitive(uploadLink));
entry.add(new JsonPrimitive(upload.getTotalBenchmarks()));
entry.add(new JsonPrimitive(upload.isEverythingComplete()));
dataTablePageEntries.add(entry);
}
JsonObject entries = createPageDataJsonObject(query, dataTablePageEntries);
return entries;
}
/**
* Given a list of benchmarks, creates a JsonObject that can be used to
* populate a datatable client-side
*
* @param benchmarks The benchmarks that will be the rows of the table
* @param query a DataTablesQuery object
* @return A JsonObject that can be used to populate a datatable
* @author Eric Burns
*/
public static JsonObject convertBenchmarksToJsonObject(List<Benchmark> benchmarks, DataTablesQuery query) {
/*
Generate the HTML for the next DataTable page of entries
*/
JsonArray dataTablePageEntries = new JsonArray();
for (Benchmark bench : benchmarks) {
String benchLink = getBenchLink(bench);
// Create the benchmark type tag
// Set the tooltip to be the benchmark type's description
String typeSpan =
"<span title=\"" + bench.getType().getDescription() + "\">" + bench.getType().getName() + "</span>";
// Create an object, and inject the above HTML, to represent an
// entry in the DataTable
JsonArray entry = new JsonArray();
entry.add(new JsonPrimitive(benchLink));
entry.add(new JsonPrimitive(typeSpan));
dataTablePageEntries.add(entry);
}
return createPageDataJsonObject(query, dataTablePageEntries);
}
private static StringBuilder getPairsInSpaceLink(String type, int spaceId, int configId, int stageNumber) {
StringBuilder sb = new StringBuilder();
sb.append("<a href=\"").append(Util.docRoot(
"secure/details/pairsInSpace.jsp?type=" + type + "&sid=" + spaceId + "&configid=" + configId +
"&stagenum=" + stageNumber));
sb.append("\" target=\"_blank\" >");
return sb;
}
/**
* Given a list of SolverStats, creates a JsonObject that can be used to
* populate a datatable client-side.
* In any other case, this should produce objects with named fields.
* However, this particular API can produce output with many thousands of
* rows of output. Naming each field would more than triple the size of the
* file. In order to keep the size of the output manageable, we are simply
* returning an array. This makes this API particularly fragile, and the
* server-side and client-side must be kept in sync!
*
* @param stats The SolverStats that will be the rows of the table
* @param query a DataTablesQuery object
* @param shortFormat Whether to include all fields (false) or only fields for the subspace overview (true)
* @param wallTime Whether to use wallclock times (true) or cpu times (false).
* @param primitivesToAnonymize a PrimitivesToAnonymize enum describing if the solver stats should be anonymized.
* @return A JsonObject that can be used to populate a datatable
* @author Eric Burns+
* @author Pat Hawks
*/
public static JsonObject convertSolverStatsToJsonObject(Collection<SolverStats> stats, DataTablesQuery query, int spaceId, int jobId, boolean shortFormat, boolean wallTime, PrimitivesToAnonymize primitivesToAnonymize) {
JsonArray dataTablePageEntries = new JsonArray();
for (SolverStats js : stats) {
JsonArray entries = new JsonArray();
entries.add(js.getSolver().getId());
entries.add(js.getConfiguration().getId());
entries.add(js.getSolver().getName());
entries.add(js.getConfiguration().getName());
entries.add(js.getCorrectOverCompleted());
if (wallTime) {
entries.add(Math.round(js.getWallTime() * 100));
} else {
entries.add(Math.round(js.getCpuTime() * 100));
}
if (!shortFormat) {
entries.add(js.getStageNumber());
entries.add(js.getIncorrectJobPairs());
entries.add(js.getResourceOutJobPairs());
entries.add(js.getFailedJobPairs());
entries.add(js.getUnknown());
entries.add(js.getIncompleteJobPairs());
if (AnonymousLinks.isNothingAnonymized(primitivesToAnonymize)) {
entries.add(js.getConflicts());
} else {
// Don't support conflicts for anonymized pages.
entries.add("N/A");
}
}
// add index 13, CONFIG_DELETED, for dynamic config link; see getSolverTableInitializer() in job.js
entries.add( js.getConfigDeleted() );
// debug for queuegraph
log.info( "\n\nin convertSolverStatsToJsonObject(); " +
"CONFIG_DELETED = " + js.getConfigDeleted() + "\n" );
dataTablePageEntries.add(entries);
}
return createPageDataJsonObject(query, dataTablePageEntries);
}
private static String getPairsInSpaceHtml(int spaceId, int configId, String linkText) {
StringBuilder sb = getPairsInSpaceLink("all", spaceId, configId, 1);
sb.append(linkText);
RESTHelpers.addImg(sb);
return sb.toString();
}
public static Map<Integer, String> getJobSpaceIdToSolverStatsJsonMap(List<JobSpace> jobSpaces, int stageNumber, boolean wallclock, Boolean includeUnknown) {
Map<Integer, String> jobSpaceIdToSolverStatsJsonMap = new HashMap<>();
for (JobSpace jobSpace : jobSpaces) {
Collection<SolverStats> stats = Jobs.getAllJobStatsInJobSpaceHierarchyIncludeDeletedConfigs(jobSpace, stageNumber, PrimitivesToAnonymize.NONE, includeUnknown);
DataTablesQuery query = new DataTablesQuery();
query.setTotalRecords(stats.size());
query.setTotalRecordsAfterQuery(stats.size());
query.setSyncValue(1);
JsonObject solverStatsJson = RESTHelpers.convertSolverStatsToJsonObject(stats, query, jobSpace.getId(), jobSpace.getJobId(), false, wallclock, PrimitivesToAnonymize.NONE);
if (solverStatsJson != null) {
jobSpaceIdToSolverStatsJsonMap.put(jobSpace.getId(), gson.toJson(solverStatsJson));
}
}
return jobSpaceIdToSolverStatsJsonMap;
}
public static Map<Integer, String> getJobSpaceIdToSubspaceJsonMap(int jobId, List<JobSpace> jobSpaces) {
Map<Integer, String> jobSpaceIdToSubspaceJsonMap = new HashMap<>();
for (JobSpace jobSpace : jobSpaces) {
String subspaceJson = RESTHelpers.getJobSpacesJson(jobSpace.getId(), jobId, false);
jobSpaceIdToSubspaceJsonMap.put(jobSpace.getId(), subspaceJson);
}
return jobSpaceIdToSubspaceJsonMap;
}
/**
* Gets a JSON representation of a job space tree
*
* @param jobId
* @param userId
* @return
*/
public static String getJobSpacesTreeJson(int jobId, int userId) {
ValidatorStatusCode status = JobSecurity.canUserSeeJob(jobId, userId);
if (!status.isSuccess()) {
String output = gson.toJson(status);
log.debug("User cannot see job, getJobSpacesJson output: " + output);
return output;
}
List<JSTreeItem> subspaces = new ArrayList<>();
buildFullJsTree(jobId, subspaces);
return gson.toJson(subspaces);
}
/**
* Builds the entire JS tree for a jobspace rather than just a single level.
* This method is needed for the local job page since we can't send GET requests
* for single levels.
*
* @author Albert Giegerich
*/
private static void buildFullJsTree(int jobId, List<JSTreeItem> root) {
buildFullJsTreeHelper(0, jobId, root, true);
}
private static List<JobSpace> getSubspacesOrRootSpace(int parentId, int jobId) {
List<JobSpace> subspaces = new ArrayList<>();
if (parentId > 0) {
subspaces = Spaces.getSubSpacesForJob(parentId, false);
} else {
//if the id given is 0, we want to get the root space
Job j = Jobs.get(jobId);
JobSpace s = Spaces.getJobSpace(j.getPrimarySpace());
subspaces.add(s);
}
return subspaces;
}
/**
* Helper method for buildFullJsTree
*
* @see org.starexec.app.RESTHelpers#buildFullJsTree
*/
private static void buildFullJsTreeHelper(int parentId, int jobId, List<JSTreeItem> root, boolean firstRecursion) {
List<JobSpace> subspaces = getSubspacesOrRootSpace(parentId, jobId);
String className = (firstRecursion ? "rootNode" : null);
for (JobSpace js : subspaces) {
JSTreeItem node = null;
if (Spaces.getCountInJobSpace(js.getId()) > 0) {
node = new JSTreeItem(js.getName(), js.getId(), "closed", R.SPACE, js.getMaxStages(), className);
} else {
node = new JSTreeItem(js.getName(), js.getId(), "leaf", R.SPACE, js.getMaxStages(), className);
}
root.add(node);
buildFullJsTreeHelper(js.getId(), jobId, node.getChildren(), false);
}
}
public static String validateAndGetJobSpacesJson(int parentId, int jobId, boolean makeSpaceTree, int userId) {
log.debug("got here with jobId= " + jobId + " and parent space id = " + parentId);
log.debug("getting job spaces for panels");
//don't populate the subspaces if the user can't see the job
ValidatorStatusCode status = JobSecurity.canUserSeeJob(jobId, userId);
if (!status.isSuccess()) {
String output = gson.toJson(status);
log.debug("User cannot see job, getJobSpacesJson output: " + output);
return output;
}
return getJobSpacesJson(parentId, jobId, makeSpaceTree);
}
protected static String getSolverComparisonGraphJson(int jobSpaceId, int config1, int config2, int edgeLengthInPixels, String axisColor, int stageNumber, PrimitivesToAnonymize primitivesToAnonymize) {
List<String> chartPath = null;
Color c = Util.getColorFromString(axisColor);
if (c == null) {
return gson.toJson(new ValidatorStatusCode(false, "The given color is not valid"));
}
if (edgeLengthInPixels <= 0 || edgeLengthInPixels > 2000) {
return gson.toJson(new ValidatorStatusCode(false, "The given size is not valid: please choose an integer from 1-2000"));
}
chartPath = Statistics.makeSolverComparisonChart(config1, config2, jobSpaceId, edgeLengthInPixels, c, stageNumber, primitivesToAnonymize);
if (chartPath == null) {
return gson.toJson(RESTServices.ERROR_DATABASE);
}
if (chartPath.get(0).equals(Statistics.OVERSIZED_GRAPH_ERROR)) {
return gson.toJson(RESTServices.ERROR_TOO_MANY_JOB_PAIRS);
}
JsonObject json = new JsonObject();
json.addProperty("src", chartPath.get(0));
json.addProperty("map", chartPath.get(1));
return gson.toJson(json);
}
protected static String getJobSpacesJson(int parentId, int jobId, boolean makeSpaceTree) {
return getJobSpacesJson(parentId, jobId, makeSpaceTree, PrimitivesToAnonymize.NONE);
}
protected static String getJobSpacesJson(int parentId, int jobId, boolean makeSpaceTree, PrimitivesToAnonymize primitivesToAnonymize) {
log.debug("got a request for parent space = " + parentId);
List<JobSpace> subspaces = getSubspacesOrRootSpace(parentId, jobId);
if (AnonymousLinks.areJobsAnonymized(primitivesToAnonymize)) {
anonymizeJobSpaceNames(subspaces, jobId);
}
log.debug("making next tree layer with " + subspaces.size() + " spaces");
if (makeSpaceTree) {
String output = gson.toJson(RESTHelpers.toJobSpaceTree(subspaces));
log.debug("makeSpaceTree is true, getJobSpacesJson output: " + output);
return output;
} else {
String output = gson.toJson(subspaces);
log.debug("makeSpaceTree is false, getJobSpacesJson output: " + output);
return output;
}
}
protected static void anonymizeJobSpaceNames(List<JobSpace> jobSpaces, int jobId) {
final String methodName = "anonymizeJobSpaceNames";
log.entry(methodName);
Map<Integer, String> jobSpaceNames = AnonymousLinks.getAnonymizedJobSpaceNames(jobId);
for (JobSpace space : jobSpaces) {
space.setName(jobSpaceNames.get(space.getId()));
}
}
public static JsonObject convertCommunityRequestsToJsonObject(List<CommunityRequest> requests, DataTablesQuery query, int currentUserId) {
/*
Generate the HTML for the next DataTable page of entries
*/
JsonArray dataTablePageEntries = new JsonArray();
for (CommunityRequest req : requests) {
User user = Users.get(req.getUserId());
String userLink = getUserLink(user.getId(), user.getFullName(), currentUserId);
//Community/space
String spaceLink = getSpaceLink(Spaces.get(req.getCommunityId()));
StringBuilder sb = new StringBuilder();
sb.append("<input class=\"acceptRequestButton\" type=\"button\" data-code=\"").append(req.getCode())
.append("\" value=\"Approve\" />");
String approveButton = sb.toString();
sb = new StringBuilder();
sb.append("<input type=\"button\" class=\"declineRequestButton\"" + "data-code=\"").append(req.getCode())
.append("\" value=\"Decline\"/>");
String declineButton = sb.toString();
// Create an object, and inject the above HTML, to represent an
// entry in the DataTable
JsonArray entry = new JsonArray();
entry.add(new JsonPrimitive(userLink));
entry.add(new JsonPrimitive(spaceLink));
entry.add(new JsonPrimitive(req.getMessage()));
entry.add(new JsonPrimitive(approveButton));
entry.add(new JsonPrimitive(declineButton));
dataTablePageEntries.add(entry);
}
return createPageDataJsonObject(query, dataTablePageEntries);
}
/*
* Given an JSONArray of the next page and the query,
* return a JsonObject of the elements displayed in the front end table
* @author PressDodd
* @docs aguo2
*/
private static JsonObject createPageDataJsonObject(DataTablesQuery query, JsonArray entries) {
JsonObject nextPage = new JsonObject();
// Build the actual JSON response object and populated it with the
// created data
nextPage.addProperty(SYNC_VALUE, query.getSyncValue());
nextPage.addProperty(TOTAL_RECORDS, query.getTotalRecords());
nextPage.addProperty(TOTAL_RECORDS_AFTER_QUERY, query.getTotalRecordsAfterQuery());
nextPage.add("aaData", entries);
// Return the next DataTable page
return nextPage;
}
/**
* Gets all pending community requests for a given community.
*
* @param httpRequest The http request.
* @param communityId The community to get pending requests for.
* @return the new json object or null on error.
* @author Albert Giegerich
*/
public static JsonObject getNextDataTablesPageForPendingCommunityRequestsForCommunity(HttpServletRequest httpRequest, int communityId) {
// Parameter Validation
DataTablesQuery query = RESTHelpers.getAttrMap(Primitive.SPACE, httpRequest);
if (query == null) {
return null;
}
List<CommunityRequest> requests = null;
try {
requests = Requests.getPendingCommunityRequestsForCommunity(query, communityId);
query.setTotalRecords(Requests.getCommunityRequestCountForCommunity(communityId));
query.setTotalRecordsAfterQuery(query.getTotalRecords());
} catch (StarExecDatabaseException e) {
log.error("Could not successfully get community requests for community with id=" + communityId, e);
return null;
}
return setupAttrMapAndConvertRequestsToJson(requests, query, httpRequest);
}
/**
* Gets all pending community requests.
*
* @param httpRequest The http request.
* @return a JsonObject representing the requests.
* @author Albert Giegerich
*/
public static JsonObject getNextDataTablesPageForPendingCommunityRequests(HttpServletRequest httpRequest) {
// Parameter Validation
DataTablesQuery query = RESTHelpers.getAttrMap(Primitive.SPACE, httpRequest);
if (query == null) {
return null;
}
List<CommunityRequest> requests = null;
try {
requests = Requests.getPendingCommunityRequests(query);
query.setTotalRecords(Requests.getCommunityRequestCount());
query.setTotalRecordsAfterQuery(query.getTotalRecords());
} catch (StarExecDatabaseException e) {
log.error("Could not successfully get community requests for all communities.", e);
return null;
}
return setupAttrMapAndConvertRequestsToJson(requests, query, httpRequest);
}
/**
* Provides an abstraction so the same code can be used when we want to get all pending community requests or
* just requests for a given community.
*
* @param httpRequest The http request.
* @author Unknown, Albert Giegerich
*/
private static JsonObject setupAttrMapAndConvertRequestsToJson(List<CommunityRequest> requests, DataTablesQuery query, HttpServletRequest httpRequest) {
// If no search is provided, TOTAL_RECORDS_AFTER_QUERY = TOTAL_RECORDS
if (!query.hasSearchQuery()) {
query.setTotalRecordsAfterQuery(query.getTotalRecords());
}
// Otherwise, TOTAL_RECORDS_AFTER_QUERY < TOTAL_RECORDS
else {
query.setTotalRecordsAfterQuery(requests.size());
}
int currentUserId = SessionUtil.getUserId(httpRequest);
return convertCommunityRequestsToJsonObject(requests, query, currentUserId);
}
private static Map<String, Triple<Integer, Double, Double>> initializeAttrCounts(List<String> headers) {
Map<String, Triple<Integer, Double, Double>> attrCounts = new HashMap<>();
for (String header : headers) {
attrCounts.put(header, new ImmutableTriple<>(0, 0.0, 0.0));
}
return attrCounts;
}
/**
* Creates a map from a solver-config pair to a map from an attribute to the count of attributes (results) generated
* by that solver-config as well as the time it took to create all those results.
*
* @param jobSpaceId the jobspace to generate the map for, only job pairs in this jobspace will be examined.
* @throws SQLException if there is a database issue.
*/
private static Map<SolverConfig, Map<String, Triple<Integer, Double, Double>>> getSolverConfigToAttrCountMap(int jobSpaceId) throws SQLException {
Map<SolverConfig, Map<String, Triple<Integer, Double, Double>>> solverConfigToAttrCount = new HashMap<>();
List<AttributesTableData> jobAttributes = Jobs.getJobAttributesTable(jobSpaceId);
List<String> uniqueResultValues = Jobs.getJobAttributeValues(jobSpaceId);
for (AttributesTableData tableEntry : jobAttributes) {
// Initialize a solverConfig to be used as a key in our map.
SolverConfig solverConfig = new SolverConfig(tableEntry.solverId, tableEntry.configId);
// Add this optional data so we can populate the table with it later.
solverConfig.solverName = tableEntry.solverName;
solverConfig.configName = tableEntry.configName;
// Initialize new entries in the map with a 0 count for each attribute.
if (!solverConfigToAttrCount.containsKey(solverConfig)) {
Map<String, Triple<Integer, Double, Double>> zeroAttrCounts = initializeAttrCounts(uniqueResultValues);
solverConfigToAttrCount.put(solverConfig, zeroAttrCounts);
}
// Populate the map with the count and times in the table entry.
solverConfigToAttrCount.get(solverConfig).put(tableEntry.attrValue, new ImmutableTriple<>(tableEntry.attrCount, tableEntry.wallclockSum, tableEntry.cpuSum));
}
return solverConfigToAttrCount;
}
/**
* Creates the attribute table for details/jobAttributes as a list.
*
* @see #getSolverConfigToAttrCountMap(int)
*/
public static List<AttributesTableRow> getAttributesTable(int jobSpaceId) throws SQLException {
Map<SolverConfig, Map<String, Triple<Integer, Double, Double>>> solverConfigToAttrCount = getSolverConfigToAttrCountMap(jobSpaceId);
List<AttributesTableRow> table = new ArrayList<>();
for (SolverConfig solverConfig : solverConfigToAttrCount.keySet()) {
AttributesTableRow row = new AttributesTableRow();
row.solverId = solverConfig.solverId;
row.configId = solverConfig.configId;
row.solverName = solverConfig.solverName;
row.configName = solverConfig.configName;
// Add all the attr_value counts under the appropriate headers. To do this we sort the list of headers.
// The headers will need to be sorted in the same way so the columns line up.
Map<String, Triple<Integer, Double, Double>> valueCounts = solverConfigToAttrCount.get(solverConfig);
List<String> attrValues = new ArrayList<>(valueCounts.keySet()).stream().sorted().collect(Collectors.toList());
for (String attrValue : attrValues) {
Triple<Integer, Double, Double> countWallclockCpu = valueCounts.get(attrValue);
Triple<Integer, String, String> formattedCountWallclockCpu = new ImmutableTriple<>(countWallclockCpu.getLeft(), String.format("%.4f", countWallclockCpu.getMiddle()), String.format("%.4f", countWallclockCpu.getRight()));
row.countAndTimes.add(formattedCountWallclockCpu);
}
table.add(row);
}
return table;
}
protected static String getWallclockCpuAttributeTableHtml(Double wallclockSum, Double cpuSum) {
String formatter = "%.3f";
String formattedWallclock = String.format(formatter, wallclockSum);
String formattedCpu = String.format(formatter, cpuSum);
return "<span class='wallclockSum'>" + formattedWallclock + "</span>" + "<span class='cpuSum hidden'>" + formattedCpu + "</span>";
}
public static boolean freezePrimitives() throws SQLException {
return Common.query(
"{CALL GetFreezePrimitives()}",
procedure -> {},
results -> {
results.next();
return results.getBoolean("freeze_primitives");
}
);
}
public static void setReadOnly(boolean readOnly) throws SQLException{
log.debug(
readOnly ? "READ ONLY IS ENABLED, no new jobs can be ran"
: "READ ONLY IS DISABLED, jobs can be ran normally"
);
Common.update(
"{CALL SetReadOnly(?)}",
procedure -> {
procedure.setBoolean(1, readOnly);
});
}
public static boolean getReadOnly() throws SQLException {
return Common.query(
"{CALL GetReadOnly()}",
procedure -> {},
results -> {
results.next();
return results.getBoolean("read_only");
}
);
}
public static void setFreezePrimitives(boolean frozen) throws SQLException {
log.info("setFreezePrimitives",
frozen
? "!!! Freezing Primitives !!!\n\tUploading Benchmarks and Solvers will be disabled"
: "!!! Unfreezing Primitives !!!\n\tUploading Benchmarks and Solvers will be allowed"
);
Common.update(
"{CALL SetFreezePrimitives(?)}",
procedure -> {
procedure.setBoolean(1, frozen);
}
);
}
/**
* Represents a node in jsTree tree with certain attributes used for
* displaying the node and obtaining information about the node.
*
* @author Tyler Jensen
*/
@SuppressWarnings("unused")
protected static class JSTreeItem {
private String data;
private JSTreeAttribute attr;
private List<JSTreeItem> children;
private String state;
public JSTreeItem(String name, int id, String state, String type) {
this(name, id, state, type, 0, null);
}
public JSTreeItem(String name, int id, String state, String type, int maxStages) {
this(name, id, state, type, maxStages, null);
}
public JSTreeItem(String name, int id, String state, String type, int maxStages, String cLass) {
this.data = name;
this.attr = new JSTreeAttribute(id, type, maxStages, cLass);
this.state = state;
this.children = new LinkedList<>();
}
public List<JSTreeItem> getChildren() {
return children;
}
public void addChild(JSTreeItem child) {
children.add(child);
}
}
/**
* An attribute of a jsTree node which holds the node's id so that it can be
* passed to other ajax methods.
*
* @author Tyler Jensen
*/
@SuppressWarnings("unused")
protected static class JSTreeAttribute {
private int id;
private String rel;
private boolean global;
private int defaultQueueId;
private int maxStages;
// called cLass to bypass Java's class keyword. gson will lowercase the L
private String cLass;
public JSTreeAttribute(int id, String type, int maxStages, String cLass) {
this.id = id;
this.rel = type;
this.maxStages = maxStages;
this.cLass = cLass;
if (type.equals("active_queue") || type.equals("inactive_queue")) {
this.global = Queues.isQueueGlobal(id);
}
this.defaultQueueId = R.DEFAULT_QUEUE_ID;
}
}
/**
* Represents a space and a user's permission for that space. This is purely
* a helper class so we can easily read the information via javascript on
* the client.
*
* @author Tyler Jensen & Todd Elvers
*/
protected static class SpacePermPair {
@Expose
private final Space space;
@Expose
private final Permission perm;
public SpacePermPair(Space s, Permission p) {
this.space = s;
this.perm = p;
}
}
/**
* Represents community details including the requesting user's permissions
* for the community aint with the community's leaders. Permissions are used
* so the client side can determine what actions a user can take on the
* community
*
* @author Tyler Jensen
*/
protected static class CommunityDetails {
@Expose
private final Space space;
@Expose
private final Permission perm;
@Expose
private final List<User> leaders;
@Expose
private final List<Website> websites;
@Expose
private final Boolean isMember;
public CommunityDetails(Space s, Permission p, List<User> leaders, List<Website> websites, Boolean member) {
this.space = s;
this.perm = p;
this.leaders = leaders;
this.websites = websites;
this.isMember = member;
}
}
/**
* Represents permission details for a given space and user
*
* @author Wyatt Kaiser
*/
protected static class PermissionDetails {
@Expose
private final Permission perm;
@Expose
private final Space space;
@Expose
private final User user;
@Expose
private final User requester;
@Expose
private final boolean isCommunity;
public PermissionDetails(Permission p, Space s, User u, User r, boolean c) {
this.perm = p;
this.space = s;
this.user = u;
this.requester = r;
this.isCommunity = c;
}
}
}
| [
"noreply@github.com"
] | StarExec.noreply@github.com |
4cce322b9dbe18f9693064cd75a9231065c0af81 | d6729cd1c8f49c9bfd6ff328fbbac7c4ae00f78e | /src/Solution/SolutionLinkedList.java | 48dfb7d816fa508c612496f43c6bf207d73130da | [] | no_license | ChasingLight/JadenLeetCode | 850aa555c6a4d3ea52698cbed3d6b72169917cc6 | 66ccb2bb54880c983ebfa683811d8d48074a8f84 | refs/heads/master | 2021-09-09T09:57:01.939264 | 2018-03-15T00:21:19 | 2018-03-15T00:21:19 | 112,918,148 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,475 | java | package Solution;
import LinkedListUtil.ListNode;
public class SolutionLinkedList {
/**
* 删除链表中的一个节点(除了尾节点)
*
* 特殊点:give only access to that node.
* @param node
*/
public void deleteNode(ListNode node){
node.val = node.next.val;
node.next = node.next.next;
}
/**
* 倒转链表(最简约的方式) 涵盖了空链表和一个节点的情况
* @param head
* @return
*/
public static ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode nxt;
while(head != null){
nxt = head.next;
head.next = pre;
pre = head;
head = nxt;
}
return pre;
}
/**
* 倒转链表---递归实现方式
* @param head
* @return
*/
public static ListNode reverseList2(ListNode head) {
return helper(null, head);
}
public static ListNode helper(ListNode pre, ListNode head){
if (head == null) return pre;
ListNode nxt = head.next;
head.next = pre;
return helper(head, nxt);
}
/**
* 合并两个有序链表,以l1为主
* @param l1
* @param l2
* @return
*/
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode helper = new ListNode(0); //核心点:以l1为主体,在头部添加一个helper节点,即便第一次l2.val < l1.val,这样插入节点部分代码,通配可用。
ListNode pre = helper;
helper.next = l1;
while(l1 != null && l2 != null){
if(l1.val > l2.val){
ListNode nxt = l2.next;
l2.next = l1;
pre.next = l2;
l2 = nxt;
}else{
l1 = l1.next;
}
pre = pre.next;
}
if(l2 != null){
pre.next = l2;
}
return helper.next;
}
/**
* 合并两个有序链表,从新生成一个链表
* @param l1
* @param l2
* @return
*/
public static ListNode mergeTwoLists1(ListNode l1, ListNode l2) {
ListNode helper = new ListNode(0);
ListNode head = helper;
while(l1 != null && l2 != null){
if(l1.val > l2.val){
helper.next = l2;
helper = l2;
l2 = l2.next;
}else{
helper.next = l1;
helper = l1;
l1 = l1.next;
}
}
if(l1 != null){
helper.next = l1;
}
if(l2 != null){
helper.next = l2;
}
return head.next;
}
/**
*判断链表是否有环:且涵盖了head为null的处理
*
* @param head
* @return
*/
public static boolean hasCycle(ListNode head){
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null){ //核心点:循环跳出条件
slow = slow.next;
fast = fast.next.next;
if (slow == fast) return true;
}
return false;
}
/**
* 如果链表有循环,返回开始循环的节点;如果链表没有循环,则返回null
*
* 更考验逻辑:a+b+c+b = 2a+2b => a=c
* @param head
* @return
*/
public static ListNode detectCycle(ListNode head) { //空链表 链表节点只有一个
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){//链表有环
slow = head;
while(slow != fast){ //核心点
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
return null;
}//end method
/**
* 判断一个链表是否为回文链表---第一次书写思路写不出
* @param head
* @return
*/
public static boolean isPalindrome(ListNode head) {
//1.MOVE:利用快慢指针来查找链表中间节点(快步长2,慢步长1) 1->2->3->2->1
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
}
//2.REVERSE 1->2->3 null<-2<-1
if(fast != null){ //odd nodes:let the right half smaller
slow = slow.next;
}
slow = reverseList(slow);
fast = head;
//3.COMPARE
while(slow != null){
if(slow.val != fast.val){
return false;
}
slow = slow.next;
fast = fast.next;
}
return true;
}
/**
* 求两个链表的交点。
* 说明:如果没有交点,返回null
* @param headA
* @param headB
* @return
*/
public static ListNode getIntersectionNode(ListNode headA, ListNode headB){
if(headA == null || headB == null) return null; //移除这行代码仍旧成功。但放这行代码可以加快程序的处理速度
//考虑如下情况:Condition1两个链表非空无交点,返回null Condition2两个链表非空有交点,返回交点处节点
ListNode a = headA;
ListNode b = headB;
while(a != b){
a = (a != null) ? a.next : headB;
b = (b != null) ? b.next : headA;
}
return a;
}
/**
* 奇偶链表:将奇数位置的节点放到前面,偶数位置拼接到后面
*
* @param head 1->2->3->4->5->null
* @return
*/
public static ListNode oddEvenList(ListNode head) {
//特殊情况
if (head == null) return null;
ListNode odd = head;
ListNode even = head.next;
ListNode evenHead = even; //核心点
while (even != null && even.next != null) { //核心点
odd.next = odd.next.next;
even.next = even.next.next;
odd = odd.next;
even = even.next;
}
odd.next = evenHead; //核心点
return head;
}
/**
* 移除链表末尾的第n个节点
*
* 说明:不需要前置节点,直接移除欲删除节点,尾节点特殊处理
* 不涵盖一个节点特殊处理
*
* @param head
* @param n
* @return
*/
public static ListNode removeNthFromEnd(ListNode head, int n){
//特殊情况处理:一个节点
if(head.next == null)
return null;
//查找到欲移除节点
ListNode fast = head;
ListNode slow = head;
ListNode pre = null;
for(int i=1; i <= n; i++){
fast = fast.next;
}
while(fast != null){
pre = slow;
slow = slow.next;
fast = fast.next;
}
//判断删除节点是否为尾节点
if(n == 1){
pre.next = null;
return head; //核心点
}
//常规节点移除(非尾节点)
slow.val = slow.next.val;
slow.next = slow.next.next;
return head;
}
/**
* 移除链表末尾的第n个节点
*
* 说明:利用前置节点,来移除欲删除节点,头结点特殊处理
* 涵盖了一个节点处理情况
* @param head
* @param n
* @return
*/
public static ListNode removeNthFromEnd2(ListNode head, int n){
ListNode fast = head;
ListNode slow = head;
//fast move
for (int i = 1; i <= n; i++) {
fast = fast.next;
}
//special: remove head
if(fast == null){
head = head.next;
return head;
}
//find before node
while(fast.next != null){
slow = slow.next;
fast = fast.next;
}
//remove
slow.next = slow.next.next;
return head;
}
/**
* 解法3:为链表头添加一个辅助节点
*
* @param head
* @param n
* @return
*/
public static ListNode removeNthFromEnd3(ListNode head, int n) {
//add helper node
ListNode helper = new ListNode(0);
helper.next = head;
ListNode fast = helper;
ListNode slow = helper;
//move fast
for (int i = 1; i <= n + 1; i++) { //核心点:n+1
fast = fast.next;
}
//find before node
while(fast != null){ //核心点
slow = slow.next;
fast = fast.next;
}
//remove
slow.next = slow.next.next;
return helper.next;
}
/**
* 链表排序:要求时间复杂度为O(nlogn)
* 此例使用:归并排序
* @param head
* @return
*/
public static ListNode sortList(ListNode head){
return mergeSort(head);
}
public static ListNode mergeSort(ListNode head){
//递归出口
if(head == null || head.next == null) return head;
//查找链表中点节点
ListNode slow = head;
ListNode fast = head;
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
//左右递归
ListNode head2 = slow.next;
slow.next = null;
ListNode head1 = head;
head1 = mergeSort(head1);
head2 = mergeSort(head2);
//合并两个有序链表
return mergeTwoLists(head1, head2);
}//end method
/**
* 计算两个链表非负整数的和
* @param l1
* @param l2
* @return
*/
public static ListNode addTwoNumbers(ListNode l1, ListNode l2){
//特殊情况处理:代码已经可以执行正常
int sum = 0; //数位的和
//生成一个新的链表存储结果
ListNode helper = new ListNode(-1);
ListNode p = helper;
while(l1 != null || l2 != null){
sum = sum / 10; //是否进位
if (l1 != null) {
sum += l1.val;
l1 = l1.next;
}
if(l2 != null){
sum += l2.val;
l2 = l2.next;
}
p.next = new ListNode(sum % 10);
p = p.next;
}
if(sum >= 10){
p.next = new ListNode(1);
}
return helper.next;
}//end method
}
| [
"657091714@qq.com"
] | 657091714@qq.com |
a20436a9a42ba99bdbf5a086afaebfbc296ad07e | 67e2b90f2bf068a1afc32712cfae37cf67c74129 | /app/src/main/java/ggcartoon/yztc/com/View/SwipBackActivityS.java | 245df7cf3c65a0ba027b5c7fc81b9cd6bed4b647 | [] | no_license | jzt-Tesla/GGcartoon | d75673e8d2574b3ce055d57343e12b4a7ff3d233 | 17f6238c590524567796b4d939ccef062646dc30 | refs/heads/master | 2021-01-12T17:15:59.240709 | 2016-09-20T05:54:47 | 2016-09-20T05:54:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,533 | java | package ggcartoon.yztc.com.View;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.Utils;
import me.imid.swipebacklayout.lib.app.SwipeBackActivityBase;
import me.imid.swipebacklayout.lib.app.SwipeBackActivityHelper;
/**
* 带侧滑返回的AppCompatActivity
*/
public class SwipBackActivityS extends AppCompatActivity implements SwipeBackActivityBase{
private SwipeBackActivityHelper mHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHelper = new SwipeBackActivityHelper(this);
mHelper.onActivityCreate();
}
@Override
public SwipeBackLayout getSwipeBackLayout() {
return mHelper.getSwipeBackLayout();
}
@Override
public void setSwipeBackEnable(boolean enable) {
getSwipeBackLayout().setEnableGesture(enable);
}
@Override
public void scrollToFinishActivity() {
Utils.convertActivityToTranslucent(this);
getSwipeBackLayout().scrollToFinishActivity();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mHelper.onPostCreate();
}
@Override
public View findViewById(int id) {
View v = super.findViewById(id);
if (v == null && mHelper != null)
return mHelper.findViewById(id);
return v;
}
}
| [
"18710199577@163.com"
] | 18710199577@163.com |
48b9dbaf0d99efe8f05bcb2ae8bc2d491351e1c0 | a5f4a025699e137a2230bd90bfa42ed25fc6a765 | /SEMS/src/com/unaware/servlet/PhotoServlet.java | 2b6b62c7d86d9c8eddb49a93715e433fdd0cf972 | [] | no_license | Flians/SEMS | 142536a66ae0f817b16a23959f3dda07a31ef9a9 | 67d7a6997e409f9d1dff61f609675dbfefe9ff03 | refs/heads/master | 2021-08-28T21:27:26.378944 | 2017-12-13T06:03:35 | 2017-12-13T06:03:35 | 114,078,637 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,559 | java | package com.unaware.servlet;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileUploadException;
import com.lizhou.exception.FileFormatException;
import com.lizhou.exception.NullFileException;
import com.lizhou.exception.ProtocolException;
import com.lizhou.exception.SizeException;
import com.unaware.bean.User;
import com.unaware.service.PhotoService;
import com.unaware.tools.StringTool;
/**
* 上传照片Servlet
* @author bojiangzhou
*
*/
public class PhotoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
PhotoService service = new PhotoService();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取请求的方法
String method = request.getParameter("method");
if("GetPhoto".equals(method)){ //设置照片
getPhoto(request, response);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取请求的方法
String method = request.getParameter("method");
if("SetPhoto".equals(method)){ //设置照片
setPhoto(request, response);
}
}
/**
* 获取教师和学生的照片
* @param request
* @param response
* @throws IOException
*/
private void getPhoto(HttpServletRequest request, HttpServletResponse response) throws IOException {
User user = new User();
//获取number
String number = request.getParameter("number");
if(!StringTool.isEmpty(number)){
int type = Integer.parseInt(request.getParameter("type"));
user.setAccount(number);
user.setType(type);
} else{
user = (User) request.getSession().getAttribute("user");
}
InputStream is = service.getPhoto(user);
if(is != null){
byte[] b = new byte[is.available()];
is.read(b);
response.getOutputStream().write(b, 0, b.length);
}
}
/**
* 教师和学生设置照片
* @param request
* @param response
* @throws IOException
*/
private void setPhoto(HttpServletRequest request, HttpServletResponse response) throws IOException {
//获取学号或工号
User user = (User) request.getSession().getAttribute("user");
String msg = service.setPhoto(user, request);
response.getWriter().write(msg);
}
}
| [
"rongliangfu@outlook.com"
] | rongliangfu@outlook.com |
2d53769d8947832914a20a6daf04a220385f4e01 | a6db31c3f9264c7b0ad5c3307dee4afd7ce689c1 | /UI/ImageLoader/UniversalDemo/app/src/main/java/com/example/zy/universaldemo/MainActivity.java | d8e906532ff0ba46ea01fbd87b91decd729c44bd | [] | no_license | aJanefish/Work | 2933fa5437b3c216ff1d76aa641af26226e5295c | 96e585d6208e9d6bab5576a25853c0fdb54fbcd8 | refs/heads/master | 2021-06-29T15:53:28.458468 | 2020-02-23T08:23:44 | 2020-02-23T08:23:44 | 141,233,308 | 0 | 0 | null | 2020-10-13T10:42:43 | 2018-07-17T04:58:08 | Python | UTF-8 | Java | false | false | 8,789 | java | package com.example.zy.universaldemo;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.decode.BaseImageDecoder;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener;
import com.nostra13.universalimageloader.utils.StorageUtils;
import java.io.File;
/**
* 1、多线程异步加载和显示图片(网络图片、sd卡、资源文件(asset,mipmap等,不能加载9patch),新增加载视频缩略图)
* 2、支持加载过程的监听,可以暂停加载图片,在经常使用的ListView、GridView中,可以设置滑动时暂停加载,停止滑动时加载图片(便于节约流量,在一些优化中可以使用)
* 3、高度可定制化(可以根据自己的需求进行各种配置,如:线程池,图片下载器,内存缓存策略等)
* 4、支持图片的内存缓存,SD卡(文件)缓存
*
* 注意事项:
* 1、ImageLoaderConfiguration必须配置并且全局化的初始化这个配置ImageLoader.getInstance().init(config); 否则会出现错误提示
* 2、ImageLoader是根据ImageView的height,width确定图片的宽高。
* 3、如果经常出现OOM(官方的建议)
* ①减少配置之中线程池的大小,(.threadPoolSize).推荐1-5;
* ②使用.bitmapConfig(Bitmap.config.RGB_565)代替ARGB_8888;
* ③使用.imageScaleType(ImageScaleType.IN_SAMPLE_INT)或者 try.imageScaleType(ImageScaleType.EXACTLY);
* ④避免使用RoundedBitmapDisplayer.他会创建新的ARGB_8888格式的Bitmap对象;
* ⑤使用.memoryCache(new WeakMemoryCache()),不要使用.cacheInMemory();
* */
public class MainActivity extends AppCompatActivity {
private ImageLoader imageLoader;
private ImageView myimage;
private DisplayImageOptions mOptions;
private String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
init();
}
private void initView() {
myimage = findViewById(R.id.myimage);
}
private void init() {
//获取缓存文件
File cacheDir = StorageUtils.getCacheDirectory(this);
//设置自定义缓存的目录
cacheDir = StorageUtils.getOwnCacheDirectory(this,"imageloader/Cache");
//初始化ImageLoad
ImageLoaderConfiguration config =new ImageLoaderConfiguration.Builder(this)
.memoryCacheExtraOptions(480,800)//设置缓存图片的默认尺寸,一般取设备的屏幕尺寸
.diskCacheExtraOptions(480,800, null)
.threadPoolSize(3)// 线程池内加载的数量,default = 3
.threadPriority(Thread.NORM_PRIORITY-2)
.tasksProcessingOrder(QueueProcessingType.FIFO)
.denyCacheImageMultipleSizesInMemory()
.memoryCache(new LruMemoryCache(2*1024*1024))//自定义内存的缓存策略
.memoryCacheSize(2*1024*1024)
.memoryCacheSizePercentage(13)// default
.diskCache(new UnlimitedDiskCache(cacheDir))// default
.diskCacheSize(50*1024*1024)
.diskCacheFileCount(100)//缓存的文件数量
.diskCache(new UnlimitedDiskCache(cacheDir))//自定义缓存路径
.diskCacheFileNameGenerator(new HashCodeFileNameGenerator())// default
.imageDownloader(new BaseImageDownloader(this))// default
.imageDecoder(new BaseImageDecoder(true))// default
.defaultDisplayImageOptions(DisplayImageOptions.createSimple())// default
.writeDebugLogs()
.build();
ImageLoader.getInstance().init(config);
imageLoader = ImageLoader.getInstance();
mOptions = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.loading)//设置图片在下载期间显示的图片
.showImageForEmptyUri(R.mipmap.ic_launcher)//设置图片Uri为空或是错误的时候显示的图片
.showImageOnFail(R.drawable.loaderror)//设置图片加载/解码过程中错误时候显示的图片
.cacheInMemory(true)//设置下载的图片是否缓存在内存中
.cacheOnDisk(true)//设置是否缓存在SD卡中
.considerExifParams(true)//是否考虑JPEG图像EXIF参数(旋转,翻转)
.imageScaleType(ImageScaleType.EXACTLY_STRETCHED)//设置图片的缩放类型
.bitmapConfig(Bitmap.Config.ARGB_4444)//设置图片的解码类型
//.decodingOptions(null) //设置Bitmap的配置选项
.resetViewBeforeLoading(true)//设置图片在下载前是否重置,复位
.displayer(new RoundedBitmapDisplayer(100))//是否设置为圆角,弧度为多少
.displayer(new FadeInBitmapDisplayer(500))//是否图片加载好后渐入的动画时间
.build();
/**
* imageScaleType(ImageScaleType imageScaleType)是设置图片的缩放方式,其中缩放方式有如下几种:
* EXACTLY :图像将完全按比例缩小的目标大小
* EXACTLY_STRETCHED:图片会缩放到目标大小完全
* IN_SAMPLE_INT:图像将被二次采样的整数倍
* IN_SAMPLE_POWER_OF_2:图片将降低2倍,直到下一减少步骤,使图像更小的目标大小
* NONE:图片不会调整
*
* displayer(BitmapDisplayer displayer)是设置图片的显示方式显示方式displayer:
* RoundedBitmapDisplayer(introundPixels)设置圆角图片
* FakeBitmapDisplayer()这个类什么都没做
* FadeInBitmapDisplayer(intdurationMillis)设置图片渐显的时间
* SimpleBitmapDisplayer()正常显示一张图片
* */
}
public void loadOne(View view) {
// 加载一张网络图片
imageLoader.displayImage("http://wx2.sinaimg.cn/mw690/ac38503ely1fesz8m0ov6j20qo140dix.jpg", myimage);
}
public void loadTwo(View view) {
//加载一张网络图片并自定义配置
imageLoader.displayImage(imageUrl,myimage,mOptions);
}
private static final String imageUrl = "http://wx2.sinaimg.cn/mw690/ac38503ely1fesz8m0ov6j20qo140dix.jpg";
public void loadThree(View view) {
ImageLoader.getInstance().displayImage(imageUrl,
myimage,
mOptions,
new ImageLoadingListener() {
@Override
public void onLoadingStarted(String imageUri, View view) {
//开始加载
Log.d(TAG,"onLoadingStarted:"+imageUri);
}
@Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
//加载失败
Log.d(TAG,"onLoadingFailed:"+failReason.getCause());
}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
//加载完成
Log.d(TAG,"onLoadingComplete:");
}
@Override
public void onLoadingCancelled(String imageUri, View view) {
//取消加载
Log.d(TAG,"onLoadingCancelled:"+imageUri);
}
});
}
public void loadFour(View view) {
imageLoader.displayImage(imageUrl,
myimage,
mOptions,
new ImageLoadingListener() {
@Override
public void onLoadingStarted(String imageUri, View view) {
//开始加载
Log.d(TAG,"onLoadingStarted:"+imageUri);
}
@Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
//加载失败
Log.d(TAG,"onLoadingFailed:"+failReason.getCause());
}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
//加载完成
Log.d(TAG,"onLoadingComplete:");
}
@Override
public void onLoadingCancelled(String imageUri, View view) {
//取消加载
Log.d(TAG,"onLoadingCancelled:"+imageUri);
}
},
new ImageLoadingProgressListener(){
@Override
public void onProgressUpdate(String imageUri, View view, int current, int total) {
}
}
);
}
}
| [
"yu.zhang@singou.mo"
] | yu.zhang@singou.mo |
14d583d0641e314ff51ae3e7ce60c43888f85329 | a2717e7ab57889c86e154794ab660555fc73450d | /src/ciclos.java | ea6749e05522b318f421f5eeb7e303334b27f990 | [] | no_license | Jefry18/ciclos | e2f5c8606c306a451c2349b00b8627b1c5fdeb34 | 867d68cca1db90385ffbe08843183254596033fd | refs/heads/master | 2023-01-19T09:59:32.197903 | 2020-11-17T16:46:49 | 2020-11-17T16:46:49 | 313,682,693 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 937 | java | package com.company;
import java.util.Scanner;
public class ciclos {
public static void main(String[] args) {
int s = 1;
while (s != 2) {
System.out.println("Tabla de multiplicar del 1 al 12");
Scanner entrada = new Scanner(System.in);
int n;
System.out.println("Introduce un número entero: ");
n = entrada.nextInt();
if (n > 0 || n <= 12) {
System.out.println("Tabla del " + n);
for (int i = 1; i <= 12; i++) {
System.out.println(n + " * " + i + " = " + n * i);
}
System.out.println("Desea visualizar otra tabla? ");
System.out.println("1. Si");
System.out.println("2. No");
s = entrada.nextInt();
}
}
}
}
| [
"yahikomu17@gmail.com"
] | yahikomu17@gmail.com |
e3d817c9c5dfb6a38525767a7db0828ab9cc6f42 | 39f8e8422190effa27f373c6b48842e3e9722c33 | /app/src/androidTest/java/com/example/jitu/searchexample1/ExampleInstrumentedTest.java | 555b620f959ab26010e75f08c0dcf9093e196058 | [] | no_license | jituumakanta/Searchexample1 | a40708cd6d33b696490e59e09e841fd1e60e39ab | 26908970911ad4fc5a4f3c627b45ee2a705f6846 | refs/heads/master | 2021-01-11T19:17:32.140199 | 2017-09-28T20:20:23 | 2017-09-28T20:20:23 | 79,345,401 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 766 | java | package com.example.jitu.searchexample1;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.jitu.searchexample1", appContext.getPackageName());
}
}
| [
"jitu.umakanta@gmail.com"
] | jitu.umakanta@gmail.com |
84e5ded02b3dbe53239db4672dfdc7d6d9a08ba8 | 45a88531ceb11ff4ff0344a5035d3b9929d74ed1 | /src/main/java/astavie/thermallogistics/util/RequesterReference.java | c2f48104045bb31977ee1ba0fcc6b24aa58ea7bb | [] | no_license | Astavie/ThermalLogistics | 5dc01b7ab18bb4d9500765ee8f129acb633c2cfb | bb017105d9219b4eab477364e806e037172e1f09 | refs/heads/0.3-x | 2021-08-03T01:26:19.267501 | 2021-07-07T09:16:48 | 2021-07-07T09:16:48 | 155,930,242 | 10 | 10 | null | 2021-07-21T21:13:49 | 2018-11-02T23:03:10 | Java | UTF-8 | Java | false | false | 5,728 | java | package astavie.thermallogistics.util;
import java.util.List;
import astavie.thermallogistics.attachment.IRequester;
import astavie.thermallogistics.attachment.IRequesterContainer;
import cofh.core.network.PacketBase;
import cofh.thermaldynamics.duct.Attachment;
import cofh.thermaldynamics.duct.tiles.TileGrid;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.fml.common.FMLCommonHandler;
public class RequesterReference<I> {
public final int dim;
public final BlockPos pos;
public final byte side;
public final int index;
private long tick;
private IRequester<I> cache;
private ItemStack icon = ItemStack.EMPTY;
private ItemStack tile = ItemStack.EMPTY;
public RequesterReference(int dim, BlockPos pos) {
this(dim, pos, (byte) 0, 0);
}
public RequesterReference(int dim, BlockPos pos, byte side) {
this(dim, pos, side, 0);
}
public RequesterReference(int dim, BlockPos pos, byte side, int index) {
this.dim = dim;
this.pos = pos;
this.side = side;
this.index = index;
}
public static NBTTagCompound writeNBT(RequesterReference<?> reference) {
NBTTagCompound nbt = new NBTTagCompound();
if (reference == null) {
return nbt;
}
nbt.setInteger("dim", reference.dim);
nbt.setInteger("x", reference.pos.getX());
nbt.setInteger("y", reference.pos.getY());
nbt.setInteger("z", reference.pos.getZ());
nbt.setByte("side", reference.side);
nbt.setInteger("index", reference.index);
return nbt;
}
public static <I> RequesterReference<I> readNBT(NBTTagCompound nbt) {
if (nbt.isEmpty()) {
return null;
} else {
return new RequesterReference<>(nbt.getInteger("dim"), new BlockPos(nbt.getInteger("x"), nbt.getInteger("y"), nbt.getInteger("z")), nbt.getByte("side"), nbt.getInteger("index"));
}
}
public static void writePacket(PacketBase packet, RequesterReference<?> reference) {
packet.addBool(reference == null);
if (reference != null) {
packet.addInt(reference.dim);
packet.addCoords(reference.pos.getX(), reference.pos.getY(), reference.pos.getZ());
packet.addByte(reference.side);
packet.addInt(reference.index);
IRequester<?> requester = reference.get();
packet.addItemStack(requester.getIcon());
packet.addItemStack(requester.getTileIcon());
}
}
public static <I> RequesterReference<I> readPacket(PacketBase packet) {
if (packet.getBool()) {
return null;
} else {
RequesterReference<I> reference = new RequesterReference<>(packet.getInt(), packet.getCoords(), packet.getByte(), packet.getInt());
reference.icon = packet.getItemStack();
reference.tile = packet.getItemStack();
return reference;
}
}
public boolean isLoaded() {
World world = DimensionManager.getWorld(dim);
return world != null && world.isBlockLoaded(pos);
}
public boolean isLoaded(World world) {
return world.provider.getDimension() == dim && world.isBlockLoaded(pos);
}
public IRequester<I> get() {
return get(FMLCommonHandler.instance().getMinecraftServerInstance().getWorld(dim));
}
public IRequesterContainer<I> getContainer() {
return getContainer(FMLCommonHandler.instance().getMinecraftServerInstance().getWorld(dim));
}
@SuppressWarnings("unchecked")
public IRequester<I> get(World world) {
if (world.provider.getDimension() != dim)
return null;
if (world.getTotalWorldTime() == tick)
return cache;
tick = world.getTotalWorldTime();
cache = null;
TileEntity tile = world.getTileEntity(pos);
try {
if (tile instanceof IRequester) {
cache = (IRequester<I>) tile;
} else if (tile instanceof IRequesterContainer) {
List<? extends IRequester<?>> list = ((IRequesterContainer<?>) tile).getRequesters();
cache = index < list.size() ? (IRequester<I>) list.get(index) : null;
} else if (tile instanceof TileGrid) {
Attachment attachment = ((TileGrid) tile).getAttachment(side);
if (attachment instanceof IRequester) {
cache = (IRequester<I>) attachment;
} else if (attachment instanceof IRequesterContainer) {
List<? extends IRequester<?>> list = ((IRequesterContainer<?>) attachment).getRequesters();
cache = index < list.size() ? (IRequester<I>) list.get(index) : null;
}
}
} catch (ClassCastException ignore) {
cache = null;
}
return cache;
}
@SuppressWarnings("unchecked")
public IRequesterContainer<I> getContainer(World world) {
if (world.provider.getDimension() != dim)
return null;
TileEntity tile = world.getTileEntity(pos);
try {
if (tile instanceof IRequesterContainer) {
return (IRequesterContainer<I>) tile;
} else if (tile instanceof TileGrid) {
Attachment attachment = ((TileGrid) tile).getAttachment(side);
if (attachment instanceof IRequesterContainer)
return (IRequesterContainer<I>) attachment;
}
} catch (ClassCastException ignore) {
}
return null;
}
public boolean references(IRequester<?> requester) {
return requester != null && requester.referencedBy(this);
}
public boolean equals(Object object) {
if (object instanceof RequesterReference) {
RequesterReference<?> reference = (RequesterReference<?>) object;
return reference.dim == dim && reference.pos.equals(pos) && reference.side == side && reference.index == index;
}
return false;
}
@Override
public int hashCode() {
return ((Integer.hashCode(dim) * 31 + pos.hashCode()) * 31 + Integer.hashCode(side)) * 31 + Integer.hashCode(index);
}
public ItemStack getIcon() {
return icon;
}
public ItemStack getTileIcon() {
return tile;
}
}
| [
"astavie@protonmail.com"
] | astavie@protonmail.com |
b312c8489e7ca6449ba9407e34925f2f505c68bb | 5468f8e2dd1c6ba3fb4d0561f43ad5baa764b62e | /src/org/mybatis/generator/codegen/mybatis3/javamapper/elements/sqlprovider/ProviderUpdateByExampleSelectiveMethodGenerator.java | 9812c146aed2337982299d03afa29748eec47d5c | [] | no_license | liuyuhua1984/MyBatisSql | f0934de98e0c5111efe0de71081a11dc3b28f62f | e039cc7387cf00e04f8b5008e1e9428f77992310 | refs/heads/master | 2021-01-20T16:55:16.391918 | 2017-06-13T10:35:17 | 2017-06-13T10:35:17 | 90,857,314 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,454 | java | /**
* Copyright 2006-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mybatis.generator.codegen.mybatis3.javamapper.elements.sqlprovider;
import static org.mybatis.generator.internal.util.JavaBeansUtil.getGetterMethodName;
import static org.mybatis.generator.internal.util.StringUtility.escapeStringForJava;
import static org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities.getAliasedEscapedColumnName;
import static org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities.getParameterClause;
import java.util.Set;
import java.util.TreeSet;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.codegen.mybatis3.ListUtilities;
/**
*
* @author Jeff Butler
*
*/
public class ProviderUpdateByExampleSelectiveMethodGenerator extends AbstractJavaProviderMethodGenerator {
public ProviderUpdateByExampleSelectiveMethodGenerator(boolean useLegacyBuilder) {
super(useLegacyBuilder);
}
@Override
public void addClassElements(TopLevelClass topLevelClass) {
Set<String> staticImports = new TreeSet<String>();
Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>();
if (useLegacyBuilder) {
staticImports.add("org.apache.ibatis.jdbc.SqlBuilder.BEGIN"); //$NON-NLS-1$
staticImports.add("org.apache.ibatis.jdbc.SqlBuilder.UPDATE"); //$NON-NLS-1$
staticImports.add("org.apache.ibatis.jdbc.SqlBuilder.SET"); //$NON-NLS-1$
staticImports.add("org.apache.ibatis.jdbc.SqlBuilder.SQL"); //$NON-NLS-1$
} else {
importedTypes.add(NEW_BUILDER_IMPORT);
}
importedTypes.add(new FullyQualifiedJavaType("java.util.Map")); //$NON-NLS-1$
Method method = new Method(introspectedTable.getUpdateByExampleSelectiveStatementId());
method.setReturnType(FullyQualifiedJavaType.getStringInstance());
method.setVisibility(JavaVisibility.PUBLIC);
method.addParameter(new Parameter(new FullyQualifiedJavaType("java.util.Map<java.lang.String, java.lang.Object>"), //$NON-NLS-1$
"parameter")); //$NON-NLS-1$
FullyQualifiedJavaType record = introspectedTable.getRules().calculateAllFieldsClass();
importedTypes.add(record);
method.addBodyLine(String.format("%s record = (%s) parameter.get(\"record\");", //$NON-NLS-1$
record.getShortName(), record.getShortName()));
FullyQualifiedJavaType example = new FullyQualifiedJavaType(introspectedTable.getExampleType());
importedTypes.add(example);
method.addBodyLine(String.format("%s example = (%s) parameter.get(\"example\");", //$NON-NLS-1$
example.getShortName(), example.getShortName()));
context.getCommentGenerator().addGeneralMethodComment(method, introspectedTable);
method.addBodyLine(""); //$NON-NLS-1$
if (useLegacyBuilder) {
method.addBodyLine("BEGIN();"); //$NON-NLS-1$
} else {
method.addBodyLine("SQL sql = new SQL();"); //$NON-NLS-1$
}
method.addBodyLine(String.format("%sUPDATE(\"%s\");", //$NON-NLS-1$
builderPrefix, escapeStringForJava(introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime())));
method.addBodyLine(""); //$NON-NLS-1$
for (IntrospectedColumn introspectedColumn : ListUtilities.removeGeneratedAlwaysColumns(introspectedTable.getAllColumns())) {
if (!introspectedColumn.getFullyQualifiedJavaType().isPrimitive()) {
method.addBodyLine(String.format("if (record.%s() != null) {", //$NON-NLS-1$
getGetterMethodName(introspectedColumn.getJavaProperty(), introspectedColumn.getFullyQualifiedJavaType())));
}
StringBuilder sb = new StringBuilder();
sb.append(getParameterClause(introspectedColumn));
sb.insert(2, "record."); //$NON-NLS-1$
method.addBodyLine(String.format("%sSET(\"%s = %s\");", //$NON-NLS-1$
builderPrefix, escapeStringForJava(getAliasedEscapedColumnName(introspectedColumn)), sb.toString()));
if (!introspectedColumn.getFullyQualifiedJavaType().isPrimitive()) {
method.addBodyLine("}"); //$NON-NLS-1$
}
method.addBodyLine(""); //$NON-NLS-1$
}
if (useLegacyBuilder) {
method.addBodyLine("applyWhere(example, true);"); //$NON-NLS-1$
method.addBodyLine("return SQL();"); //$NON-NLS-1$
} else {
method.addBodyLine("applyWhere(sql, example, true);"); //$NON-NLS-1$
method.addBodyLine("return sql.toString();"); //$NON-NLS-1$
}
if (context.getPlugins().providerUpdateByExampleSelectiveMethodGenerated(method, topLevelClass, introspectedTable)) {
topLevelClass.addStaticImports(staticImports);
topLevelClass.addImportedTypes(importedTypes);
topLevelClass.addMethod(method);
}
}
}
| [
"lyh@163.com"
] | lyh@163.com |
17510c03e025a1a9f187506eb9105d81371b5d5b | bcb66b4b7cd57a3099c96b564cd4ddd736df52c9 | /MineSweeper/src/mineSweeper/OptionDialog.java | c3b32c02b3f5de1619fa0f7dfae2662a0a146590 | [] | no_license | hyunstyle/Java-MineSweeper | 8409fec822810c7c4788e505c01b1e15f4d915ce | 38acf2ebf6caa3fa6a4981818d86ccc90c1351ba | refs/heads/master | 2020-12-02T22:23:29.281807 | 2017-07-03T15:33:17 | 2017-07-03T15:33:17 | 96,125,272 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,739 | java | package mineSweeper;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;
/*
* this class is used for Menu->Option click.
*/
public class OptionDialog extends JDialog
{
/*
* fill this dialog to OptionPanel(JPanel).
*/
private OptionPanel panel;
private JDialog dlg;
public OptionDialog(JFrame parent, Timer timer)
{
super();
parent.setEnabled(false);
this.setTitle("Options");
this.setSize(500, 500);
this.setVisible(true);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.setBackground(Color.black);
dlg = this;
/*
* if this dialog is toggled, this dialog always goes on top.
* and if this dialog is closed,
* set main frame enable and if game is not GAMEOVER state,
* restart timer.
*/
this.addWindowListener(new WindowAdapter()
{
@Override
public void windowOpened(WindowEvent e)
{
dlg.setAlwaysOnTop(true);
}
@Override
public void windowClosed(WindowEvent e)
{
parent.setEnabled(true);
parent.setAlwaysOnTop(true);
parent.setAlwaysOnTop(false);
if(!Frame.isGameOver)
timer.start();
System.out.println("CLOSED");
}
});
panel = new OptionPanel();
panel.btnCancel.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
/*
* Cancel option.
* just close the dialog.
*/
dlg.dispose();
}
});
panel.btnOK.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
parent.setEnabled(true);
timer.start();
if(Frame.difficulty == panel.difficulty && panel.difficulty != 4)
{
/*
* difficulty is not changed. just close dialog.
*/
dlg.dispose();
}
else if(Frame.difficulty != panel.difficulty || panel.difficulty == 4 ) // difficulty is changed
{
if(panel.difficulty == 4 && panel.textFieldWidth.getText() != null &&
panel.textFieldHeight.getText() != null && panel.textFieldMines.getText() != null)
{
/*
* if difficulty is 4 ( Custom ),
* width, height, mines should not be null.
* if just one of them is null, show warning dialog.
* or, set each value to the actual width, height, mineCount and close the dialog.
*/
try
{
Frame.CUSTOM_WIDTH = Integer.parseInt(panel.textFieldWidth.getText());
Frame.CUSTOM_HEIGHT = Integer.parseInt(panel.textFieldHeight.getText());
Frame.CUSTOM_MINES = Integer.parseInt(panel.textFieldMines.getText());
Frame.difficulty = panel.difficulty;
dlg.dispose();
}
catch(NumberFormatException ex)
{
JOptionPane.showMessageDialog(null, "width, height, mines must be a number.", "NumberFormatException", JOptionPane.WARNING_MESSAGE);
}
}
else // case difficulty : 1 or 2 or 3
{
/*
* just change actual difficulty.
* because in difficulty 1, 2, 3,
* width, height, the number of mines are automatically set.
*/
Frame.difficulty = panel.difficulty;
System.out.println("difficulty is set : " + Frame.difficulty);
dlg.dispose();
}
}
else
{
System.out.println("exception");
dlg.dispose();
}
}
});
this.add(panel);
System.out.println("option");
}
}
| [
"shox_@naver.com"
] | shox_@naver.com |
687df5a37ff82b52ae49d24dfbf16e5ad5d89be4 | e295ba67ba5856838bf39507048dd9d496f03839 | /src/oui/mms/mmi/MmfOuiMultiBasinEspRunTreeNode.java | f7ab350f3f8e30b5511bf243fff7bdac898693f9 | [] | no_license | nhm-usgs/oui | b0f815d101d0d0d4450d00177d4d561c8e4182b8 | caef26785c4b1a750b68a2d28c5f59ed8f7e40f8 | refs/heads/master | 2020-07-13T07:22:30.017074 | 2017-06-09T14:39:35 | 2017-06-09T14:39:35 | 205,031,172 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,026 | java | /*
* MmsOuiMultiBasinEspRunTreeNode.java
*
* Created on Dec 16, 2004, 10:08 AM
*/
package oui.mms.mmi;
import gov.usgs.cawsc.gui.WindowFactory;
import java.util.ArrayList;
import java.util.Iterator;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import oui.mms.datatypes.EnsembleData;
import oui.mms.MmsProjectXml;
import oui.mms.gui.Mms;
import oui.mms.io.MmsDataFileReader;
import oui.mms.datatypes.OuiCalendar;
/**
*
* @author markstro
*/
public class MmfOuiMultiBasinEspRunTreeNode extends MmsModelTreeNode implements MmsEspModelRunner {
// private MmsProjectXml pxml;
private String dataFileName;
private int initLength;
private String data_file;
private String espDataDestDir;
private String[] subBasins;
private String mmsWorkspace;
private String executable;
private String envFile;
private String controlFileExt;
private String espIODir;
private String espVariableName;
private String espVariableIndex;
private String xrouteHeaderDataFile;
private String xrouteExecutable;
private String xrouteControlFile;
private String xrouteEspVariableName;
private String[] xrouteEspVariableIndex;
private String relativeMmsWorkspace;
private String paramFileExt;
private String subBasinTheme = null;
private String forecastNodeTheme = null;
/** Creates a new instance of SingleRunMmi */
public MmfOuiMultiBasinEspRunTreeNode(Node xml_node) {
super(xml_node);
MmsProjectXml pxml = MmsProjectXml.getMmsProjectXml();
String mmi = MmsProjectXml.getElementContent(xml_node, "@mmi", null);
Node mmiNode = pxml.getMmiNode(mmi);
Node prmsNode = MmsProjectXml.selectSingleNode(mmiNode, "models[@name='prms']");
Node routeNode = MmsProjectXml.selectSingleNode(mmiNode, "models[@name='route']");
mmsWorkspace = pxml.getPath(prmsNode);
relativeMmsWorkspace = "./" + mmsWorkspace.substring(Mms.fileNameIndex(mmsWorkspace) + 1, mmsWorkspace.length());
dataFileName = MmsProjectXml.getElementContent(prmsNode, "@dataFileName", null);
espVariableName = MmsProjectXml.getElementContent(prmsNode, "@espVariableName", null);
espVariableIndex = MmsProjectXml.getElementContent(prmsNode, "@espVariableIndex", null);
initLength = Integer.parseInt(MmsProjectXml.getElementContent(prmsNode, "@initLength", null));
espIODir = pxml.getEspIODir(prmsNode, "@espIODir");
executable = MmsProjectXml.getElementContent(prmsNode, "@executable", null);
envFile = MmsProjectXml.getElementContent(prmsNode, "@envFile", null);
controlFileExt = MmsProjectXml.getElementContent(prmsNode, "@controlFileExt", null);
paramFileExt = MmsProjectXml.getElementContent(prmsNode, "@paramFileExt", null);
subBasinTheme = MmsProjectXml.getElementContent(prmsNode, "@theme", null);
xrouteExecutable = MmsProjectXml.getElementContent(routeNode, "@executable", null);
xrouteControlFile = MmsProjectXml.getElementContent(routeNode, "@controlFile", null);
xrouteHeaderDataFile = mmsWorkspace + "/input/data/" + MmsProjectXml.getElementContent(routeNode, "@dataFileHeader", null);
xrouteEspVariableName = MmsProjectXml.getElementContent(routeNode, "@espVariableName", null);
/*
* Get the esp variable indicies
*/
forecastNodeTheme = MmsProjectXml.getElementContent(routeNode, "@theme", null);
}
@Override
public void run() {
MmsProjectXml pxml = MmsProjectXml.getMmsProjectXml();
/*
* Get the MMI nodes
*/
// String mmi = pxml.getElementContent(_xml_node, "@mmi", null);
// Node mmiNode = pxml.getMmiNode(mmi);
// Node prmsNode = pxml.selectSingleNode(mmiNode, "models[@name='prms']");
// Node routeNode = pxml.selectSingleNode(mmiNode, "models[@name='route']");
/*
* Read the stuff for PRMS from XML
*/
// mmsWorkspace = pxml.getPath(prmsNode);
// relativeMmsWorkspace = "./" + mmsWorkspace.substring(Mms.fileNameIndex(mmsWorkspace) + 1, mmsWorkspace.length());
// dataFileName = pxml.getElementContent(prmsNode, "@dataFileName", null);
// espVariableName = pxml.getElementContent(prmsNode, "@espVariableName", null);
// espVariableIndex = pxml.getElementContent(prmsNode, "@espVariableIndex", null);
// initLength = Integer.parseInt(pxml.getElementContent(prmsNode, "@initLength", null));
// espIODir = pxml.getEspIODir(prmsNode, "@espIODir");
// executable = pxml.getElementContent(prmsNode, "@executable", null);
// envFile = pxml.getElementContent(prmsNode, "@envFile", null);
// controlFileExt = pxml.getElementContent(prmsNode, "@controlFileExt", null);
// paramFileExt = pxml.getElementContent(prmsNode, "@paramFileExt", null);
/*
* Get the sub basin names
*/
// String subBasinTheme = pxml.getElementContent(prmsNode, "@theme", null);
Node subBasinThemeMappingNode = MmsProjectXml.selectSingleNode(pxml.getProjectXmlNode(), "MetaData/gis/themes/theme[@theme='" + subBasinTheme + "']/mappings");
// DANGER hack
if (subBasinThemeMappingNode == null) {
subBasinThemeMappingNode = MmsProjectXml.selectSingleNode(pxml.getProjectXmlNode(), "MetaData/themes/theme[@theme='" + subBasinTheme + "']/mappings");
}
NodeList mappingNodes = MmsProjectXml.selectNodes(subBasinThemeMappingNode, "mapping");
subBasins = new String[mappingNodes.getLength()];
for (int i = 0; i < mappingNodes.getLength(); i++) {
subBasins[i] = MmsProjectXml.getElementContent(mappingNodes.item(i), "@modelName", null);
}
// I don't think these things need to be in order.
// NodeList mappingNodes = pxml.selectNodes(subBasinThemeMappingNode, "mapping");
// subBasins = new String[mappingNodes.getLength()];
// for (int i = 0; i < mappingNodes.getLength(); i++) { // put the subbasin list in order
// int index = -1;
// try {
// index = Integer.decode(pxml.getElementContent(mappingNodes.item(i), "@modelOrder", null)).intValue();
// } catch (NumberFormatException e) {
// System.out.println ("Bad value for modelOrder tag in node" + mappingNodes.item(i));
// }
//
// subBasins[index - 1] = pxml.getElementContent(mappingNodes.item(i), "@modelName", null);
// }
data_file = mmsWorkspace + "/input/data/" + dataFileName;
espDataDestDir = mmsWorkspace + "/input/data/" + espIODir;
/*
* Read the stuff for xroute from XML
*/
// xrouteExecutable = pxml.getElementContent(routeNode, "@executable", null);
if (xrouteExecutable != null) {
// xrouteControlFile = pxml.getElementContent(routeNode, "@controlFile", null);
// xrouteHeaderDataFile = mmsWorkspace + "/input/data/" + pxml.getElementContent(routeNode, "@dataFileHeader", null);
// xrouteEspVariableName = pxml.getElementContent(routeNode, "@espVariableName", null);
/*
* Get the esp variable indicies
*/
// String forecastNodeTheme = pxml.getElementContent(routeNode, "@theme", null);
Node forecastThemeMappingNode = MmsProjectXml.selectSingleNode(pxml.getProjectXmlNode(), "MetaData/gis/themes/theme[@theme='" + forecastNodeTheme + "']/mappings");
// DANGER hack
if (forecastThemeMappingNode == null) {
forecastThemeMappingNode = MmsProjectXml.selectSingleNode(pxml.getProjectXmlNode(), "MetaData/themes/theme[@theme='" + forecastNodeTheme + "']/mappings");
}
mappingNodes = MmsProjectXml.selectNodes(forecastThemeMappingNode, "mapping");
xrouteEspVariableIndex = new String[mappingNodes.getLength()];
for (int i = 0; i < mappingNodes.getLength(); i++) {
int index = -1;
try {
index = Integer.decode(MmsProjectXml.getElementContent(mappingNodes.item(i), "@modelOrder", null)).intValue();
} catch (NumberFormatException e) {
System.out.println("Bad value for modelOrder tag in node" + mappingNodes.item(i));
}
xrouteEspVariableIndex[index - 1] = MmsProjectXml.getElementContent(mappingNodes.item(i), "@modelId", null);
}
}
/*
* Create the GUI
*/
MmsDataFileReader mdfr = new MmsDataFileReader(data_file);
if (showRunnerGui) {
MmsEspRunSimpleGui gui = new MmsEspRunSimpleGui(data_file, mdfr.getStart(), mdfr.getEnd(), this);
WindowFactory.displayInFrame(gui, "Run MMS Model in ESP Mode");
}
}
public void runModel(OuiCalendar forecastStart, OuiCalendar forecastEnd) {
/*
* Generate the ESP run and save to XML file
*/
String dataFileBasinName = dataFileName.substring(0, dataFileName.indexOf('.'));
EnsembleData ed = new EnsembleData(dataFileBasinName, null, null, null);
MmsOuiEspRun.writeEspDataFiles(ed, initLength, data_file, espDataDestDir, forecastStart, forecastEnd);
for (int i = 0; i < subBasins.length; i++) {
ed.setName(subBasins[i]);
MmsOuiEspRun.runEsp(ed, mmsWorkspace, executable, envFile, controlFileExt,
espIODir, espVariableName, espVariableIndex, relativeMmsWorkspace, paramFileExt);
// TODO Danger should this be commented out?
// MmsOuiEspReader.readEsp(ed);
String xml_file = mmsWorkspace + "/output/" + espIODir + "/" + subBasins[i] + ".xml";
ed.save(xml_file);
}
/*
* Load ESP run into EnsembleData
*/
ArrayList<EnsembleData> localEnsembleData = new ArrayList<EnsembleData>(subBasins.length);
for (int i = 0; i < subBasins.length; i++) {
String xml_file = mmsWorkspace + "/output/" + espIODir + "/" + subBasins[i] + ".xml";;
ed = EnsembleData.load(xml_file);
localEnsembleData.add(i, ed);
}
/*
* Xroute stuff
*/
if (xrouteExecutable != null) {
ArrayList routedEnsembleData = MmsOuiMultiBasinEspRun.writeXrouteDataFiles(localEnsembleData, espDataDestDir, xrouteHeaderDataFile, subBasins);
MmsOuiMultiBasinEspRun.runXrouteEsp(routedEnsembleData, mmsWorkspace, xrouteExecutable, envFile, xrouteControlFile, espIODir, xrouteEspVariableName, xrouteEspVariableIndex, relativeMmsWorkspace);
MmsOuiMultiBasinEspRun.readXrouteEsp(routedEnsembleData);
Iterator it = routedEnsembleData.iterator();
while (it.hasNext()) {
ed = (EnsembleData)(it.next());
String xml_file = mmsWorkspace + "/output/" + espIODir + "/" + ed.getName() + ".xml";
ed.save(xml_file);
}
}
}
}
| [
"markstro@usgs.gov"
] | markstro@usgs.gov |
7cc766f85ef105eab24fd10066d84ee0a5697ab4 | 84722332ae5fbadd9e151a5a7d85ad4538edde48 | /login/src/test/java/com/user/manager/service/AuthAdminServiceTest.java | f58b23af12cd290d94090a44f4c6ec1d3891623c | [] | no_license | freeloop-xiao/myopen | 421e44766947e1eb71dd817ea61583b062ca21ef | dbf41d6f88d251b098093beafe61a635ef959459 | refs/heads/master | 2020-03-19T02:48:17.990846 | 2018-06-10T14:54:17 | 2018-06-10T14:54:17 | 135,662,155 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,853 | java | package com.user.manager.service;
import com.user.exception.AppException;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* author: xiao
* date: 2018/6/4
* desc: 用户授权角色测试
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class AuthAdminServiceTest {
@Autowired
private AuthAdminService authAdminService;
@Rule
public ExpectedException thrown= ExpectedException.none();
@Test
public void authRole() {
int result = authAdminService.authRole("1069461504", 2);
Assert.assertEquals(1,result);
thrown.expect(AppException.class);
authAdminService.authRole("106946150411", 2);
thrown.expect(AppException.class);
authAdminService.authRole("1069461504", 100);
}
@Test
public void authRoles() {
List<Integer> roids = Arrays.asList(2, 3, 4, 5, 6, 7, 8, 9);
int result = authAdminService.authRoles("1069461504", roids);
Assert.assertEquals(8, result);
roids = Arrays.asList(10,11,100);
thrown.expect(AppException.class);
authAdminService.authRoles("1069461504", roids);
}
@Test
public void canceRole() {
int result = authAdminService.canceRole(1);
Assert.assertEquals(1, result);
}
@Test
public void canceRoles() {
List<Integer> adminRoleIds = Arrays.asList(2, 3, 4, 5);
int result = authAdminService.canceRoles(adminRoleIds);
Assert.assertEquals(4, result);
}
} | [
"306934150@qq.com"
] | 306934150@qq.com |
c7fac48f60958c632150a113dc6154d8e318fb17 | f92ee505d347635c4d4c744c915b77ea9b007386 | /netty-test/src/main/java/com/study/netty/NettyClient.java | 7aaf491537c083e4230a14514be6534e1e6317da | [] | no_license | py199541/netty-im-chat | 8ab367f260c3827d3460302e5976078688df2bc4 | a6c8f206bea953e6d24f0515538e2ef1cbe3ebad | refs/heads/master | 2020-04-15T15:42:06.994793 | 2018-11-30T16:44:58 | 2018-11-30T16:44:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,461 | java | package com.study.netty;
import com.study.netty.handler.FirstClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;
/**
* @author Kevin
* @Title: NettyClient
* @ProjectName studyjava
* @Description: TODO
* @date 2018/9/27 19:02
*/
public class NettyClient {
/**
* 重试次数
*/
private static final int MAX_RETRY = 5;
/**
* 对于客户端启动来说,和服务端的启动类似,依然需要线程模型、IO模型、以及IO业务处理逻辑三大参数。
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception{
//创建启动类
Bootstrap boot = new Bootstrap();
NioEventLoopGroup group = new NioEventLoopGroup();
//1.指定线程模型
boot.group(group)
//2.指定IO模型
.channel(NioSocketChannel.class)
//3.设定IO处理逻辑
.handler(new ChannelInitializer<SocketChannel>(){
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
//socketChannel.pipeline().addLast(new StringEncoder());
socketChannel.pipeline().addLast(new FirstClientHandler());
}
});
//4.建立连接
//Channel channel = boot.connect(new InetSocketAddress("127.0.0.1", 8000)).channel();
//此处连接有可能失败。因此需要有一定的重连机制
try {
ChannelFuture connect = connect(boot, "127.0.0.1", 8000, 5);
//写数据
// int i = 0;
// while (true){
// connect.channel().writeAndFlush("yangxuan"+i++);
// Thread.sleep(2000);
// }
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 通常情况下,连接建立失败不会立即重新建立连接,而是会通过一个指数退避的方式。
* 比如每个 1, 2, 4, 8, ...以2的次方来建立连接,然后重试一定次数后就放弃连接。
* 本方法重试5次
* @return
*/
private static ChannelFuture connect(Bootstrap boot, String host, int port, int retryCount){
return boot.connect(host, port).addListener(future -> {
if(future.isSuccess()){
System.out.println("客户端连接建立成功");
}else if(retryCount == 0){
System.out.println("重试连接次数已经用完,放弃连接");
throw new RuntimeException("重试连接次数已经用完,放弃连接");
}else{
//重连的次数
int count = MAX_RETRY - retryCount + 1;
System.out.println("连接失败,第"+ count +"次重连");
//重连的间隔
int delay = 1 << count;
boot.config().group().schedule(()->{connect(boot, host, port, retryCount - 1);}, delay, TimeUnit.SECONDS);
}
});
}
}
| [
"yangxuan_321@163.com"
] | yangxuan_321@163.com |
9245cfbba96a8a260da99eedcd02712faa5bccb3 | ff262ab7b962bd6980a68c298436a0db8cd6bfdd | /emt_lab_163179/src/main/java/com/example/emt_lab_163179/repository_persistence/impl/BookRepositoryInMemoryImpl.java | 49dabd66e4d216f258629e2dd47b8257c9ef77b1 | [] | no_license | NikolaMaroski/emt_lab_163179 | bda9e9496280eca8876f03593532933c8836f9a1 | 40dcde9b55411629d8e053ce6785521af3b40c20 | refs/heads/master | 2022-04-16T07:54:21.064826 | 2020-04-13T12:13:59 | 2020-04-13T12:13:59 | 255,188,545 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,183 | java | package com.example.emt_lab_163179.repository_persistence.impl;
import com.example.emt_lab_163179.model.Book;
import com.example.emt_lab_163179.repository_persistence.BookRepository;
import java.util.*;
import java.util.stream.Collectors;
import org.springframework.stereotype.Repository;
@Repository
public class BookRepositoryInMemoryImpl implements BookRepository {
private HashMap<Long, Book> books;
private Long counter;
public BookRepositoryInMemoryImpl() {
this.books = new HashMap<>();
this.counter = 0L;
Long id = this.generateKey();
this.books.put(id, new Book(id,"b1", 10L, null));
id = this.generateKey();
this.books.put(id, new Book(id,"b2", 20L, null));
id = this.generateKey();
this.books.put(id, new Book(id,"b3", 40L, null));
id = this.generateKey();
this.books.put(id, new Book(id,"b4", 15L, null));
}
private Long generateKey() {
return ++counter;
}
@Override
public List<Book> findAll() {
return new ArrayList<>(this.books.values());
}
@Override
public List<Book> findAllSortedNoS(boolean asc) {
Comparator<Book> priceComparator = Comparator.comparing(Book::getNumberSamples);
if(!asc){
priceComparator = priceComparator.reversed();
}
return this.books.values()
.stream()
.sorted(priceComparator)
.collect(Collectors.toList());
}
@Override
public List<Book> findByCategoryId(Long categoryId) {
return this.books.values()
.stream()
.filter(item -> item.getCategory().getId().equals(categoryId))
.collect(Collectors.toList());
}
@Override
public Optional<Book> findById(Long id) {
return Optional.ofNullable(this.books.get(id));
}
@Override
public Book save(Book book) {
if(book.getId() == null){
book.setId(this.generateKey());
}
this.books.put(book.getId(), book);
return book;
}
@Override
public void deleteById(Long id) {
this.books.remove(id);
}
}
| [
"nikolamaroski@hotmail.com"
] | nikolamaroski@hotmail.com |
4b2546aa15ce47bdac9251ab7d66544760a9741c | c3445da9eff3501684f1e22dd8709d01ff414a15 | /LIS/sinosoft-parents/lis-business/src/main/java_other/com/sinosoft/workflow/circ/ReportYWImportAfterInitService.java | d7c268330183d4225293fd9a21056414c375194a | [] | no_license | zhanght86/HSBC20171018 | 954403d25d24854dd426fa9224dfb578567ac212 | c1095c58c0bdfa9d79668db9be4a250dd3f418c5 | refs/heads/master | 2021-05-07T03:30:31.905582 | 2017-11-08T08:54:46 | 2017-11-08T08:54:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,229 | java | /**
* Copyright (c) 2002 sinosoft Co. Ltd.
* All right reserved.
*/
package com.sinosoft.workflow.circ;
import org.apache.log4j.Logger;
import java.util.Vector;
import com.sinosoft.lis.db.LFDesbModeDB;
import com.sinosoft.lis.db.LFItemRelaDB;
import com.sinosoft.lis.pubfun.GlobalInput;
import com.sinosoft.lis.pubfun.MMap;
import com.sinosoft.lis.pubfun.PubCalculator;
import com.sinosoft.lis.pubfun.PubFun;
import com.sinosoft.lis.pubfun.ReportPubFun;
import com.sinosoft.lis.schema.LFDesbModeSchema;
import com.sinosoft.lis.vschema.LFDesbModeSet;
import com.sinosoft.msreport.CalService;
import com.sinosoft.utility.CError;
import com.sinosoft.utility.CErrors;
import com.sinosoft.utility.SQLwithBindVariables;
import com.sinosoft.utility.TransferData;
import com.sinosoft.utility.VData;
import com.sinosoft.workflowengine.AfterInitService;
/**
* <p>Description: </p>
* <p>Copyright: SINOSOFT Copyright (c) 2004</p>
* <p>Company: 中科软科技</p>
* @author guoxiang
* @version 1.0
*/
public class ReportYWImportAfterInitService implements AfterInitService
{
private static Logger logger = Logger.getLogger(ReportYWImportAfterInitService.class);
/** 传入数据的容器 */
// private VData mInputData = new VData();
/** 传出数据的容器 */
private VData mResult = new VData();
/** 数据操作字符串 */
// private String mOperate;
/** 错误处理类 */
public CErrors mErrors = new CErrors();
/** 业务处理相关变量 */
private TransferData mTransferData = new TransferData();
private MMap mmap = new MMap();
// private String tOperate;
/** 全局数据 */
private GlobalInput mGlobalInput = new GlobalInput();
public ReportYWImportAfterInitService()
{
}
/**
* 传输数据的公共方法
* @param: cInputData 输入的数据
* cOperate 数据操作
* @return:
*/
public boolean submitData(VData cInputData, String cOperate)
{
// mOperate = cOperate;
// 得到外部传入的数据,将数据备份到本类中
if (!getInputData(cInputData))
{
return false;
}
// 处理提数逻辑
if (!dealData())
{
return false;
}
//准备公共提交数据
if (mmap != null && mmap.keySet().size() > 0)
{
mResult.add(mmap);
}
// 提交到BLS进行插入INSERT 处理
// ReportEngineBLS tReportEngineBLS = new ReportEngineBLS();
// if (!tReportEngineBLS.submitData(mResult, tOperate))
// {
// // @@错误处理
// this.mErrors.copyAllErrors(tReportEngineBLS.mErrors);
// buildError("submitData", "数据插入中间表失败!");
// mResult.clear();
//
// return false;
// }
// else
// {
// mResult = tReportEngineBLS.getResult();
// this.mErrors.copyAllErrors(tReportEngineBLS.mErrors);
// }
return true;
}
/**
* 根据前面的输入数据,进行BL逻辑处理
* 如果在处理过程中出错,则返回false,否则返回true
*/
private boolean dealData()
{
String tWhereSQLName = "WhereSQL";
String tWhereSQLValue = (String) mTransferData.getValueByName((Object)
tWhereSQLName)
.toString();
String[] KeyWord = PubFun.split(tWhereSQLValue, "||");
// 查找计算处理的记录
String strSQL = "SELECT * FROM LFDesbMode where 1=1"
+ ReportPubFun.getWherePart("ItemCode", ReportPubFun.getParameterStr(KeyWord[0], "?keyword0?"))
+ ReportPubFun.getWherePart("ItemNum", ReportPubFun.getParameterStr(KeyWord[1], "?keyword1?"))
+ " " + KeyWord[2];
logger.debug("通过前台的条件查询描述表:" + strSQL);
SQLwithBindVariables sqlbv = new SQLwithBindVariables();
sqlbv.sql(strSQL);
sqlbv.put("keyword0", KeyWord[0]);
sqlbv.put("keyword1", KeyWord[1]);
LFDesbModeSet tLFDesbModeSet = new LFDesbModeDB().executeQuery(sqlbv);
if (tLFDesbModeSet.size() == 0)
{
buildError("dealData", "查询描述表失败!");
return false;
}
mResult.clear();
for (int i = 1; i <= tLFDesbModeSet.size(); i++)
{
LFDesbModeSchema mLFDesbModeSchema = tLFDesbModeSet.get(i);
try
{
if (!CheckTransitionCondition(mLFDesbModeSchema, mTransferData))
{
return false;
}
}
catch (Exception ex)
{
ex.printStackTrace();
return false;
}
}
return true;
}
/**
* 校验转移条件是否满足
* @param: tLWProcessInstanceSchema 输入的当前描述实例 数据
* @param: tInputData 输入的辅助数据
* @return boolean:
*
*/
private boolean CheckTransitionCondition(LFDesbModeSchema tLFDesbModeSchema,
TransferData tTransferData) throws
Exception
{
if (tLFDesbModeSchema == null)
{
// @@错误处理
buildError("CheckTransitionCondition", "传入的信息为空");
return false;
}
if (tLFDesbModeSchema.getDealType().equals("S"))
{
//S-应用SQL语句进行处理
String insertSQL = "";
insertSQL = getInsertSQL(tLFDesbModeSchema, tTransferData);
mmap.put(insertSQL, "insert");
logger.debug("map:" + mmap);
logger.debug("size:" + mResult.size());
return true;
}
else if (tLFDesbModeSchema.getDealType().equals("C"))
{
//C -- 应用Class类进行处理
try
{
Class tClass = Class.forName(tLFDesbModeSchema
.getInterfaceClassName());
CalService tCalService = (CalService) tClass.newInstance();
// 准备数据
String strOperate = "";
VData tInputData = new VData();
tInputData.add(tTransferData);
tInputData.add(tLFDesbModeSchema);
if (!tCalService.submitData(tInputData, strOperate))
{
return false;
}
mResult = tCalService.getResult();
}
catch (Exception ex)
{
ex.printStackTrace();
return false;
}
}
return true;
}
private String getInsertSQL(LFDesbModeSchema tLFDesbModeSchema,
TransferData tTransferData)
{
PubCalculator tPubCalculator = new PubCalculator();
//准备计算要素
Vector tVector = (Vector) tTransferData.getValueNames();
String tNeedItemKeyName = "NeedItemKey";
String tNeedItemKeyValue = (String) tTransferData.getValueByName((
Object) tNeedItemKeyName)
.toString();
if (tNeedItemKeyName.equals("1")) //1-扩充要素
{
LFItemRelaDB tLFItemRelaDB = new LFItemRelaDB();
tLFItemRelaDB.setItemCode(tLFDesbModeSchema.getItemCode());
if (!tLFItemRelaDB.getInfo())
{
buildError("getInsertSQL", "查询内外科目编码对应表失败!");
return "0";
}
tPubCalculator.addBasicFactor("UpItemCode",
tLFItemRelaDB.getUpItemCode());
tPubCalculator.addBasicFactor("Layer",
String.valueOf(tLFItemRelaDB.getLayer()));
tPubCalculator.addBasicFactor("Remark", tLFItemRelaDB.getRemark());
}
//0-普通要素
for (int i = 0; i < tVector.size(); i++)
{
String tName = (String) tVector.get(i);
String tValue = (String) tTransferData.getValueByName((Object)
tName)
.toString();
tPubCalculator.addBasicFactor(tName, tValue);
}
//准备计算SQL
if ((tLFDesbModeSchema.getCalSQL1() == null)
|| (tLFDesbModeSchema.getCalSQL1().length() == 0))
{
tLFDesbModeSchema.setCalSQL1("");
}
if ((tLFDesbModeSchema.getCalSQL2() == null)
|| (tLFDesbModeSchema.getCalSQL2().length() == 0))
{
tLFDesbModeSchema.setCalSQL2("");
}
if ((tLFDesbModeSchema.getCalSQL3() == null)
|| (tLFDesbModeSchema.getCalSQL3().length() == 0))
{
tLFDesbModeSchema.setCalSQL3("");
}
String Calsql = tLFDesbModeSchema.getCalSQL()
+ tLFDesbModeSchema.getCalSQL1()
+ tLFDesbModeSchema.getCalSQL2()
+ tLFDesbModeSchema.getCalSQL3();
tPubCalculator.setCalSql(Calsql);
String strSQL = tPubCalculator.calculateEx();
logger.debug("从描述表取得的SQL : " + strSQL);
String insertSQL = "Insert Into ";
String insertTableName = tLFDesbModeSchema.getDestTableName();
String stsql = insertSQL + " " + insertTableName + " " + strSQL;
logger.debug("得到的insert SQL 语句: " + stsql);
return stsql;
}
/**
* 从输入数据中得到所有对象
* 输出:如果没有得到足够的业务数据对象,则返回false,否则返回true
*/
private boolean getInputData(VData cInputData)
{
//全局变量
mGlobalInput.setSchema((GlobalInput) cInputData.getObjectByObjectName(
"GlobalInput",
0));
mTransferData = (TransferData) cInputData.getObjectByObjectName(
"TransferData",
0);
if ((mGlobalInput == null) || (mTransferData == null))
{
buildError("getInputData", "没有得到足够的信息!");
return false;
}
return true;
}
/**
* 数据输出方法,供外界获取数据处理结果
* @return 包含有数据查询结果字符串的VData对象
*/
public VData getResult()
{
return mResult;
}
public TransferData getReturnTransferData()
{
return mTransferData;
}
public CErrors getErrors()
{
return mErrors;
}
/*
* add by kevin, 2002-10-14
*/
private void buildError(String szFunc, String szErrMsg)
{
CError cError = new CError();
cError.moduleName = "ReportEngineBL";
cError.functionName = szFunc;
cError.errorMessage = szErrMsg;
this.mErrors.addOneError(cError);
}
public static void main(String[] args)
{
}
}
| [
"dingzansh@sinosoft.com.cn"
] | dingzansh@sinosoft.com.cn |
aff2f913bbae2680212fcd0f4420679dbd4cd8de | 2ee541671155ada41d1edc78f72d38cc2254c2d5 | /Tere/Java Spring/Aplicacion/src/main/java/com/example/demo/ApplicationVariasPaginasWeb.java | b939551dd8831e5cb4be3193cf1a56b0d2b9d555 | [] | no_license | susoooo/IFCT06092019C3 | cff5b05a05701362151fd9a2dc131671fa15032a | a220af43dc845742a9e8b945aed47a3ff04a548e | refs/heads/master | 2022-12-12T18:16:24.869219 | 2020-09-22T11:41:38 | 2020-09-22T11:41:38 | 228,371,243 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,543 | java | /*1-Crea una aplicación web que tenga varias páginas.
2-Crea una aplicación que muestre el contenido de una página:
<iframe src="https://www.starwars.com" width="100%" height="80%"title="Que bien programao!!!"></iframe>
*/
package com.example.demo;
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class ApplicationVariasPaginasWeb {
public static void main(String[] args) {
SpringApplication.run(ApplicationVariasPaginasWeb.class, args);
}
@GetMapping("/hello")
public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
@GetMapping("/hasta luego")
public String hastaluego(@RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hasta luego %s!", name);
}
@GetMapping("/Adios")
public String Adios(@RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Adios %s!", name);
}
@GetMapping("/concellodelugo")
public String concellodelugo() {
return ("<iframe src=\"https://www.starwars.com\" width=\"100%\" height=\"80%\"title=\"Que bien programao!!!\"></iframe>");
}
}
| [
"trs.rguez@hotmail.com"
] | trs.rguez@hotmail.com |
25c5c22112e5f368799526f511277024638cb35c | 647ec12ce50f06e7380fdbfb5b71e9e2d1ac03b4 | /com.tencent.mm/classes.jar/com/tencent/mm/plugin/multitask/MultiTaskListParcel.java | 9d1297aa7fc561eff4438bb4788186345896f36b | [] | no_license | tsuzcx/qq_apk | 0d5e792c3c7351ab781957bac465c55c505caf61 | afe46ef5640d0ba6850cdefd3c11badbd725a3f6 | refs/heads/main | 2022-07-02T10:32:11.651957 | 2022-02-01T12:41:38 | 2022-02-01T12:41:38 | 453,860,108 | 36 | 9 | null | 2022-01-31T09:46:26 | 2022-01-31T02:43:22 | Java | UTF-8 | Java | false | false | 2,500 | java | package com.tencent.mm.plugin.multitask;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.Parcelable.Creator;
import com.tencent.matrix.trace.core.AppMethodBeat;
import com.tencent.mm.plugin.multitask.model.MultiTaskInfo;
import java.util.List;
import kotlin.Metadata;
import kotlin.g.b.s;
@Metadata(d1={""}, d2={"Lcom/tencent/mm/plugin/multitask/MultiTaskListParcel;", "Landroid/os/Parcelable;", "taskInfoList", "", "Lcom/tencent/mm/plugin/multitask/model/MultiTaskInfo;", "(Ljava/util/List;)V", "in", "Landroid/os/Parcel;", "(Landroid/os/Parcel;)V", "multiTaskInfoList", "getMultiTaskInfoList", "()Ljava/util/List;", "setMultiTaskInfoList", "describeContents", "", "writeToParcel", "", "dest", "flags", "Companion", "plugin-multitask_release"}, k=1, mv={1, 5, 1}, xi=48)
final class MultiTaskListParcel
implements Parcelable
{
public static final Parcelable.Creator<MultiTaskListParcel> CREATOR;
public static final MultiTaskListParcel.a LBb;
List<? extends MultiTaskInfo> LBc;
static
{
AppMethodBeat.i(303751);
LBb = new MultiTaskListParcel.a((byte)0);
CREATOR = (Parcelable.Creator)new b();
AppMethodBeat.o(303751);
}
protected MultiTaskListParcel(Parcel paramParcel)
{
AppMethodBeat.i(303741);
this.LBc = ((List)paramParcel.createTypedArrayList(MultiTaskInfo.CREATOR));
AppMethodBeat.o(303741);
}
public MultiTaskListParcel(List<? extends MultiTaskInfo> paramList)
{
this.LBc = paramList;
}
public final int describeContents()
{
return 0;
}
public final void writeToParcel(Parcel paramParcel, int paramInt)
{
AppMethodBeat.i(303768);
s.u(paramParcel, "dest");
paramParcel.writeTypedList(this.LBc);
AppMethodBeat.o(303768);
}
@Metadata(d1={""}, d2={"com/tencent/mm/plugin/multitask/MultiTaskListParcel$Companion$CREATOR$1", "Landroid/os/Parcelable$Creator;", "Lcom/tencent/mm/plugin/multitask/MultiTaskListParcel;", "createFromParcel", "in", "Landroid/os/Parcel;", "newArray", "", "size", "", "(I)[Lcom/tencent/mm/plugin/multitask/MultiTaskListParcel;", "plugin-multitask_release"}, k=1, mv={1, 5, 1}, xi=48)
public static final class b
implements Parcelable.Creator<MultiTaskListParcel>
{}
}
/* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mm\classes8.jar
* Qualified Name: com.tencent.mm.plugin.multitask.MultiTaskListParcel
* JD-Core Version: 0.7.0.1
*/ | [
"98632993+tsuzcx@users.noreply.github.com"
] | 98632993+tsuzcx@users.noreply.github.com |
0e0cecd35745a2761bf423708460bb5c2e9c711c | 6b2fe5c9548d6bee931f0da4d5ed778079076f5e | /MyApplication/app/src/main/java/com/example/aqqn/danboo_ver001/DANBOO.java | a9216658030c9873c036024605996529da427f63 | [] | no_license | aqqnman/DANBOO_Ver001 | 73647dddee39db6ac55c749c805db5f9c20b4aa1 | 8103c957e1519406fa133356a9d9b921567adfdf | refs/heads/master | 2021-01-18T14:10:48.117284 | 2014-09-12T16:19:20 | 2014-09-12T16:19:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,045 | java | package com.example.aqqn.danboo_ver001;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class DANBOO extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_danboo);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.danboo, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| [
"aqqnman@gmail.com"
] | aqqnman@gmail.com |
7648052fc5b0f73f89c0ce1adeccb42e59c8cb05 | 5979c398fba36235565e5748b4a2bd4c18187100 | /src/main/java/org/springframework/data/elasticsearch/annotations/Dynamic.java | a0bd128f9e8cb303294c855b0e65273089e27862 | [
"Apache-2.0"
] | permissive | jadepeng/spring-data-elasticsearch | d590b05d82f78bbdf96856372dd1ef14a1e1fa64 | 305d930870cfa6fa20e22d81c04f3800233c6a70 | refs/heads/main | 2023-07-18T08:04:32.228668 | 2021-08-30T19:37:04 | 2021-08-30T19:37:04 | 402,000,878 | 1 | 0 | Apache-2.0 | 2021-09-01T09:16:43 | 2021-09-01T09:16:43 | null | UTF-8 | Java | false | false | 1,641 | java | /*
* Copyright 2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.annotations;
/**
* Values for the {@code dynamic} mapping parameter.
*
* @author Sascha Woo
* @since 4.3
*/
public enum Dynamic {
/**
* New fields are added to the mapping.
*/
TRUE,
/**
* New fields are added to the mapping as
* <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/runtime.html">runtime fields</a>. These
* fields are not indexed, and are loaded from {@code _source} at query time.
*/
RUNTIME,
/**
* New fields are ignored. These fields will not be indexed or searchable, but will still appear in the
* {@code _source} field of returned hits. These fields will not be added to the mapping, and new fields must be added
* explicitly.
*/
FALSE,
/**
* If new fields are detected, an exception is thrown and the document is rejected. New fields must be explicitly
* added to the mapping.
*/
STRICT,
/**
* Inherit the dynamic setting from their parent object or from the mapping type.
*/
INHERIT
}
| [
"noreply@github.com"
] | jadepeng.noreply@github.com |
7665814d9b7a3c4f435cb42305651ecba9aa6a22 | 2b0dddbbe243035f7c0e0bab034b8c8fdf68c25f | /src/main/java/com/mock/project/entity/Grade.java | e3c7f5490c7298954a8ccdb26602263532aae45c | [] | no_license | TienPhongDX/MockProject_SchoolManagement | 999bd93d743f78d1bf6f933ccfb12d42c1e2f4d1 | a74862a77b74fa0a536f44c48b7e8a9ec6ec5c82 | refs/heads/main | 2023-07-12T01:02:27.067577 | 2021-08-13T09:41:53 | 2021-08-13T09:41:53 | 395,598,422 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 741 | java | package com.mock.project.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "Grade")
public class Grade implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@Column(name = "gradeID", nullable = false)
private int gradeID;
public Grade() {
// TODO Auto-generated constructor stub
}
public Grade(int gradeID) {
super();
this.gradeID = gradeID;
}
public int getGradeID() {
return gradeID;
}
public void setGradeID(int gradeID) {
this.gradeID = gradeID;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
| [
"42340547+TienPhongDX@users.noreply.github.com"
] | 42340547+TienPhongDX@users.noreply.github.com |
b77a8370f5379dbde5e63ed17514405492f7316f | 74b6528825a5b0d216fb982ff49ea0dfb4935d2f | /app/src/main/java/com/stackoverflow/MainActivity.java | d929999cd503899b9d9d3f97be0fbac3b977a7a8 | [] | no_license | Shekhar14o3/ViewPagerWithFragment | b28aba4d9c95b4804b38cd04d957a821d3edd0cb | 6fe37bd9d4d74ba1e5953769d7f1d783ebc7f5df | refs/heads/master | 2021-01-11T22:38:02.350507 | 2017-01-15T06:28:36 | 2017-01-15T06:28:36 | 79,005,584 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,281 | java | package com.stackoverflow;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager=(ViewPager)findViewById(R.id.vpPager);
viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return ScienceFragment.newInstance(0, "Science");
case 1: return SimpleFragment.newInstance(1, "Simple");
default: return ScienceFragment.newInstance(0, "Default");
}
}
@Override
public int getCount() {
return 2;
}
}
} | [
"aman.shekhar4@gmail.com"
] | aman.shekhar4@gmail.com |
55786779af15d1ba82b9b41b057e4656c89c9b21 | 677ebfe91168cbe02c8c0b4cb524b75cd5e98102 | /src/tabele/biblioteka/ba/fet/TAutorRBr.java | 731919daa7b31e2928df01dec39b2a06a954e158 | [] | no_license | dinooo/biblioteka | 6e3724c42d319d8fa130c11d2c0829c89e7a1606 | 01478ab8fa0c0a7e024cc0f7952af5621134c336 | refs/heads/master | 2020-04-09T14:18:20.907598 | 2016-10-26T10:42:04 | 2016-10-26T10:42:04 | 68,045,021 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,102 | java | package tabele.biblioteka.ba.fet;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import modeli.biblioteka.ba.fet.MAutorRBr;
public class TAutorRBr {
public static ArrayList<MAutorRBr> listaAutoraRBr = new ArrayList<>();
/*
* Sljedeci metod iz tabele Autor iz BP kupi sve autore i snima u iznad kreiranu listu autora
*/
public static ArrayList<MAutorRBr> getListaAutoraRBr(ResultSet rs) throws SQLException{
/*
* prolazimo kroz sve n-torke iz tabele
*/
while (rs.next()) {
/*
* Kreiramo varijablu autor, u koju cemo upisati jednu n-torku
*/
MAutorRBr pom = new MAutorRBr();
/*
* rs.getInt("sifAutor") kupi iz trenutne n-torke vrijednost za kolonu "sifAutor" itd, i onda
* to upisuje u varijablu pom sa setterom.
*/
pom.setSifAutorRBr(rs.getInt("sifAutorRBr"));
pom.setRBrAutora(rs.getInt("rBrAutora"));
/*
* U kreirani vektor upisujemo dohvacenu n-torku koja je smjestena u "pom"
*/
listaAutoraRBr.add(pom);
}
/*
* Vracamo listu autora
*/
return listaAutoraRBr;
}
}
| [
"dinooo_06@hotmail.com"
] | dinooo_06@hotmail.com |
3a013905320bcb37e199eeb05173d10fe6732879 | 1b27119537149cb5608e651004fe78a7c819a45b | /src/main/java/com/mx/bancoazteca/pld/security/Usuario.java | 8739e0c908488789cead4321cd2ca2a0b4c742f3 | [] | no_license | saimar/test2 | 3d0c3464b539299ac273dc74deff4a6596344295 | 384d77eb0d920104a5ca92c6b376cfbe03a2ec2f | refs/heads/master | 2021-01-23T02:22:55.482013 | 2017-03-23T18:38:10 | 2017-03-23T18:38:10 | 85,984,495 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,216 | java | package com.mx.bancoazteca.pld.security;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
public class Usuario implements IUsuario {
public static final long serialVersionUID = 9L;
//private static final Logger LOG = LoggerFactory.getLogger(Usuario.class);
private String usrLLaveMaestra = null;
private String nombreCompleto = null;
private String compania = null;
private String mail = null;
private String ipAsignada = null;
private String numeroEmpleado = null;
public String getUsrLLaveMaestra() {
return usrLLaveMaestra;
}
public void setUsrLLaveMaestra(String usrLLaveMaestra) {
this.usrLLaveMaestra = usrLLaveMaestra;
}
public String getNombreCompleto() {
return nombreCompleto;
}
public void setNombreCompleto(String nombreCompleto) {
this.nombreCompleto = nombreCompleto;
}
public String getCompania() {
return compania;
}
public void setCompania(String compania) {
this.compania = compania;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getIpAsignada() {
return ipAsignada;
}
public void setIpAsignada(String ipAsignada) {
this.ipAsignada = ipAsignada;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public void setNumeroEmpleado(String numeroEmpleado) {
this.numeroEmpleado=numeroEmpleado;
}
public String getNumeroEmpleado() {
return numeroEmpleado;
}
public void setNombre(String s) {
// TODO Auto-generated method stub
}
public String getNombre() {
// TODO Auto-generated method stub
return null;
}
public void setApPaterno(String s) {
// TODO Auto-generated method stub
}
public String getApPaterno() {
// TODO Auto-generated method stub
return null;
}
public void setApMaterno(String s) {
// TODO Auto-generated method stub
}
public String getApMaterno() {
// TODO Auto-generated method stub
return null;
}
public void setApCasada(String s) {
// TODO Auto-generated method stub
}
public String getApCasada() {
// TODO Auto-generated method stub
return null;
}
public boolean credencialExpiro() {
// TODO Auto-generated method stub
return false;
}
}
| [
"smoralesle@elektra.com"
] | smoralesle@elektra.com |
3f947e71cd0661ef3a9b84b74279c24168c2571e | 0663341bbd06cd4fb953457e59c348a36b2e42ca | /HibernateCriteria/src/main/java/com/service/employee/HibernateUtil.java | a7af0447b78a4570384eba2f1d1aea893a6f2547 | [] | no_license | Sri-va/Revature | 559419e7342e59cc0cb8b92d6dd7b408874aeddd | d6d6a6ada5913ebd23f8a20a5bacc896b85eaec9 | refs/heads/master | 2023-07-10T16:48:04.621123 | 2021-08-13T06:11:14 | 2021-08-13T06:11:14 | 377,751,562 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,954 | java | package com.service.employee;
import java.util.Properties;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
try {
Configuration configuration = new Configuration();
// Hibernate settings equivalent to hibernate.cfg.xml's properties
Properties settings = new Properties();
settings.put(Environment.DRIVER, "org.postgresql.Driver");
settings.put(Environment.URL, "jdbc:postgresql://database-1.czhcku1df67r.us-east-2.rds.amazonaws.com:5432/forHibernate");
settings.put(Environment.USER, "postgres");
settings.put(Environment.PASS, "Srivatsan123");
settings.put(Environment.DIALECT, "org.hibernate.dialect.PostgreSQLDialect");
settings.put(Environment.SHOW_SQL, "true");
settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
settings.put(Environment.HBM2DDL_AUTO, "update");
configuration.setProperties(settings);
configuration.addAnnotatedClass(Employee.class);
configuration.addAnnotatedClass(SupportCase.class);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
e.printStackTrace();
}
}
return sessionFactory;
}
} | [
"shrasri15@gmail.com"
] | shrasri15@gmail.com |
52429891a9ece75f55b5551f36dbce67dc917ef6 | 6518c78e9f96dd823d65fb2580b193f83b1c9897 | /src/main/java/com/massivedisaster/bintraydeployautomator/output/BarProgress.java | f0f022c463355c4cebfa2860972dae85afcbec8e | [
"MIT"
] | permissive | massivedisaster/bintray-deploy-automator | 4114595b12606a0be0dc75ea91f18815aae1448a | 72f42ba8807b781cb04ac42d40b650357af5ae3d | refs/heads/master | 2021-01-21T17:22:37.256110 | 2018-02-27T12:18:47 | 2018-02-27T12:18:47 | 91,946,976 | 1 | 0 | MIT | 2018-02-27T12:19:12 | 2017-05-21T09:45:35 | Java | UTF-8 | Java | false | false | 918 | java | package com.massivedisaster.bintraydeployautomator.output;
import me.tongfei.progressbar.ProgressBar;
public class BarProgress implements IProgress {
private ProgressBar mPb = null;
@Override
public void setup(String name, int steps) {
mPb = new ProgressBar(name, steps);
}
private void validateSetupCalled() {
if (mPb == null) {
throw new ExceptionInInitializerError("It's necessary to call BarProgress.setup first");
}
}
@Override
public void logMessage(String message) {
validateSetupCalled();
mPb.setExtraMessage(message);
}
@Override
public void start() {
validateSetupCalled();
mPb.start();
}
@Override
public void step() {
validateSetupCalled();
mPb.step();
}
@Override
public void stop() {
validateSetupCalled();
mPb.stop();
}
}
| [
"andrer757@gmail.com"
] | andrer757@gmail.com |
9bd8ba0d948968c40cda0210e3645f77bb50d9ee | 6a3597814b7558aa8c876dd388ecedb0f5ce53a2 | /src/main/java/com/tenpay/demo/QrCode.java | 25686ccee28136c80f514f1896bbcd095b95e10a | [] | no_license | windmill1992/home | 55ce83063dcbc47b177b7d8311d019663db37397 | 73d420cbde617779f0292d0f4b3716d19d8c64ce | refs/heads/master | 2021-04-30T14:00:40.095688 | 2018-02-12T02:58:55 | 2018-02-12T02:58:55 | 121,207,163 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 10,916 | java | package com.tenpay.demo;
/**
* 项目名称:weixinpay
*
* @description:二维码生成<br>
* 注意生成二维码和解析过程中的编码必须为GBK,否则解析过程会出错。
*
* @author spg
*
*
* @version V1.0.0
*
*/
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class QrCode
{
/**
* 二维码宽高度默认200
*/
private static final int DEFAULT_IMAGE_WIDTH = 300;
private static final int DEFAULT_IMAGE_HEIGHT = 300;
/**
* 生成带图片二维码时内部图片大小
*/
private static final int INNER_IMAGE_WIDTH = 60;
private static final int INNER_IMAGE_HEIGHT = 60;
private static final int IMAGE_HALF_WIDTH = INNER_IMAGE_WIDTH / 2;
private static final int FRAME_WIDTH = 2;
/**
* 生成普通二维码
*
* @param contents 内容
* @param width 二维码宽度,如果小于0,则按默认大小生成
* @param height 二维码高度,如果小于0,则按默认大小生成
* @param imgPath 生成后的文件完整存放路径,包含文件名。形如D:\aa.jpg
*/
public static void encodePR(String contents, int width, int height,
String imgPath)
{
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
// 指定纠错等级
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
// 指定编码格式
hints.put(EncodeHintType.CHARACTER_SET, "GBK");
if (width <= 0 || height <= 0)
{
width = DEFAULT_IMAGE_WIDTH;
height = DEFAULT_IMAGE_HEIGHT;
}
try
{
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
BarcodeFormat.QR_CODE, width, height, hints);
MatrixToImageWriter.writeToStream(bitMatrix, "jpg",
new FileOutputStream(imgPath));
} catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 生成带图片的二维码
*
* @param content
* @param width
* @param height
* @param srcImagePath
* @param destImagePath
*/
public static void encodePR(String content, int width, int height,
String srcImagePath, String destImagePath)
{
try
{
ImageIO.write(genBarcode(content, width, height, srcImagePath),
"jpg", new File(destImagePath));
} catch (IOException e)
{
e.printStackTrace();
} catch (WriterException e)
{
e.printStackTrace();
}
}
/**
* 把传入的原始图像按高度和宽度进行缩放,生成符合要求的图标
*
* @param srcImageFile
* 源文件地址
* @param height
* 目标高度
* @param width
* 目标宽度
* @param hasFiller
* 比例不对时是否需要补白:true为补白; false为不补白;
* @throws IOException
*/
private static BufferedImage scale(String srcImageFile, int height,
int width, boolean hasFiller) throws IOException
{
double ratio = 0.0; // 缩放比例
File file = new File(srcImageFile);
BufferedImage srcImage = ImageIO.read(file);
Image destImage = srcImage.getScaledInstance(width, height,
BufferedImage.SCALE_SMOOTH);
// 计算比例
if ((srcImage.getHeight() > height) || (srcImage.getWidth() > width))
{
if (srcImage.getHeight() > srcImage.getWidth())
{
ratio = (new Integer(height)).doubleValue()
/ srcImage.getHeight();
} else
{
ratio = (new Integer(width)).doubleValue()
/ srcImage.getWidth();
}
AffineTransformOp op = new AffineTransformOp(
AffineTransform.getScaleInstance(ratio, ratio), null);
destImage = op.filter(srcImage, null);
}
if (hasFiller)
{// 补白
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D graphic = image.createGraphics();
graphic.setColor(Color.white);
graphic.fillRect(0, 0, width, height);
if (width == destImage.getWidth(null))
graphic.drawImage(destImage, 0,
(height - destImage.getHeight(null)) / 2,
destImage.getWidth(null), destImage.getHeight(null),
Color.white, null);
else
graphic.drawImage(destImage,
(width - destImage.getWidth(null)) / 2, 0,
destImage.getWidth(null), destImage.getHeight(null),
Color.white, null);
graphic.dispose();
destImage = image;
}
return (BufferedImage) destImage;
}
/**
* 产生带有图片的二维码缓冲图像
*
* @param content
* @param width
* @param height
* @param srcImagePath
* @return
* @throws WriterException
* @throws IOException
*/
public static BufferedImage genBarcode(String content, int width,
int height, String srcImagePath) throws WriterException,
IOException
{
// 读取源图像
BufferedImage scaleImage = scale(srcImagePath, INNER_IMAGE_WIDTH,
INNER_IMAGE_HEIGHT, true);
int[][] srcPixels = new int[INNER_IMAGE_WIDTH][INNER_IMAGE_HEIGHT];
for (int i = 0; i < scaleImage.getWidth(); i++)
{
for (int j = 0; j < scaleImage.getHeight(); j++)
{
srcPixels[i][j] = scaleImage.getRGB(i, j);
}
}
Map<EncodeHintType, Object> hint = new HashMap<EncodeHintType, Object>();
hint.put(EncodeHintType.CHARACTER_SET, "GBK");
hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// 生成二维码
MultiFormatWriter mutiWriter = new MultiFormatWriter();
BitMatrix matrix = mutiWriter.encode(content, BarcodeFormat.QR_CODE,
width, height, hint);
// 二维矩阵转为一维像素数组
int halfW = matrix.getWidth() / 2;
int halfH = matrix.getHeight() / 2;
int[] pixels = new int[width * height];
for (int y = 0; y < matrix.getHeight(); y++)
{
for (int x = 0; x < matrix.getWidth(); x++)
{
// 读取图片
if (x > halfW - IMAGE_HALF_WIDTH
&& x < halfW + IMAGE_HALF_WIDTH
&& y > halfH - IMAGE_HALF_WIDTH
&& y < halfH + IMAGE_HALF_WIDTH)
{
pixels[y * width + x] = srcPixels[x - halfW
+ IMAGE_HALF_WIDTH][y - halfH + IMAGE_HALF_WIDTH];
}
// 在图片四周形成边框
else if ((x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH
&& x < halfW - IMAGE_HALF_WIDTH + FRAME_WIDTH
&& y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH
+ IMAGE_HALF_WIDTH + FRAME_WIDTH)
|| (x > halfW + IMAGE_HALF_WIDTH - FRAME_WIDTH
&& x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH
&& y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH
+ IMAGE_HALF_WIDTH + FRAME_WIDTH)
|| (x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH
&& x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH
&& y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH
- IMAGE_HALF_WIDTH + FRAME_WIDTH)
|| (x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH
&& x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH
&& y > halfH + IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH
+ IMAGE_HALF_WIDTH + FRAME_WIDTH))
{
pixels[y * width + x] = 0xfffffff;
} else
{
// 此处可以修改二维码的颜色,可以分别制定二维码和背景的颜色;
pixels[y * width + x] = matrix.get(x, y) ? 0xff000000
: 0xfffffff;
}
}
}
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
image.getRaster().setDataElements(0, 0, width, height, pixels);
return image;
}
public static void main(String[] args)
{
String value=null;
// 带图片的二维的生成与解析
if(value == null){
value="no";
}
value=System.getProperty("user.dir");
String contents2 = "weixin://wxpay/bizpayurl?pr=9yDaupc";
String imgPath = System.getProperty("user.dir")+"/src/main/webapp/res/images/charge/wx-pay-code.jpg";
String srcPath = System.getProperty("user.dir")+"/src/main/webapp/res/images/charge/logo-pay.png";
QrCode.encodePR(contents2, 300, 300, srcPath, imgPath);
System.out.println(value);
}
} | [
"404036704@qq.com"
] | 404036704@qq.com |
285ee1ce262e3fa94b2d4ea78125d280efa2cf12 | 6018fc9c1cfc9c2aa32056f32ec12c9f82ed4d37 | /project/src/customerinterface.java | 567f9c3dc760dbffcc4c060506bba8405d4c1e6d | [] | no_license | DhananjayaSLIIT/Aronway-Hotel | 802d3b9078e40e6b207adb99bcad50f22550f7eb | ed1a298d8589ec85a435f700a3ef22fc8fac7fb6 | refs/heads/master | 2023-06-06T22:21:06.432744 | 2021-07-17T20:57:45 | 2021-07-17T20:57:45 | 386,772,000 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 35,542 | java |
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import net.proteanit.sql.DbUtils;
public class customerinterface extends javax.swing.JFrame {
public customerinterface() {
initComponents();
Show_customers_in_table();
}
String indate;
String outdate;
String roomno;
String amount;
String adults;
String kids;
public customerinterface(String v1,String v2,String v3,String v4,String v5,String v6){
initComponents();
this.indate = v1;
this.outdate = v2;
this.roomno = v3;
this.amount = v4;
this.adults = v5;
this.kids = v6;
}
//Database Connectiom
public Connection getConnection(){
Connection con;
try{
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/itp", "root", "");
return con;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
//retrive and store data in a arraylist
public ArrayList<Customer> getcustomerList(){
ArrayList<Customer> customerList = new ArrayList<Customer>();
Connection connection = getConnection();
String query = "Select * from customer";
Statement st;
ResultSet rs;
try{
st = connection.createStatement();
rs= st.executeQuery(query);
Customer customer;
while(rs.next()){
customer = new Customer(rs.getString("NIC"),rs.getString("Name"),rs.getString("Address"),rs.getString("Phone"), rs.getString("Email"));
customerList.add(customer);
}
}catch(Exception e){
e.printStackTrace();
}
return customerList;
}
//Display data in table
public void Show_customers_in_table(){
ArrayList<Customer> customerList = getcustomerList();
DefaultTableModel model = (DefaultTableModel)jTableCustomer.getModel();
Object[] row = new Object[5];
for(int i = 0; i < customerList.size(); i++){
row[0] = customerList.get(i).getNIC();
row[1] = customerList.get(i).getName();
row[2] = customerList.get(i).getAddress();
row[3] = customerList.get(i).getMobile();
row[4] = customerList.get(i).getEmail();
model.addRow(row);
}
}
public void executeSqlQuery(String query, String message){
Connection con = getConnection();
Statement st;
try{
st = con.createStatement();
if((st.executeUpdate(query))==1){
JOptionPane.showMessageDialog(null,"Data "+message+" Successfully");
}else{
JOptionPane.showMessageDialog(null,"Data not "+message);
}
}catch(Exception e){
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTableCustomer = new javax.swing.JTable();
jPanel1 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jTextFieldNIC = new javax.swing.JTextField();
jTextFieldName = new javax.swing.JTextField();
jTextFieldAddress = new javax.swing.JTextField();
jTextFieldMobile = new javax.swing.JTextField();
jTextFieldEmail = new javax.swing.JTextField();
jButtonAdd = new javax.swing.JButton();
jButtonUpdate = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
jLabel7 = new javax.swing.JLabel();
jPanel4 = new javax.swing.JPanel();
b6 = new javax.swing.JButton();
b2 = new javax.swing.JButton();
b3 = new javax.swing.JButton();
b4 = new javax.swing.JButton();
b7 = new javax.swing.JButton();
b5 = new javax.swing.JButton();
b8 = new javax.swing.JButton();
b1 = new javax.swing.JButton();
b9 = new javax.swing.JButton();
jButtonbacktoavailablerooms = new javax.swing.JButton();
jButtonconfirmbooking = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTableCustomer.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
jTableCustomer.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"NIC", "Name", "Address", "Mobile", "Email"
}
));
jTableCustomer.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTableCustomerMouseClicked(evt);
}
});
jScrollPane1.setViewportView(jTableCustomer);
if (jTableCustomer.getColumnModel().getColumnCount() > 0) {
jTableCustomer.getColumnModel().getColumn(2).setResizable(false);
}
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Customer", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel2.setText("NIC");
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel3.setText("Name");
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel4.setText("Address");
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel5.setText("Mobile");
jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel6.setText("Email");
jTextFieldNIC.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jTextFieldNICKeyReleased(evt);
}
});
jTextFieldName.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextFieldNameActionPerformed(evt);
}
});
jButtonAdd.setText("Add");
jButtonAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonAddActionPerformed(evt);
}
});
jButtonUpdate.setText("Update");
jButtonUpdate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonUpdateActionPerformed(evt);
}
});
jButton1.setText("Clear");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextFieldEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(jLabel3)
.addComponent(jLabel2)
.addComponent(jLabel5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jTextFieldMobile, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 143, Short.MAX_VALUE)
.addComponent(jTextFieldNIC)
.addComponent(jTextFieldAddress)
.addComponent(jTextFieldName))
.addContainerGap())
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButtonAdd)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE)
.addComponent(jButtonUpdate)
.addGap(18, 18, 18)
.addComponent(jButton1)
.addContainerGap(27, Short.MAX_VALUE))))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jTextFieldNIC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(21, 21, 21)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jTextFieldName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextFieldAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(34, 34, 34)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextFieldMobile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5))
.addGap(37, 37, 37)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(jTextFieldEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(44, 44, 44)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonAdd)
.addComponent(jButtonUpdate)
.addComponent(jButton1))
.addGap(10, 10, 10))
);
jPanel3.setBackground(new java.awt.Color(0, 0, 153));
jLabel7.setFont(new java.awt.Font("Tahoma", 1, 48)); // NOI18N
jLabel7.setText("HOTEL ARONWAY");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(299, 299, 299)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 445, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(50, Short.MAX_VALUE))
);
jPanel4.setBackground(new java.awt.Color(0, 153, 102));
b6.setBackground(new java.awt.Color(0, 102, 102));
b6.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
b6.setForeground(new java.awt.Color(255, 255, 255));
b6.setText("Inventory");
b6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b6ActionPerformed(evt);
}
});
b2.setBackground(new java.awt.Color(0, 102, 102));
b2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
b2.setForeground(new java.awt.Color(255, 255, 255));
b2.setText("Hall Reservation");
b2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b2ActionPerformed(evt);
}
});
b3.setBackground(new java.awt.Color(0, 102, 102));
b3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
b3.setForeground(new java.awt.Color(255, 255, 255));
b3.setText("Room Reservation");
b3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b3ActionPerformed(evt);
}
});
b4.setBackground(new java.awt.Color(0, 102, 102));
b4.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
b4.setForeground(new java.awt.Color(255, 255, 255));
b4.setText("Menus");
b4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b4ActionPerformed(evt);
}
});
b7.setBackground(new java.awt.Color(0, 102, 102));
b7.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
b7.setForeground(new java.awt.Color(255, 255, 255));
b7.setText("Orders");
b7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b7ActionPerformed(evt);
}
});
b5.setBackground(new java.awt.Color(0, 102, 102));
b5.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
b5.setForeground(new java.awt.Color(255, 255, 255));
b5.setText("Payment");
b5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b5ActionPerformed(evt);
}
});
b8.setBackground(new java.awt.Color(0, 102, 102));
b8.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
b8.setForeground(new java.awt.Color(255, 255, 255));
b8.setText("Travel Package");
b8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b8ActionPerformed(evt);
}
});
b1.setBackground(new java.awt.Color(0, 102, 102));
b1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
b1.setForeground(new java.awt.Color(255, 255, 255));
b1.setText("Employees");
b1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
b1MouseClicked(evt);
}
});
b1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b1ActionPerformed(evt);
}
});
b9.setBackground(new java.awt.Color(0, 102, 102));
b9.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
b9.setForeground(new java.awt.Color(255, 255, 255));
b9.setText("Expenses");
b9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b9ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(b6, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(b2, javax.swing.GroupLayout.DEFAULT_SIZE, 164, Short.MAX_VALUE)
.addComponent(b3, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addComponent(b4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(b7, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(b5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(b8, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(b1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(b9, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(26, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(190, 190, 190)
.addComponent(b6, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(31, 31, 31)
.addComponent(b2, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(31, 31, 31)
.addComponent(b3, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addComponent(b4, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addComponent(b7, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(32, 32, 32)
.addComponent(b5, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(29, 29, 29)
.addComponent(b8, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(29, 29, 29)
.addComponent(b1, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addComponent(b9, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(211, Short.MAX_VALUE))
);
jButtonbacktoavailablerooms.setText("Back");
jButtonbacktoavailablerooms.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonbacktoavailableroomsActionPerformed(evt);
}
});
jButtonconfirmbooking.setText("Confirm");
jButtonconfirmbooking.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonconfirmbookingActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButtonbacktoavailablerooms, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(47, 47, 47)
.addComponent(jButtonconfirmbooking)
.addGap(104, 104, 104))
.addComponent(jPanel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1314, Short.MAX_VALUE)
.addGap(66, 66, 66))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(80, 80, 80)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 694, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(234, 234, 234)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonbacktoavailablerooms, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButtonconfirmbooking, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(21, 21, 21))
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
setBounds(0, 0, 1947, 1032);
}// </editor-fold>//GEN-END:initComponents
private void jTableCustomerMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableCustomerMouseClicked
int i = jTableCustomer.getSelectedRow();
TableModel model = jTableCustomer.getModel();
jTextFieldNIC.setText(model.getValueAt(i, 0).toString());
jTextFieldName.setText(model.getValueAt(i, 1).toString());
jTextFieldAddress.setText(model.getValueAt(i, 2).toString());
jTextFieldMobile.setText(model.getValueAt(i, 3).toString());
jTextFieldEmail.setText(model.getValueAt(i, 4).toString());
jButtonAdd.setEnabled(false);
}//GEN-LAST:event_jTableCustomerMouseClicked
private void jButtonUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonUpdateActionPerformed
String query = "update customer set Name='"+jTextFieldName.getText()+"',Address='"+jTextFieldAddress.getText()+"',Phone='"+jTextFieldMobile.getText()+"',Email='"+jTextFieldEmail.getText()+"' where NIC='"+jTextFieldNIC.getText()+"'";
executeSqlQuery(query,"Updated");
DefaultTableModel model = (DefaultTableModel)jTableCustomer.getModel();
model.setRowCount(0);
Show_customers_in_table();
}//GEN-LAST:event_jButtonUpdateActionPerformed
private void jButtonAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAddActionPerformed
Connection con = getConnection();
Statement st ;
String query = "select count(*) from customer where NIC='"+jTextFieldNIC.getText()+"'";
try{
st = con.createStatement();
ResultSet rs = st.executeQuery(query);
if(rs.next()==false){
JOptionPane.showMessageDialog(null,"Customer exist!");
}
else{
String query2 = "INSERT INTO `customer`(`NIC`, `Name`, `Phone`, `Address`,`Email`) VALUES ('"+jTextFieldNIC.getText()+"','"+jTextFieldName.getText()+"','"+jTextFieldMobile.getText()+"','"+jTextFieldAddress.getText()+"','"+jTextFieldEmail.getText()+"')";
executeSqlQuery(query2,"Inserted");
DefaultTableModel model = (DefaultTableModel)jTableCustomer.getModel();
model.setRowCount(0);
Show_customers_in_table();
}
}catch(Exception e){
e.printStackTrace();
}
}//GEN-LAST:event_jButtonAddActionPerformed
public void search(){
String search = jTextFieldNIC.getText();
Connection connection = getConnection();
try{
String query2 = "select NIC,Name,Address,Phone as Mobile,Email from customer where NIC like '%"+search+"%' or Name like '%"+search+"%'";
Statement st2 = connection.createStatement();
ResultSet rs2 = st2.executeQuery(query2);
jTableCustomer.setModel(DbUtils.resultSetToTableModel(rs2));
}catch(Exception e){
e.printStackTrace();
}
}
private void jTextFieldNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldNameActionPerformed
}//GEN-LAST:event_jTextFieldNameActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
jTextFieldNIC.setText(null);
jTextFieldName.setText(null);
jTextFieldAddress.setText(null);
jTextFieldMobile.setText(null);
jTextFieldEmail.setText(null);
jButtonAdd.setEnabled(true);
}//GEN-LAST:event_jButton1ActionPerformed
private void jButtonbacktoavailableroomsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonbacktoavailableroomsActionPerformed
availablerooms ai = new availablerooms();
ai.setVisible(true);
this.dispose();
}//GEN-LAST:event_jButtonbacktoavailableroomsActionPerformed
private void jButtonconfirmbookingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonconfirmbookingActionPerformed
try{
String query3 = "INSERT INTO `roomreservation`(`Amount`,`NoKids`,`Cus_NIC`,`NoAdults`,`RoomNo`,`CheckIn`,`CheckOut`)VALUES('"+amount+"','"+kids+"','"+jTextFieldNIC.getText()+"','"+adults+"','"+roomno+"','"+indate+"','"+outdate+"')";
executeSqlQuery(query3,"Inserted");
availablerooms ai = new availablerooms();
ai.setVisible(true);
this.dispose();
}catch(Exception e){
e.printStackTrace();
}
}//GEN-LAST:event_jButtonconfirmbookingActionPerformed
private void jTextFieldNICKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldNICKeyReleased
search();
}//GEN-LAST:event_jTextFieldNICKeyReleased
private void b6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b6ActionPerformed
// TODO add your handling code here:
ingridient i = new ingridient();
i.setVisible(true);
}//GEN-LAST:event_b6ActionPerformed
private void b2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b2ActionPerformed
// TODO add your handling code here:
HallReservation h = new HallReservation();
h.setVisible(true);
}//GEN-LAST:event_b2ActionPerformed
private void b3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b3ActionPerformed
availablerooms r = new availablerooms();
r.setVisible(true);
}//GEN-LAST:event_b3ActionPerformed
private void b4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b4ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_b4ActionPerformed
private void b7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b7ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_b7ActionPerformed
private void b5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b5ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_b5ActionPerformed
private void b8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b8ActionPerformed
// TODO add your handling code here:
travelInterface t = new travelInterface();
t.setVisible(true);
}//GEN-LAST:event_b8ActionPerformed
private void b1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_b1MouseClicked
// TODO add your handling code here:
}//GEN-LAST:event_b1MouseClicked
private void b1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_b1ActionPerformed
private void b9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b9ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_b9ActionPerformed
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(customerinterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(customerinterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(customerinterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(customerinterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new customerinterface().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton b1;
private javax.swing.JButton b2;
private javax.swing.JButton b3;
private javax.swing.JButton b4;
private javax.swing.JButton b5;
private javax.swing.JButton b6;
private javax.swing.JButton b7;
private javax.swing.JButton b8;
private javax.swing.JButton b9;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButtonAdd;
private javax.swing.JButton jButtonUpdate;
private javax.swing.JButton jButtonbacktoavailablerooms;
private javax.swing.JButton jButtonconfirmbooking;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTableCustomer;
private javax.swing.JTextField jTextFieldAddress;
private javax.swing.JTextField jTextFieldEmail;
private javax.swing.JTextField jTextFieldMobile;
private javax.swing.JTextField jTextFieldNIC;
private javax.swing.JTextField jTextFieldName;
// End of variables declaration//GEN-END:variables
}
| [
"softregister@gmail.com"
] | softregister@gmail.com |
bf5187569959196ca6e4b0cd40b70358cc4ffc88 | 22558f08fcfd1e1cd3f944045d8ac885a2ab450e | /src/maps/main/spells/mortraBlink.java | c611c965f5f31c42a3c5f55411dc90dde18870d7 | [] | no_license | artem8086/DotaPrototypeGDX | 09c7da538ae94f486cb408b59822f2b47c505a1e | 5c22d88a2aa9d8f85caf775e8c08c257a258c63e | refs/heads/master | 2020-04-02T13:44:10.678337 | 2018-10-24T12:10:12 | 2018-10-24T12:10:12 | 154,494,531 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,422 | java | package maps.main.spells;
import art.soft.Game;
import art.soft.units.Attack;
import art.soft.units.Unit;
import art.soft.utils.Image;
import art.soft.utils.Point;
import art.soft.spells.Damage;
import art.soft.spells.Effect;
/**
*
* @author Артем
*/
public class mortraBlink extends Effect {
public Effect effect;
@Override
public void Load(){
super.Load();
effect.Load();
}
@Override
public void setOwner(Unit u){
if (effect!=null) effect.setOwner(u);
super.setOwner(u);
}
@Override
public Effect copy(Effect e){
mortraBlink ef = (mortraBlink) super.copy(e);
ef.effect = effect.copy();
return ef;
}
@Override
public void setLevel(int lvl){
setCooldownTime((5 - lvl) * 5000);
effect.setLevel(lvl);
super.setLevel(lvl);
}
@Override
public Image getIcon(){
return effect.Icon;
}
@Override
public int attackDamageAim(Unit u, Unit aim){
Attack.type = Damage.TYPE_NONE;
Point p = Game.map.teleportRayCast(u.px, u.py, aim.px, aim.py, u.cMask);
u.teleport(p.x, p.y);
((mortraBlinkAS) effect).aim = aim;
effect.startCooldown();
effect.addEffect(u);
if (aim.owners.groupInGroup(u.frendGRP)) u.setMoveToUnit(aim, true);
else u.setAttackUnit(aim, true, true);
return 0;
}
}
| [
"artemsvyatoha@gmai.com"
] | artemsvyatoha@gmai.com |
c36fec7f321d690f873975a602527e8972960656 | 594972ea0d43cd2f6d7541017a959b2ada29209b | /src/main/java/com/example/demo/test/WorkGroupUSer.java | 7ab3425671a0cfd6b5defca5efc9cf001512dad9 | [] | no_license | ehssanmp/second | dd7d2709c98586482e6fdab1458c9a9d74aa80f6 | 53622335d8126c2e094f0cec7611d42e0bd26753 | refs/heads/master | 2023-04-30T21:15:31.444064 | 2020-01-24T20:02:26 | 2020-01-24T20:02:26 | 234,687,322 | 0 | 0 | null | 2023-04-14T17:43:22 | 2020-01-18T05:36:21 | Java | UTF-8 | Java | false | false | 449 | java | package com.example.demo.test;
import java.util.List;
public class WorkGroupUSer {
private WorkShop event;
private int id;
private int indx;
public WorkShop getEvent() {
return event;
}
public void setEvent(WorkShop event) {
this.event = event;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getIndx() {
return indx;
}
public void setIndx(int indx) {
this.indx = indx;
}
}
| [
"seyed.ehssan123@gmail.com"
] | seyed.ehssan123@gmail.com |
3fd381be5070afb7b1943c6d78499b70afd9ec06 | 3a705b70ceda00c41ed927619b0ca21947f4c83c | /src/main/java/com/kor/challenger/domain/dto/response/ExecutionCommentResponseDto.java | b7c0ee180505f22e03e7f1bb34c2beae03d37f9c | [] | no_license | Sandres92/challenger | 86de8b67b94c86c0bf92c0ae6cdfb964a296e1b5 | 6f81dff9a5efc360fe2cf88017bbfd173bd6e52c | refs/heads/master | 2022-12-18T04:31:54.875138 | 2020-09-01T19:53:57 | 2020-09-01T19:53:57 | 265,928,646 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 394 | java | package com.kor.challenger.domain.dto.response;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDateTime;
@AllArgsConstructor
@Setter
@Getter
public class ExecutionCommentResponseDto {
private Long id;
private String text;
private Long executionId;
private LocalDateTime creationDate;
private UserResponseDto author;
}
| [
"eastoutcity@mail.ru"
] | eastoutcity@mail.ru |
06a9f5591a1324d3b185260e64fa9b0ca6fbb760 | 642edd74d2deb9196c95698c10fa3d463d9a1cd8 | /src/main/java/com/cloud/service/rpc/dubbo/example/service/HelloNettyImpl.java | 321fe527cb18b8fd40eeb64ab52f23b895df3c2e | [] | no_license | liuheyong/z_cloud_service | 04d368418fb9369d599af9811a025e049b0938d1 | e944e5766f609347ffa70de288236ece87c55723 | refs/heads/dev | 2022-12-08T07:01:47.450663 | 2022-12-04T08:34:01 | 2022-12-04T08:34:01 | 190,364,141 | 0 | 0 | null | 2022-10-04T23:52:47 | 2019-06-05T09:15:41 | Java | UTF-8 | Java | false | false | 306 | java | package com.cloud.service.rpc.dubbo.example.service;
/**
* @author: HeYongLiu
* @create: 08-19-2019
* @description: Server(服务的提供方)
**/
public class HelloNettyImpl implements HelloNetty {
@Override
public String hello() {
return "----> hello,netty(服务端) <---";
}
}
| [
"17682347237@163.com"
] | 17682347237@163.com |
2efe9b6103f4ef3c18c8b4a6f148dc25d47eff08 | 008943c1dcf138b82ff72a84764a40ef29999168 | /DesignPatterns/java/com/sirma/itt/javacourse/designpatterns/patterns/proxy/IntegerFactory.java | 8e209f5cf1c3f72dc8e86219a2c70cc2b553dbbc | [] | no_license | peshoni/JavaCourse | dd481d845ae4fbc81cdac257c8d0156a8bfe428f | f2debd3733479baa018522005784f4db369ee475 | refs/heads/master | 2020-05-23T10:22:27.061741 | 2017-01-30T18:03:12 | 2017-01-30T18:03:12 | 80,428,609 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 457 | java | package com.sirma.itt.javacourse.designpatterns.patterns.proxy;
/**
* ITTE-1913 Proxy design pattern.
*
* @author Petar Ivanov
*/
public class IntegerFactory {
/**
* Private constructor
*/
private IntegerFactory() {
}
/**
* Creates instance of the IntegerReal class.
*
* @return Instance of IntegerReal class.
*/
public static IntegerReal createInstance(int integer) {
return new IntegerReal(integer);
}
}
| [
"pesho02@abv.bg"
] | pesho02@abv.bg |
868a771f8f9286c5d2b5b8079ef9e280c4735587 | acf659c9ea8c2f18af5414fd915589c65fc1b003 | /智能移动平台开发/ImgCluster/app/src/main/java/com/app/zpvoh/imgcluster/sqlUtils/InitEntityUtils.java | ddf27b991a125422098e9c10c5ba8b6634c608cd | [] | no_license | 17302010040/FudanUniversity | 0da664b4fe63ccdc8cd4096ba5fbfbdb6eadca31 | a122f19256d2a666265b7344ba1dcd8eb6b36885 | refs/heads/master | 2020-08-21T13:10:48.600608 | 2019-08-01T05:30:17 | 2019-08-01T05:30:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,177 | java | package com.app.zpvoh.imgcluster.sqlUtils;
import android.util.Log;
import com.app.zpvoh.imgcluster.entities.Comment;
import com.app.zpvoh.imgcluster.entities.Group;
import com.app.zpvoh.imgcluster.entities.Image;
import com.app.zpvoh.imgcluster.entities.User;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class InitEntityUtils {
public static User initUser(ResultSet resultSet) throws SQLException {
if (!resultSet.next()) return null;
Log.i("getUser", "success");
User user = new User();
user.setUid(resultSet.getInt(1));
user.setEmail(resultSet.getString(2));
user.setUsername(resultSet.getString(3));
return user;
}
public static ArrayList<Group> initGroupList(ResultSet resultSet) throws SQLException {
ArrayList<Group> arrayList = new ArrayList<>();
while (resultSet.next()) {
Group group = new Group();
group.setGroup_id(resultSet.getInt(1));
group.setGroup_name(resultSet.getString(2));
arrayList.add(group);
}
return arrayList;
}
public static ArrayList<Image> initImageList(ResultSet resultSet) throws SQLException {
ArrayList<Image> arrayList = new ArrayList<>();
while (resultSet.next()) {
Image image = new Image();
image.setImg_id(resultSet.getInt(1));
image.setGroup_id(resultSet.getInt(2));
image.setName(resultSet.getString(3));
image.setPath("http://139.196.80.102:8080/pj-imgs/"+resultSet.getString(4));
image.setTime(resultSet.getTimestamp(5).toString());
arrayList.add(image);
}
return arrayList;
}
public static ArrayList<Comment> initCommentList(ResultSet resultSet) throws SQLException {
ArrayList<Comment> arrayList = new ArrayList<>();
while (resultSet.next()) {
Comment comment = new Comment();
comment.setUsername(resultSet.getString(1));
comment.setContent(resultSet.getString(2));
arrayList.add(comment);
}
return arrayList;
}
}
| [
"384460967@qq.com"
] | 384460967@qq.com |
22cc930dcb2c398ffdbbcc1ad541cd13b3d94a71 | 8af1164bac943cef64e41bae312223c3c0e38114 | /results-java/orientechnologies--orientdb/22696406869532cbfe6e4d082027944192ed2207/before/OFileExtractor.java | 7d3bbd307ea404ab38e057e2a2ef937a18f78e4c | [] | no_license | fracz/refactor-extractor | 3ae45c97cc63f26d5cb8b92003b12f74cc9973a9 | dd5e82bfcc376e74a99e18c2bf54c95676914272 | refs/heads/master | 2021-01-19T06:50:08.211003 | 2018-11-30T13:00:57 | 2018-11-30T13:00:57 | 87,353,478 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,755 | java | /*
*
* * Copyright 2010-2014 Orient Technologies LTD (info(at)orientechnologies.com)
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package com.orientechnologies.orient.etl.extract;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.record.impl.ODocument;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.NoSuchElementException;
import java.util.zip.GZIPInputStream;
public abstract class OFileExtractor extends OAbstractExtractor {
protected String fileName;
protected Object path;
protected boolean lockFile = false;
protected long byteParsed = 0;
protected long byteToParse = -1;
protected RandomAccessFile raf = null;
protected FileChannel channel = null;
protected InputStreamReader fileReader = null;
protected FileInputStream fis = null;
protected FileLock lock = null;
@Override
public void configure(ODocument iConfiguration) {
path = iConfiguration.field("path");
if (iConfiguration.containsField("lock"))
lockFile = iConfiguration.field("lock");
}
@Override
public String getName() {
return "file";
}
public String getUnit() {
return "bytes";
}
public void extract(OCommandContext context) {
if (path instanceof String)
path = new File((String) path);
if (path instanceof File) {
final File file = (File) path;
fileName = file.getName();
try {
raf = new RandomAccessFile(file, "rw");
channel = raf.getChannel();
fis = new FileInputStream(file);
if (fileName.endsWith(".gz"))
fileReader = new InputStreamReader(new GZIPInputStream(fis));
else {
fileReader = new FileReader(file);
byteToParse = file.length();
}
} catch (Exception e) {
end();
}
} else if (path instanceof InputStream) {
fileName = null;
byteToParse = -1;
fileReader = new InputStreamReader((InputStream) path);
} else if (path instanceof InputStreamReader) {
fileName = null;
byteToParse = -1;
fileReader = (InputStreamReader) path;
} else
throw new OExtractorException("Unknown input '" + path + "' of class '" + path.getClass() + "'");
begin();
}
@Override
public boolean hasNext() {
if (fileReader == null)
return false;
try {
final boolean res = fileReader.ready();
if (!res)
// CLOSE IT
end();
return res;
} catch (IOException e) {
throw new OExtractorException(e);
}
}
@Override
public Object next() {
if (!hasNext())
throw new NoSuchElementException("EOF");
try {
byteParsed++;
return (byte) fileReader.read();
} catch (IOException e) {
throw new OExtractorException(e);
}
}
public void end() {
if (lock != null)
try {
lock.release();
} catch (IOException e) {
e.printStackTrace();
}
if (fis != null)
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
if (fileReader != null)
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
if (channel != null)
try {
channel.close();
} catch (IOException e) {
e.printStackTrace();
}
if (raf != null)
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public long getProgress() {
return byteParsed;
}
@Override
public long getTotal() {
return byteToParse;
}
protected void begin() {
byteParsed = 0;
if (lockFile)
try {
lock = channel.lock();
} catch (IOException e) {
e.printStackTrace();
}
final long startTime = System.currentTimeMillis();
}
} | [
"fraczwojciech@gmail.com"
] | fraczwojciech@gmail.com |
94ff3f080fa3d9629b331c79f9f3555973fce09a | 69a4f2d51ebeea36c4d8192e25cfb5f3f77bef5e | /methods/Method_19020.java | 6d5ca53abbeec6c97abab85643a9986b258929e6 | [] | no_license | P79N6A/icse_20_user_study | 5b9c42c6384502fdc9588430899f257761f1f506 | 8a3676bc96059ea2c4f6d209016f5088a5628f3c | refs/heads/master | 2020-06-24T08:25:22.606717 | 2019-07-25T15:31:16 | 2019-07-25T15:31:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 122 | java | @VisibleForTesting(otherwise=VisibleForTesting.PACKAGE_PRIVATE) public List<Section> getChildren(){
return mSections;
}
| [
"sonnguyen@utdallas.edu"
] | sonnguyen@utdallas.edu |
7f25f50b90ac874931c472cdb81c4323ea07f720 | 9ac2c0cdad9126c20d74e305890d8da7aca4a47a | /src/main/java/T.java | f86dea5d22d881741b41a247e03928a532079c05 | [] | no_license | ericaZhou/util | 0a653eb9a6c62ac6220494620e3a81b4510d2a2c | b3d727f83fed8c5fce36298fa03099498ba485f9 | refs/heads/master | 2021-01-21T11:40:16.701195 | 2013-09-25T09:33:01 | 2013-09-25T09:33:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,555 | java | import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Properties;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.PropertiesConfigurationLayout;
public class T {
public static void main(String[] args) throws Exception {
//Properties prop = new Properties();// 属性集合对象
File f = new File("src/main/java/agent.properties");
//FileInputStream fis = new FileInputStream(f);// 属性文件输入流
//prop.load(fis);// 将属性文件流装载到Properties对象中
//fis.close();// 关闭流
PropertiesConfiguration prop = new PropertiesConfiguration(f);
PropertiesConfigurationLayout proLayout = prop.getLayout();
prop.setProperty("zone.id", "0000");
Writer w = new FileWriter(f);
proLayout.save(w);
// 获取属性值,sitename已在文件中定义
// 获取属性值,country未在文件中定义,将在此程序中返回一个默认值,但并不修改属性文件
// System.out.println("获取属性值:country=" + prop.getProperty("country",
// "中国"));
// 修改sitename的属性值
/* prop.setProperty("password", "heihei1");
// 文件输出流
FileOutputStream fos = new FileOutputStream("src/test.properties");
// 将Properties集合保存到流中
prop.store(fos, "Copyright (c) Boxcode Studio");
fos.close();// 关闭流
*/
System.out.println("获取修改后的属性值:password=" + prop.getProperty("zone.id"));
}
}
| [
"zhouwenya@actionsky.com"
] | zhouwenya@actionsky.com |
c6ae7f355c295c3684433ab5d7fd01e801ecb665 | b5dc21b23f8639908df6124c123ce3d8aa617b6c | /time_is_key/Android_auth/classes_dex2jar/android/support/v7/widget/AppCompatCheckedTextView.java | 1dd2b4b3f00eb9bbded44ba4571cb33f28980dfa | [] | no_license | warsang/wargameNDH2K17 | d8a6863e347b45dbbb06e87328123c3372e53ec1 | 349fa667d5d9132597f8cc03044f3f05ab7f9f94 | refs/heads/master | 2020-12-02T22:16:45.039175 | 2017-07-03T14:00:04 | 2017-07-03T14:00:04 | 96,105,912 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,825 | java | package android.support.v7.widget;
import android.content.Context;
import android.support.annotation.DrawableRes;
import android.support.v7.content.res.AppCompatResources;
import android.util.AttributeSet;
import android.widget.CheckedTextView;
public class AppCompatCheckedTextView
extends CheckedTextView
{
private static final int[] TINT_ATTRS = { 16843016 };
private AppCompatTextHelper mTextHelper = AppCompatTextHelper.create(this);
public AppCompatCheckedTextView(Context paramContext)
{
this(paramContext, null);
}
public AppCompatCheckedTextView(Context paramContext, AttributeSet paramAttributeSet)
{
this(paramContext, paramAttributeSet, 16843720);
}
public AppCompatCheckedTextView(Context paramContext, AttributeSet paramAttributeSet, int paramInt)
{
super(TintContextWrapper.wrap(paramContext), paramAttributeSet, paramInt);
this.mTextHelper.loadFromAttributes(paramAttributeSet, paramInt);
this.mTextHelper.applyCompoundDrawablesTints();
TintTypedArray localTintTypedArray = TintTypedArray.obtainStyledAttributes(getContext(), paramAttributeSet, TINT_ATTRS, paramInt, 0);
setCheckMarkDrawable(localTintTypedArray.getDrawable(0));
localTintTypedArray.recycle();
}
protected void drawableStateChanged()
{
super.drawableStateChanged();
if (this.mTextHelper != null) {
this.mTextHelper.applyCompoundDrawablesTints();
}
}
public void setCheckMarkDrawable(@DrawableRes int paramInt)
{
setCheckMarkDrawable(AppCompatResources.getDrawable(getContext(), paramInt));
}
public void setTextAppearance(Context paramContext, int paramInt)
{
super.setTextAppearance(paramContext, paramInt);
if (this.mTextHelper != null) {
this.mTextHelper.onSetTextAppearance(paramContext, paramInt);
}
}
}
| [
"warsang@hotmail.com"
] | warsang@hotmail.com |
fb5a99bb32c417836530346534db07640d77d51d | b5ffa3251feeef69febe39127219e1b515f900b3 | /app/src/test/java/com/zbigniew/beaconcalibrator/ExampleUnitTest.java | 7e46f6176ebb5f324e6cbc78b45f667d10584713 | [] | no_license | zibiksior/BeaconCalibrator | b2ecfb9d33b41222e8c655c8326c551a05e317b5 | 0646044e5df8488a67e2e64217dfa33a533f56d4 | refs/heads/master | 2021-01-21T12:54:01.337255 | 2016-05-17T12:40:09 | 2016-05-17T12:40:09 | 48,047,974 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 322 | java | package com.zbigniew.beaconcalibrator;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"zbigniew.fr@gmail.com"
] | zbigniew.fr@gmail.com |
6dde26ff92b75d9b078223f8f4d0ff35b4c302de | b6f577190dab6f5bdf624fd69426950a8e9a1668 | /src/Hw1.java | 9d8bbdf3243e0e192f8e1ef41d1437366bee4d1a | [] | no_license | Raji-P/Add-java-code | e64f3992d8808256f9e1aa72db10b89d4681f0e6 | 0838a02f365d17bdd936b0e107deb27086808900 | refs/heads/master | 2021-04-08T07:34:14.837293 | 2020-03-20T12:37:18 | 2020-03-20T12:37:18 | 248,753,952 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 147 | java |
public class Hw1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello GITHUB!!");
}
}
| [
"sruthi.1418it@gmail.com"
] | sruthi.1418it@gmail.com |
bad0111be237412cfbad140fdd87495cabf9a090 | 09c321746958e2fc5f4867acc77a82de1303ee2e | /ADS/Tree/BT2.java | 14982357f3708007e8e6491d4ecda011dec0722a | [] | no_license | mrakshayvthawale/May2021 | 454a83ee59d911a671aba2299a67fe33c382252d | 2b1786c35a77f98046dcf320336e10f302044610 | refs/heads/main | 2023-07-03T17:29:06.569578 | 2021-08-05T06:48:58 | 2021-08-05T06:48:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,350 | java | package list;
class BT2
{
Node root;
static class Node
{
int data;
Node left, right;
Node(int d)
{
data = d;
left = right = null;
}
}
BT2()
{
root = null;
}
BT2(int d)
{
root = new Node(d);
}
void Inorder(Node node)
{
if(node == null)
return;
Inorder(node.left);
System.out.print(node.data+" ");
Inorder(node.right);
}
void Preorder(Node node)
{
if(node == null)
return;
System.out.print(node.data+ " ");
Preorder(node.left);
Preorder(node.right);
}
void Postorder(Node node)
{
if(node == null)
return;
Postorder(node.left);
Postorder(node.right);
System.out.print(node.data+" ");
}
void Inorder()
{
Inorder(root);
}
void Preorder()
{
Preorder(root);
}
void Postorder()
{
Postorder(root);
}
public static void main(String args[])
{
BT2 t1 = new BT2();
t1.root = new Node(1);
t1.root.left = new Node(2);
t1.root.right = new Node(3);
t1.root.left.left = new Node(4);
t1.root.left.right = new Node(5);
System.out.println("Inorder Traversal : ");
t1.Inorder();
System.out.println();
System.out.println("Preorder Traversal : ");
t1.Preorder();
System.out.println();
System.out.println("Postorder Traversal : ");
t1.Postorder();
}
} | [
"noreply@github.com"
] | mrakshayvthawale.noreply@github.com |
069b8be74e7d4d08fbc322b1bd2c6704d9d2c8b1 | 5628da13e2fb495e7c9006b068e0d0aae7d29c77 | /src/ed/ogonzalezm/a06/DLList.java | 81186e7e2b7211ea689011440ab16a8fc2ea3fdd | [] | no_license | OsvaldoGM/ED-OGonzalezM-A06 | d026114b79a0a6a47442e8bee73a39dc128b824d | ec2c4bd00fbaad6676817e0725c41f8f9f6d4710 | refs/heads/master | 2021-01-23T19:11:38.683307 | 2017-10-13T01:06:16 | 2017-10-13T01:06:16 | 102,809,837 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,749 | java | /*
* 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 ed.ogonzalezm.a06;
/**
*
* @author HONORIO ZAIBACK
*/
public class DLList <T>{
NodoDL<T> first;
NodoDL<T> last;
NodoDL<T> pointer;
int length;
DLList(){
first = last = pointer = null;
length = 0;
}
DLList(T d){
NodoDL<T> nodo = new NodoDL(d);
first = last = nodo;
nodo.next = nodo.back = null;
length++;
}
boolean isEmpty(){
return length==0;
}
void insertFirst(T d){
NodoDL<T> nodo = new NodoDL(d);
if(isEmpty()){
first = last = nodo;
}else{
nodo.next = first;
first.back = nodo;
first = nodo;
}
length++;
}
void insertLast(T d){
NodoDL<T> nodo = new NodoDL(d);
if(isEmpty()){
first = last = nodo;
}else{
nodo.back = last;
last.next = nodo;
last = nodo;
}
length--;
}
void deleteFirst(T d){
if(!isEmpty()){
if(length==1){
first = last = null;
}else{
first = first.next;
first.back = null;
}
}
length--;
}
void deleteLast(){
if(!isEmpty()){
if(length==1){
first = last = null;
}else{
pointer = first;
while(pointer.next != last){
pointer = pointer.next;
}
last = pointer;
last.next = pointer = null;
}
length--;
}
}
void deleteNodo(T d){
pointer = first;
if(!isEmpty()){
if(length==1){
if(first.data == d){
first = last = null;
}
}else{
if(first.data == d){
first = first.next;
first.back = null;
}else if(last.data == d){
last = last.back;
last.next = null;
}else{
pointer = first;
while(pointer.next != last){
if(pointer.next.data == d){
pointer.next = pointer.next.next;
pointer.next.next.back = pointer;
}
pointer = pointer.next;
}
}
}
length--;
}
}
}
| [
"noreply@github.com"
] | OsvaldoGM.noreply@github.com |
dd8164c21dee784ce8dd52f3c76fe70cfb5b2640 | cd3a9cefe6335c77a20ec9b27f73c78a9686e802 | /src/test/java/pl/coderslab/Main02.java | 2933e92afe6b22c8c7e9c0caae3cc67b66c2e785 | [] | no_license | sunymonkey/MySQL_user_DAO | 78d7cfb03fa070844cdd900d3d79abb40a12ef62 | 9e735450344db9dc144e71e4b2f0a05fd0cc9722 | refs/heads/master | 2023-04-26T02:40:12.287986 | 2021-05-28T12:20:34 | 2021-05-28T12:20:34 | 371,500,953 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,912 | java | package pl.coderslab;
import org.mindrot.jbcrypt.BCrypt;
import pl.coderslab.entity.ConsoleColors;
import pl.coderslab.entity.User;
import pl.coderslab.entity.UserDao;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main02 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
menuPrint();
String menu = scanner.nextLine().trim();
switch (menu) {
case "add" -> addUser();
case "update" -> updateUser();
case "remove" -> removeUser();
case "print users" -> printUsers();
case "list all" -> readAll();
case "find" -> findUser();
case "exit" -> {
System.out.println(ConsoleColors.RED + "Bye, bye !");
return;
}default -> System.out.println(ConsoleColors.RED_BOLD + "Wrong command" + ConsoleColors.RESET);
}
}
}
private static void updateUser() {
Scanner scanner = new Scanner(System.in);
System.out.println("Podaj id użytkownika którego chcesz zaktualizować:");
int id = idRead();
UserDao userDao = new UserDao();
User user = userDao.read(id);
if (user != null) {
update(scanner, id, userDao, user);
} else {
System.out.println("Id nie istnieje");
}
}
private static void update(Scanner scanner, int id, UserDao userDao, User user) {
printUser(user);
System.out.println("Który parametr chcesz zaktualizować ? Wpisz: email, name, password");
String menu = scanner.nextLine().trim();
int temp = 0;
switch (menu) {
case "email" -> {
System.out.println("Wpisz nowy email:");
String email = scanner.nextLine().trim();
user.setEmail(email);
temp = 1;
} case "name" -> {
System.out.println("Wpisz nowy name:");
String name = scanner.nextLine().trim();
user.setUserName(name);
temp = 1;
} case "password" -> {
System.out.println("Wpisz stare hasło:");
String password = scanner.nextLine().trim();
if (BCrypt.checkpw(password, user.getPassword())) {
System.out.println("Wprowadz nowe haslo: ");
password = scanner.nextLine().trim();
user.setPassword(password);
temp = 1;
} else {
System.out.println("Błędne hasło, aktualizacja niemożliwa");
}
} default -> System.out.println(ConsoleColors.RED_BOLD + "Wrong command" + ConsoleColors.RESET);
}
if (userDao.update(user) && temp == 1) {
user = userDao.read(id);
System.out.println("Dane po aktualizacji");
printUser(user);
}
}
private static void printUser(User user) {
headUsersTable();
System.out.println(user);
}
private static void printUsers() {
UserDao userDao = new UserDao();
System.out.println("Podaj id użytkownika: ");
int id = idRead();
User users = userDao.read(id);
if (users != null) {
printUser(users);
} else {
System.out.println("Brak wpisu w bazie");
}
}
private static void readAll() {
UserDao userDao = new UserDao();
User[] users = userDao.findAll();
printDatabase(users);
}
private static void findUser() {
System.out.println("Po czym chcesz szukać użytkowników ? Wpisz email lub name");
Scanner scanner = new Scanner(System.in);
String menu = scanner.nextLine().trim();
switch (menu) {
case "email" -> emailFind();
case "name" -> nameFind();
default -> System.out.println(ConsoleColors.RED_BOLD + "Wrong command" + ConsoleColors.RESET);
}
}
private static void nameFind() {
Scanner scanner = new Scanner(System.in);
System.out.println("Wpisz szukana nazwę użytkownika:");
String name = scanner.nextLine().trim();
UserDao userDao = new UserDao();
User[] users = userDao.findName(name);
printDatabase(users);
}
private static void emailFind() {
Scanner scanner = new Scanner(System.in);
System.out.println("Wpisz szukana nazwę użytkownika:");
String name = scanner.nextLine().trim();
UserDao userDao = new UserDao();
User[] users = userDao.findEmail(name);
printDatabase(users);
}
private static void removeUser() {
System.out.println("Wpisz którego użytkownika chcesz usunąć:");
int id = idRead();
UserDao userDao = new UserDao();
if (userDao.delete(id)){
System.out.println("Wpis usunięty");
} else {
System.out.println(ConsoleColors.RED_BOLD + "Wpis nie usuniety" + ConsoleColors.RESET);
}
}
private static int idRead() {
Scanner scanner = new Scanner(System.in);
try {
return scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println(ConsoleColors.RED_BOLD + "Wprowadzono błędny format danych !" + ConsoleColors.RESET);
}
return 0;
}
private static void addUser() {
Scanner scanner = new Scanner(System.in);
System.out.println("Wpisz użytkownika");
String username = scanner.nextLine().trim();
System.out.println("Wpisz email");
String email = scanner.nextLine().trim();
System.out.println("Wpisz hasło");
String password = scanner.nextLine().trim();
UserDao userDao = new UserDao();
userDao.create(new User(username, email, password));
}
private static void menuPrint() {
System.out.println("-".repeat(10));
System.out.println(ConsoleColors.BLUE_BOLD + "Please select an option: " + ConsoleColors.RESET);
System.out.println("add");
System.out.println("update");
System.out.println("remove");
System.out.println("find");
System.out.println("print users");
System.out.println("list all");
System.out.println("exit");
}
private static void printDatabase(User[] users) {
if (users.length != 0) {
headUsersTable();
for (User element:users) {
System.out.println(element);
}
} else {
System.out.println("Brak danych w bazie");
}
}
private static void headUsersTable() {
System.out.printf("%3s. %-15s %-35s%n", "id", "user name", "email");
}
}
| [
"mr.piotr.ratajczyk@gmail.com"
] | mr.piotr.ratajczyk@gmail.com |
72b0676c4713b989c8b4d429352e68924d256326 | b067d5061e4ae5e3e7f010175694bf2802706485 | /American/ravv-service/src/main/java/cn/farwalker/ravv/service/payment/bank/biz/impl/MemberBankBizImpl.java | ec0b0e6ce7f6f66d684bfb7be40f277c3e918b12 | [] | no_license | lizhenghong20/web | 7cf5a610ec19a0b8f7ba662131e56171fffabf9b | 8941e68a2cf426b831e8219aeea8555568f95256 | refs/heads/master | 2022-11-05T18:02:47.842268 | 2019-06-10T02:22:32 | 2019-06-10T02:22:32 | 190,309,917 | 0 | 0 | null | 2022-10-12T20:27:42 | 2019-06-05T02:09:30 | Java | UTF-8 | Java | false | false | 1,576 | java | package cn.farwalker.ravv.service.payment.bank.biz.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import cn.farwalker.ravv.service.payment.bank.model.MemberBankBo;
import cn.farwalker.waka.util.Tools;
import cn.farwalker.ravv.service.payment.bank.dao.IMemberBankDao;
import cn.farwalker.ravv.service.payment.bank.biz.IMemberBankBiz;
/**
* 会员银行卡<br/>
* <br/>
* //手写的注释:以"//"开始 <br/>
* @author generateModel.java
*/
@Service
public class MemberBankBizImpl extends ServiceImpl<IMemberBankDao,MemberBankBo> implements IMemberBankBiz{
@Resource
private IMemberBankBiz memberBankBiz;
@Override
public List<MemberBankBo> getBankCardByMemberId(Long memberId) {
if(null == memberId) {
return null;
}
Wrapper<MemberBankBo> wrapper = new EntityWrapper<>();
wrapper.eq(MemberBankBo.Key.memberId.toString(), memberId);
List<MemberBankBo> bankCardList = memberBankBiz.selectList(wrapper);
if(Tools.collection.isNotEmpty(bankCardList)) {
for(MemberBankBo bankCard : bankCardList) {
//只显示银行卡后四位数字
Integer length = bankCard.getCardNumber().length();
StringBuilder hideCardNumber = new StringBuilder(bankCard.getCardNumber());
hideCardNumber.replace(0, length - 4, "*");
bankCard.setCardNumber(hideCardNumber.toString());
}
}
return bankCardList;
}
} | [
"simple.ding816@gmail.com"
] | simple.ding816@gmail.com |
f5cce48686e529c979170b848b05ce924604e27f | 383f1c0b8999b1a92acbdfbd9757777eec462e2d | /src/com/ui/slidersample/SliderSample.java | 7ed6fc5e09ea53b1ca1d35f76ff4f1e4331b1f72 | [] | no_license | yafengstark/JavaFxBook | 65819ab3ee5895219dcbb78cae211cb85707f6bd | 65dd0b33223be54a03dfb360038027721f112a9e | refs/heads/master | 2020-05-17T01:25:18.926916 | 2019-05-26T08:56:26 | 2019-05-26T08:56:26 | 183,425,436 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,871 | java | /*
* Copyright (c) 2012, 2014, Oracle and/or its affiliates.
* All rights reserved. Use is subject to license terms.
*
* This file is available and licensed under the following license:
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ui.slidersample;
import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.effect.SepiaTone;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class SliderSample extends Application {
final Slider opacityLevel = new Slider(0, 1, 1);
final Slider sepiaTone = new Slider(0, 1, 1);
final Slider scaling = new Slider (0.5, 1, 1);
final Image image = new Image(getClass().getResourceAsStream(
"cappuccino.jpg")
);
final Label opacityCaption = new Label("Opacity Level:");
final Label sepiaCaption = new Label("Sepia Tone:");
final Label scalingCaption = new Label("Scaling Factor:");
final Label opacityValue = new Label(
Double.toString(opacityLevel.getValue()));
final Label sepiaValue = new Label(
Double.toString(sepiaTone.getValue()));
final Label scalingValue = new Label(
Double.toString(scaling.getValue()));
final static Color textColor = Color.BLACK;
final static SepiaTone sepiaEffect = new SepiaTone();
@Override
public void start(Stage stage) {
Group root = new Group();
Scene scene = new Scene(root, 600, 400);
stage.setScene(scene);
stage.setTitle("Slider Sample");
GridPane grid = new GridPane();
grid.setPadding(new Insets(10, 10, 10, 10));
grid.setVgap(10);
grid.setHgap(70);
final ImageView cappuccino = new ImageView (image);
cappuccino.setEffect(sepiaEffect);
GridPane.setConstraints(cappuccino, 0, 0);
GridPane.setColumnSpan(cappuccino, 3);
grid.getChildren().add(cappuccino);
scene.setRoot(grid);
opacityCaption.setTextFill(textColor);
GridPane.setConstraints(opacityCaption, 0, 1);
grid.getChildren().add(opacityCaption);
opacityLevel.valueProperty().addListener((
ObservableValue<? extends Number> ov,
Number old_val, Number new_val) -> {
cappuccino.setOpacity(new_val.doubleValue());
opacityValue.setText(String.format("%.2f", new_val));
});
GridPane.setConstraints(opacityLevel, 1, 1);
grid.getChildren().add(opacityLevel);
opacityValue.setTextFill(textColor);
GridPane.setConstraints(opacityValue, 2, 1);
grid.getChildren().add(opacityValue);
sepiaCaption.setTextFill(textColor);
GridPane.setConstraints(sepiaCaption, 0, 2);
grid.getChildren().add(sepiaCaption);
sepiaTone.valueProperty().addListener((
ObservableValue<? extends Number> ov, Number old_val,
Number new_val) -> {
sepiaEffect.setLevel(new_val.doubleValue());
sepiaValue.setText(String.format("%.2f", new_val));
});
GridPane.setConstraints(sepiaTone, 1, 2);
grid.getChildren().add(sepiaTone);
sepiaValue.setTextFill(textColor);
GridPane.setConstraints(sepiaValue, 2, 2);
grid.getChildren().add(sepiaValue);
scalingCaption.setTextFill(textColor);
GridPane.setConstraints(scalingCaption, 0, 3);
grid.getChildren().add(scalingCaption);
scaling.valueProperty().addListener((
ObservableValue<? extends Number> ov, Number old_val,
Number new_val) -> {
cappuccino.setScaleX(new_val.doubleValue());
cappuccino.setScaleY(new_val.doubleValue());
scalingValue.setText(String.format("%.2f", new_val));
});
GridPane.setConstraints(scaling, 1, 3);
grid.getChildren().add(scaling);
scalingValue.setTextFill(textColor);
GridPane.setConstraints(scalingValue, 2, 3);
grid.getChildren().add(scalingValue);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
} | [
"fengfeng043@gmail.com"
] | fengfeng043@gmail.com |
d35cda5d235d9dbef0da3111f8423e9b5d3f928f | 753d62464adb2aa2c09a3b3135082e51b1efb42d | /sample-app/src/androidTest/java/com/kogitune/prelollipoptransition/ApplicationTest.java | fc4936f789b11e32c5c52d20faefaf4262de9e4b | [
"Apache-2.0"
] | permissive | tantom/PreLollipopTransition | e871b82f25ef2238140e3cc87fdfafa3e8bae362 | 05100f912a1b0e589ce9fae71db28a76db8d1849 | refs/heads/develop | 2020-12-25T01:44:26.078387 | 2016-04-30T15:02:24 | 2016-04-30T15:02:24 | 62,679,089 | 2 | 0 | null | 2016-07-06T00:41:30 | 2016-07-06T00:41:29 | null | UTF-8 | Java | false | false | 967 | java | /*
* Copyright (C) 2015 takahirom
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.kogitune.prelollipoptransition;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | [
"takam.dev@gmail.com"
] | takam.dev@gmail.com |
e48ddea554707a8919d1eb775c5de215359b7fad | e3a09a1c199fb3e32d1e43c1393ec133fa34ceab | /game/data/scripts/handlers/admincommandhandlers/AdminUnblockIp.java | cf5f8bebea4310b1dc2a4fbc61bd5056933ca4e4 | [] | no_license | Refuge89/l2mobius-helios | 0fbaf2a11b02ce12c7970234d4b52efa066ef122 | d1251e1fb5a2a40925839579bf459083a84b0c59 | refs/heads/master | 2020-03-23T01:37:03.354874 | 2018-07-14T06:52:51 | 2018-07-14T06:52:51 | 140,927,248 | 1 | 0 | null | 2018-07-14T07:49:40 | 2018-07-14T07:49:39 | null | UTF-8 | Java | false | false | 2,158 | java | /*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package handlers.admincommandhandlers;
import java.util.logging.Logger;
import com.l2jmobius.gameserver.handler.IAdminCommandHandler;
import com.l2jmobius.gameserver.model.actor.instance.L2PcInstance;
import com.l2jmobius.gameserver.util.BuilderUtil;
/**
* This class handles following admin commands:
* <ul>
* <li>admin_unblockip</li>
* </ul>
* @version $Revision: 1.3.2.6.2.4 $ $Date: 2005/04/11 10:06:06 $
*/
public class AdminUnblockIp implements IAdminCommandHandler
{
private static final Logger LOGGER = Logger.getLogger(AdminUnblockIp.class.getName());
private static final String[] ADMIN_COMMANDS =
{
"admin_unblockip"
};
@Override
public boolean useAdminCommand(String command, L2PcInstance activeChar)
{
if (command.startsWith("admin_unblockip "))
{
try
{
final String ipAddress = command.substring(16);
if (unblockIp(ipAddress, activeChar))
{
BuilderUtil.sendSysMessage(activeChar, "Removed IP " + ipAddress + " from blocklist!");
}
}
catch (StringIndexOutOfBoundsException e)
{
BuilderUtil.sendSysMessage(activeChar, "Usage: //unblockip <ip>");
}
}
return true;
}
@Override
public String[] getAdminCommandList()
{
return ADMIN_COMMANDS;
}
private boolean unblockIp(String ipAddress, L2PcInstance activeChar)
{
// LoginServerThread.getInstance().unBlockip(ipAddress);
LOGGER.warning("IP removed by GM " + activeChar.getName());
return true;
}
}
| [
"conan_513@hotmail.com"
] | conan_513@hotmail.com |
68b4365f1e05b3b7d9242b4583685c302cf1d9a8 | ed66b3ce70288a1389407963a53030c8465a89f8 | /src/section3/HelloWorld.java | d649c8dc4e9317f2d3ff2c4a97019369d4ef4911 | [] | no_license | League-Workshop/intro-to-java-workshop-Sashaur | a6bb703225053e6bb2e39b736f09223f5ae30cb7 | d3b4791d844991be0638f9c69532765cb288a4b9 | refs/heads/master | 2021-04-29T15:06:53.493399 | 2018-02-16T22:57:09 | 2018-02-16T22:57:09 | 121,790,910 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 311 | java | package section3;
import javax.swing.JOptionPane;
public class HelloWorld {
public static void main(String[] args) {
System.out.println();
JOptionPane.showMessageDialog(null, "never gonna give you up");
String name = JOptionPane.showInputDialog("never gonna letchu down");
System.out.println(name);
}
}
| [
"league@WTS-iMac-11.local"
] | league@WTS-iMac-11.local |
867846fb6aaee3c18c6fce1c7378e10d92dba82b | 5f6f1f63ef1034c0431d418e32e8e6ab7451f062 | /Silc/src/main/java/org/reldb/ldi/sili/values/ValueInteger.java | fb34df4c3c021e5cf90a203a5b1e8511478af268 | [
"Apache-2.0"
] | permissive | DaveVoorhis/LDI | 99ecc41680c8d0951f9c8b22684ad74fe02e0c1d | 7ec280206adef98590b468a183e19e43b7c794b7 | refs/heads/master | 2022-10-20T22:28:25.886973 | 2022-10-09T22:01:13 | 2022-10-09T22:01:13 | 78,937,423 | 1 | 8 | null | null | null | null | UTF-8 | Java | false | false | 1,846 | java | package org.reldb.ldi.sili.values;
public class ValueInteger extends ValueAbstract {
private static final long serialVersionUID = 0;
private static final ValueInteger _zero = new ValueInteger(0);
private long internalValue;
/* Methods used by XML serialization and nothing else. */
public ValueInteger() {
}
public long getValue() {
return internalValue;
}
public void setValue(long v) {
internalValue = v;
}
/* Public methods from here on down. */
public static ValueInteger getZero() {
return _zero;
}
public ValueInteger(long b) {
internalValue = b;
}
public String getTypeName() {
return "INTEGER";
}
/** Convert this to a primitive boolean. */
public boolean booleanValue() {
return (internalValue != 0) ? true : false;
}
/** Convert this to a primitive long. */
public long longValue() {
return internalValue;
}
/** Convert this to a primitive double. */
public double doubleValue() {
return (double)internalValue;
}
/** Convert this to a primitive String. */
public String stringValue() {
return "" + internalValue;
}
public int compareTo(Value v) {
if (internalValue == v.longValue())
return 0;
else if (internalValue > v.longValue())
return 1;
else
return -1;
}
public Value add(Value v) {
return new ValueInteger(internalValue + v.longValue());
}
public Value subtract(Value v) {
return new ValueInteger(internalValue - v.longValue());
}
public Value mult(Value v) {
return new ValueInteger(internalValue * v.longValue());
}
public Value div(Value v) {
return new ValueInteger(internalValue / v.longValue());
}
public Value unary_plus() {
return new ValueInteger(internalValue);
}
public Value unary_minus() {
return new ValueInteger(-internalValue);
}
public String toString() {
return "" + internalValue;
}
}
| [
"dave@armchair.mb.ca"
] | dave@armchair.mb.ca |
b299c4e689657313594a4a8bc6b415610182954f | 14494e4c47f31b528b905c231c1b5e12367c4984 | /src/main/java/tda/darkarmy/redditclone/service/RefreshTokenService.java | 28d8b6a17ca7a126d07649d86c5ce2cfa1bcc60c | [] | no_license | ThDarkArmy/reddit-clone | b13ce8f5eb25a78b47e141b89eca6e41724f700c | b888e7125072bf6204ecd016a17d7633b108fe14 | refs/heads/master | 2022-11-22T23:09:01.205941 | 2020-07-29T05:10:42 | 2020-07-29T05:10:42 | 283,393,653 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,212 | java | package tda.darkarmy.redditclone.service;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tda.darkarmy.redditclone.exception.SpringRedditException;
import tda.darkarmy.redditclone.model.RefreshToken;
import tda.darkarmy.redditclone.repository.RefreshTokenRepository;
import java.time.Instant;
import java.util.UUID;
@Transactional
@Service
@AllArgsConstructor
@Slf4j
public class RefreshTokenService {
private final RefreshTokenRepository refreshTokenRepository;
public RefreshToken generateRefreshToken(){
RefreshToken refreshToken = new RefreshToken();
refreshToken.setToken(UUID.randomUUID().toString());
refreshToken.setCreatedDate(Instant.now());
return refreshTokenRepository.save(refreshToken);
}
public void validateRefreshToken(String token) throws SpringRedditException {
refreshTokenRepository.findByToken(token).orElseThrow(()->new SpringRedditException("Invalid refresh token."));
}
public void deleteRefreshToken(String token){
refreshTokenRepository.deleteByToken(token);
}
}
| [
"thepenseur1729@gmail.com"
] | thepenseur1729@gmail.com |
87dd460a2fbf17f54f15db70e39169f06966deae | 3df34237018eab1608e2f5ab0bf89203a93afc36 | /PersonalProjects/src/ExercisesPartThree/PointTest.java | 2e6ee6244c72b353b86998e5b3a386372aa69fed | [] | no_license | santapuri7655/PersonalProjects | 0762e1a168a71f8197b2d4e5db09347e31e14466 | 1371dfe3c2e83f697ae0b8ef6bf6b0fbba210493 | refs/heads/master | 2020-04-28T19:04:22.955802 | 2020-04-16T16:33:06 | 2020-04-16T16:33:06 | 175,499,969 | 0 | 0 | null | 2020-04-16T03:44:39 | 2019-03-13T21:13:30 | Java | UTF-8 | Java | false | false | 495 | java | package ExercisesPartThree;
public class PointTest {
public static void main(String[] args) {
Point first = new Point(6, 5);
Point second = new Point(3, 1);
System.out.println("distance(0,0)= " + first.distance());
System.out.println("distance(second)= " + first.distance(second));
System.out.println("distance(2,2)= " + first.distance(2, 2));
Point point = new Point();
System.out.println("distance()= " + point.distance());
}
}
| [
"radhika.santapuri@gmail.com"
] | radhika.santapuri@gmail.com |
d8e4616b93657429625854297fcf4d653654affa | 6ceb8f6b5400d6ca462e552c4f31a14fd2482c58 | /final_project/src/by/vasiliuk/project/command/impl/NewAdvertCommand.java | 2467920ba49a40fca725051bec3a70bc9f592f59 | [] | no_license | Mercurialcool/JWD_2019 | 2604f813d60ea5e5fe600415c79331d5e43a5971 | 897915aa8d4f04f63eebdc727070a545933f7c76 | refs/heads/master | 2022-01-01T05:17:41.311410 | 2020-02-18T08:39:26 | 2020-02-18T08:39:26 | 229,074,149 | 0 | 0 | null | 2021-12-14T21:37:41 | 2019-12-19T14:42:40 | Java | UTF-8 | Java | false | false | 974 | java | package by.vasiliuk.project.command.impl;
import by.vasiliuk.project.command.Command;
import by.vasiliuk.project.command.CommandException;
import by.vasiliuk.project.service.impl.AdvertServiceImpl;
import javax.servlet.http.HttpServletRequest;
import static by.vasiliuk.project.command.JspPath.RETURN_PAGE;
import static by.vasiliuk.project.command.ParameterName.TEXT;
import static by.vasiliuk.project.command.ParameterName.TITLE;
public class NewAdvertCommand implements Command {
//private static final long USER_ID = ;
@Override
public String execute(HttpServletRequest request) throws CommandException {
String title = request.getParameter(TITLE);
String text = request.getParameter(TEXT);
// long userId =Long.valueOf( request.getParameter(USER_ID));
AdvertServiceImpl advertServiceImpl = AdvertServiceImpl.getInstance();
//advertService.saveAdvert(title, text, userId);
return RETURN_PAGE;
}
}
| [
"vadim.minsk61@gmail.com"
] | vadim.minsk61@gmail.com |
e1564f5892cc39594ffca0b2540bb85d13fd9368 | 6ffe5d7171985038bd3df446be0a68f4aeac89d2 | /src/main/java/me/jko/pay/domain/pay/helper/CardNumberMasker.java | cbcf208c444033412997ee2685290055ba132966 | [] | no_license | junhee-ko/pay | e4817cbb3dd15a5bcaf03ae22c507a3b016b1738 | e9866d2872815d6d946428f19856271c33572ef9 | refs/heads/main | 2023-01-21T15:15:44.514271 | 2020-11-24T12:52:11 | 2020-11-24T12:52:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 481 | java | package me.jko.pay.domain.pay.helper;
import org.springframework.stereotype.Component;
@Component
public class CardNumberMasker {
private static final Character maskCharacter = '*';
public String mask(String cardNumber) {
StringBuilder stringBuilder = new StringBuilder(cardNumber);
for (int i = 6; i < stringBuilder.length() - 3; i++) {
stringBuilder.setCharAt(i, maskCharacter);
}
return stringBuilder.toString();
}
}
| [
"jko@ip-192-168-1-173.ap-northeast-2.compute.internal"
] | jko@ip-192-168-1-173.ap-northeast-2.compute.internal |
91e9f6f697450a97a87c3edf927108d9efa1e178 | 939905ff24c827b25b55f9ffe2f461243ffc4077 | /src/main/java/com/mongodb/controller/StudentController.java | 938407c4cc89707767faecefe1bf130a65be01b0 | [] | no_license | DSKostadinov/MongoDB | 6dbecf8b46760ab9befc4615ca23e92a2f433b4f | cc5f8eb49861c8e158ffcb308d42ad996d378d4c | refs/heads/main | 2023-02-13T01:31:49.574201 | 2021-01-13T22:26:52 | 2021-01-13T22:26:52 | 325,289,349 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,040 | java | package com.mongodb.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.mongodb.entity.Student;
import com.mongodb.service.StudentService;
@RestController
@RequestMapping("/api/student")
public class StudentController {
@Autowired
StudentService studentService;
@PostMapping("/create")
public Student createStudent(@RequestBody Student student) {
return studentService.createStudent(student);
}
@GetMapping("/getById/{id}")
public Student getStudentbyId(@PathVariable String id) {
return studentService.getStudentbyId(id);
}
@GetMapping("/all")
public List<Student> getAllStudents() {
return studentService.getAllStudents();
}
@PutMapping("/update")
public Student updateStudent(@RequestBody Student student) {
return studentService.updateStudent(student);
}
@DeleteMapping("/delete/{id}")
public String deleteStudent(@PathVariable String id) {
return studentService.deleteStudent(id);
}
@GetMapping("/studentsByName/{name}")
public List<Student> studentsByName(@PathVariable String name) {
return studentService.getStudentsByName(name);
}
@GetMapping("/studentsByNameAndMail")
public Student studentsByNameAndMail(@RequestParam String name,
@RequestParam String email) {
return studentService.studentsByNameAndMail(name, email);
}
@GetMapping("/studentsByNameOrMail")
public Student studentsByNameOrMail(@RequestParam String name,
@RequestParam String email) {
return studentService.studentsByNameOrMail(name, email);
}
@GetMapping("/allWithPagination")
public List<Student> getAllWithPagination(@RequestParam int pageNo,
@RequestParam int pageSize) {
return studentService.getAllWithPagination(pageNo, pageSize);
}
@GetMapping("/allWithSorting")
public List<Student> allWithSorting() {
return studentService.allWithSorting();
}
@GetMapping("/byDepartmentName")
public List<Student> byDepartmentName(@RequestParam String deptName) {
return studentService.byDepartmentName(deptName);
}
@GetMapping("/bySubjectName")
public List<Student> bySubjectName(@RequestParam String subName) {
return studentService.bySubjectName(subName);
}
@GetMapping("/nameStartsWith")
public List<Student> nameStartsWith(@RequestParam String name) {
return studentService.nameStartsWith(name);
}
@GetMapping("/byDepartmentId")
public List<Student> byDepartmentId(@RequestParam String deptId) {
return studentService.byDepartmentId(deptId);
}
}
| [
"damyan.kostadinov@gmail.com"
] | damyan.kostadinov@gmail.com |
f0ee8e828a2b95b78b78efe03ec7f223c3262816 | 0b0575943846372d64b57c6f9f199f8f8b2f7980 | /sentry-spring/src/main/java/io/sentry/spring/SentryWebConfiguration.java | 3b221e0ed22c0afa6ec7c22f956ab4f6161380f0 | [
"MIT"
] | permissive | Beezig/sentry-java | 4d7708124f8ec06661b5e17e1144c863a2b052ca | a2d52818495a1342669bd63a131d19da98c84340 | refs/heads/main | 2022-12-20T03:37:28.566749 | 2020-10-14T19:34:49 | 2020-10-14T19:34:49 | 304,087,704 | 0 | 0 | MIT | 2020-10-14T17:27:46 | 2020-10-14T17:27:45 | null | UTF-8 | Java | false | false | 1,086 | java | package io.sentry.spring;
import com.jakewharton.nopen.annotation.Open;
import io.sentry.IHub;
import io.sentry.SentryOptions;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
/** Registers Spring Web specific Sentry beans. */
@Configuration
@Open
public class SentryWebConfiguration {
@Bean
@Lazy
public @NotNull HttpServletRequestSentryUserProvider httpServletRequestSentryUserProvider(
final @NotNull SentryOptions sentryOptions) {
return new HttpServletRequestSentryUserProvider(sentryOptions);
}
@Bean
public @NotNull SentrySpringRequestListener sentrySpringRequestListener(
final @NotNull IHub sentryHub, final @NotNull SentryOptions sentryOptions) {
return new SentrySpringRequestListener(sentryHub, sentryOptions);
}
@Bean
public @NotNull SentryExceptionResolver sentryExceptionResolver(final @NotNull IHub sentryHub) {
return new SentryExceptionResolver(sentryHub);
}
}
| [
"noreply@github.com"
] | Beezig.noreply@github.com |
39fd7e35f12c6341a55809c513f5925b2167895e | 84be28816d77e98379d9b6e9c43a99c7b898f871 | /src/main/java/com/danielprinz/udemy/books/InMemoryBookStore.java | 1a7ed1aab9f884c7649c29e90ff187c05b7e72b9 | [
"MIT"
] | permissive | danielprinz/books | 2cc8049a978f1ca3db788ba30fd87a727f14d2a1 | b108d0801be33f18240ac2863bcc186985851652 | refs/heads/main | 2023-06-12T06:15:42.209589 | 2023-05-24T18:31:38 | 2023-05-24T18:31:38 | 200,527,909 | 5 | 5 | MIT | 2023-05-24T18:34:14 | 2019-08-04T18:28:53 | Java | UTF-8 | Java | false | false | 1,127 | java | package com.danielprinz.udemy.books;
import java.util.HashMap;
import java.util.Map;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
public class InMemoryBookStore {
private Map<Long, Book> books = new HashMap<>();
public InMemoryBookStore(){
books.put(1L, new Book(1L, "Vert.x in Action"));
books.put(2L, new Book(2L, "Building Microservices"));
}
public JsonArray getAll(){
JsonArray all = new JsonArray();
books.values().forEach(book -> {
all.add(JsonObject.mapFrom(book));
});
return all;
}
public void add(final Book entry) {
books.put(entry.getIsbn(), entry);
}
public Book update(final String isbn, final Book entry) {
Long key = Long.parseLong(isbn);
if (key != entry.getIsbn()) {
throw new IllegalArgumentException("ISBN does not match!");
}
books.put(key, entry);
return entry;
}
public Book get(final String isbn) {
Long key = Long.parseLong(isbn);
return books.get(key);
}
public Book delete(final String isbn) {
Long key = Long.parseLong(isbn);
return books.remove(key);
}
}
| [
"daniel.prinz@outlook.com"
] | daniel.prinz@outlook.com |
8a0401c698d10a744bb5debfc2028bbc9ecc49e5 | 26b7f30c6640b8017a06786e4a2414ad8a4d71dd | /src/number_of_direct_superinterfaces/i6424.java | 55ec4ccabfafe0ff7f3696c1874ecdd4bf4a4976 | [] | no_license | vincentclee/jvm-limits | b72a2f2dcc18caa458f1e77924221d585f23316b | 2fd1c26d1f7984ea8163bc103ad14b6d72282281 | refs/heads/master | 2020-05-18T11:18:41.711400 | 2014-09-14T04:25:18 | 2014-09-14T04:25:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 68 | java | package number_of_direct_superinterfaces;
public interface i6424 {} | [
"vincentlee.dolbydigital@yahoo.com"
] | vincentlee.dolbydigital@yahoo.com |
f6ab7706085116eeec0f4fb1705a43ce590f16a9 | 3b6f84602b358c8a4edbd3cffb8488a4d7674bf9 | /src/main/java/ru/zinin/myexpenses/repo/CategoryRepo.java | 885815163444876cfee5eec22afddfadcba690fe | [] | no_license | daboggg/my-expenses | ad197a9de24c8ecf0b3d8e4d5e9ea1a3aee14103 | fb5738935309b30a23354d2c76a38ab5f361b99a | refs/heads/master | 2023-01-23T08:40:01.580011 | 2019-12-04T14:33:24 | 2019-12-04T14:33:24 | 218,048,473 | 0 | 0 | null | 2023-01-04T23:48:16 | 2019-10-28T13:05:39 | Vue | UTF-8 | Java | false | false | 395 | java | package ru.zinin.myexpenses.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.zinin.myexpenses.model.Category;
import ru.zinin.myexpenses.model.User;
import java.util.List;
public interface CategoryRepo extends JpaRepository<Category, Long> {
List<Category> getAllByUsr(User user);
List<Category> getByName(String name);
Category getById(Long id);
}
| [
"daboggg@ya.ru"
] | daboggg@ya.ru |
7d35dfd9aef2ba8dc4150e89fc9733448d73807c | 6edf0f9b30a0d2fc1828858bc62da5990eff8874 | /MyApplication/app/src/main/java/com/example/andrea/myapplication/MainActivity.java | 4cdeff794b98ef38154052880ba2040f8fddf03a | [] | no_license | andreapadula/Android-OpenGL | 349aaa7a5cdd1f4547a0a94c0eae5b4bf72f1ca3 | 0a721f3e9783de65254d46a1b580b371cc6f5293 | refs/heads/master | 2020-03-21T22:05:24.507577 | 2018-06-29T05:22:57 | 2018-06-29T05:22:57 | 139,103,086 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 345 | java | package com.example.andrea.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
| [
"andrea@Andreas-MacBook-Pro.local"
] | andrea@Andreas-MacBook-Pro.local |
b8ca1db1220688fcfe36e1a97de6bc7782ef9deb | dcd2419c93155a8f5043370782b7b55b45acf0c4 | /TRAINING1/src/com/lti/servlets/DeleteUserServlet.java | 928d9ec92414934911b52f560aee8b25e00e8a7f | [] | no_license | SAKSHIGUPTA3198/Servletup | 8ae92ec0bc780dd2eb2a0add79f309ebf1a8d1ad | 10c8d966ec5fada6aec4f9de5eb4f0f360836ffb | refs/heads/master | 2020-09-07T19:35:42.113049 | 2019-11-11T03:35:19 | 2019-11-11T03:35:19 | 220,893,389 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 936 | java | package com.lti.servlets;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.lti.service.Read;
public class DeleteUserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String trainingid = request.getParameter("trainingid");
Read service = new Read();
boolean result = service.removeUser(trainingid);
//if (result){
// List<Users> users = service.findAllUsers();
// request.setAttribute("UsersList", users);
// }
RequestDispatcher rd = request.getRequestDispatcher("show.view");
rd.forward(request,response);
}
}
| [
"sakshigupta3198@gmail.com`"
] | sakshigupta3198@gmail.com` |
f718fa9c7e4fa71e1e438cdbe53c27d738318dd9 | 2d815b23b3b5c1c9110eedeac30a60063dea349c | /lingmoney-dao/src/main/java/com/mrbt/lingmoney/mapper/UnfreezeFlowMapper.java | 5658d259197f27060cb2833455c09dff21b2e75c | [] | no_license | shiwuyisheng/lingmoney | 9f7a9e1216017cf3a0762e42a1f1f6fdeebda8ba | 19cafe72b8dbc7100bec40415c431e969227057f | refs/heads/master | 2020-06-13T20:53:31.503482 | 2018-06-15T03:37:41 | 2018-06-15T03:37:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,252 | java | package com.mrbt.lingmoney.mapper;
import com.mrbt.lingmoney.model.UnfreezeFlow;
import com.mrbt.lingmoney.model.UnfreezeFlowExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface UnfreezeFlowMapper {
/**
* 根据指定的条件获取数据库记录数,unfreeze_flow
*
* @param example
*/
long countByExample(UnfreezeFlowExample example);
/**
* 根据指定的条件删除数据库符合条件的记录,unfreeze_flow
*
* @param example
*/
int deleteByExample(UnfreezeFlowExample example);
/**
* 根据主键删除数据库的记录,unfreeze_flow
*
* @param id
*/
int deleteByPrimaryKey(Integer id);
/**
* 新写入数据库记录,unfreeze_flow
*
* @param record
*/
int insert(UnfreezeFlow record);
/**
* 动态字段,写入数据库记录,unfreeze_flow
*
* @param record
*/
int insertSelective(UnfreezeFlow record);
/**
* 根据指定的条件查询符合条件的数据库记录,unfreeze_flow
*
* @param example
*/
List<UnfreezeFlow> selectByExample(UnfreezeFlowExample example);
/**
* 根据指定主键获取一条数据库记录,unfreeze_flow
*
* @param id
*/
UnfreezeFlow selectByPrimaryKey(Integer id);
/**
* 动态根据指定的条件来更新符合条件的数据库记录,unfreeze_flow
*
* @param record
* @param example
*/
int updateByExampleSelective(@Param("record") UnfreezeFlow record, @Param("example") UnfreezeFlowExample example);
/**
* 根据指定的条件来更新符合条件的数据库记录,unfreeze_flow
*
* @param record
* @param example
*/
int updateByExample(@Param("record") UnfreezeFlow record, @Param("example") UnfreezeFlowExample example);
/**
* 动态字段,根据主键来更新符合条件的数据库记录,unfreeze_flow
*
* @param record
*/
int updateByPrimaryKeySelective(UnfreezeFlow record);
/**
* 根据主键来更新符合条件的数据库记录,unfreeze_flow
*
* @param record
*/
int updateByPrimaryKey(UnfreezeFlow record);
} | [
"252544983@qq.com"
] | 252544983@qq.com |
084e86fbc86dd3b53719c44d19120e31f65af2b9 | b94e5c99dd5454e903511b0ca31b4b4e21c92ce3 | /W2D1/W2D1/src/StaticCar/Car.java | 7fe0277636c6747db6d181eb843fe9e3572ff52b | [] | no_license | kent7777777/CS203 | 183629ee3fd86250bf52da4800e244f26b30b722 | e549ab04137992c95a0bb8026be062dc08b692d0 | refs/heads/master | 2016-09-09T22:18:37.994250 | 2015-03-19T15:01:47 | 2015-03-19T15:01:47 | 31,226,437 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 898 | java | package StaticCar;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Kevin
*/
public class Car {
private int x;
private int y;
public static void sety(Car This, int y){
This.y = y;
}
public static void setx(Car This,int x){
This.x = x;
}
public static void moveUp(Car This, int a){
This.y = This.y + a;
}
public static void moveDown(Car This, int a){
This.y = This.y - a;
}
public static void moveRight(Car This, int a){
This.x = This.x + a;
}
public static void moveLeft(Car This, int a){
This.x = This.x - a;
}
public static String printLocation(Car This){
return This.x + " " + This.y;
}
}
| [
"coolkent7777777@gmail.com"
] | coolkent7777777@gmail.com |
679d0a4a6d3801c97fe953504180bbd9da615e02 | 1b5ab622e1c3340a3bf537ba3f5c9d8eee740e29 | /1.JavaSyntax/src/com/javarush/task/task03/task0313/Solution.java | 3aa4dea02d8bffd888c332e3daae87ba178c326a | [] | no_license | NikonoffSE/JavaRushTasks | 1ac1a626708041f36a380e92390f98175f4fd715 | 85c87998d6c8fe94bc888ebb0afe0c08bd41f241 | refs/heads/master | 2020-04-17T11:25:03.116165 | 2019-05-15T08:19:04 | 2019-05-15T08:19:04 | 166,539,702 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 713 | java | package com.javarush.task.task03.task0313;
/*
Мама мыла раму
*/
public class Solution {
public static void main(String[] args) {
String a = "Мама";
String b = "Мыла";
String c = "Раму";
System.out.print(a + b + c);
System.out.println("");
System.out.print(a + c + b);
System.out.println("");
System.out.print(b + a + c);
System.out.println("");
System.out.print(b + c + a);
System.out.println("");
System.out.print(c + a + b);
System.out.println("");
System.out.print(c + b + a);
//System.out.println("");
//напишите тут ваш код
}
}
| [
"noreply@github.com"
] | NikonoffSE.noreply@github.com |
6cd4f43b8330dd2e6d4d133f5533fd52a626af9b | 0156071ecbe4d599a447857362930b804f2b5f5b | /space-common/space-common-data/src/main/java/com/zcloud/space/common/data/tenant/TenantContextHolderFilter.java | 0b40dc1a4bcb6d53ef8a5a787e388ace15ae4935 | [] | no_license | gdzzp1989/space | 2fd128edcbf9ee14a3a1332c459f8d9d74be6047 | b6f859b11924a4666206d9da8be762fb652feef9 | refs/heads/master | 2022-11-28T00:37:33.182240 | 2020-08-12T07:28:27 | 2020-08-12T07:28:27 | 286,946,635 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,402 | java | package com.zcloud.space.common.data.tenant;
import cn.hutool.core.util.StrUtil;
import com.zcloud.space.common.core.constant.Constants;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @Description
* @Author
* @Date
*/
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class TenantContextHolderFilter extends GenericFilterBean {
@Override
@SneakyThrows
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String tenantId = request.getHeader(Constants.TENANT_ID);
log.debug("获取header中的租户ID为:{}", tenantId);
if (StrUtil.isNotBlank(tenantId)) {
TenantContextHolder.setTenantId(Integer.parseInt(tenantId));
} else {
TenantContextHolder.setTenantId(1);
}
filterChain.doFilter(request, response);
TenantContextHolder.clear();
}
}
| [
"123456"
] | 123456 |
638c51e44eb5e5f79f5bb8c2191dc7cee060963c | a266d6856ecdcca63343ee214b6210b7d0391b57 | /chapter_server_socket/src/main/java/ru/pimalex1978/mjc/server/RequestHandler.java | 48a2179b7336ddf764ffe26e590322573c4f3ee7 | [] | no_license | alexander-pimenov/javalesson | 21aced7983d22daafc1e8dcb43341d2515ff7076 | 35b79e63279aaef94b8812f2ca9bc51212b9d952 | refs/heads/master | 2023-05-26T06:21:53.710359 | 2023-05-23T19:00:29 | 2023-05-23T19:00:29 | 226,805,717 | 0 | 0 | null | 2023-03-04T11:55:45 | 2019-12-09T06:58:50 | Java | UTF-8 | Java | false | false | 4,881 | java | package ru.pimalex1978.mjc.server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.Socket;
import java.util.Arrays;
import java.util.List;
/**
* Класс, который занимается отображением и обработкой наших запросов.
* Выводит информацию на страницу.
*/
public class RequestHandler {
private static final String FREE_SPACE = "<br><br><br>";
private static final String HTML_START = "<html><body>";
private static final String HTML_END = "</body></html>";
private static final String HTML_FORM = "<form method='POST'>" +
"<input name='param' type='text'/>" +
"<input type='submit'/>" +
"</form>";
private static final String DELIMETER = " --------------------- --------------------- ----------- \n";
private static final String HOME_PAGE = "<h1>Tech Talk server_side of network!</h1>";
private static final String MESSAGE_PAGE = "<h1>Welcome to MESSAGE PAGE</h1>";
private static final List<String> HANDLED_REQUEST = Arrays.asList("/", "/msg");
private static final Logger log = LoggerFactory.getLogger(RequestHandler.class);
private static String payload = null;
public static void handleRequest(Socket socket) throws IOException {
OutputStream os = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
Request request = new Request(reader);
if (!request.parse()) {
respond(500, "Unable to parse request", os);
return;
}
log.info(DELIMETER);
log.info("Request path: " + request.getPath());
log.info("Request Query: " + request.getQueryParameters());
log.info(DELIMETER);
String responseHtml = null;
switch (request.getPath()) {
case "/msg":
responseHtml = handleMessagePage(request);
break;
default:
responseHtml = handleRequestMethod(request, HOME_PAGE);
}
String result = getResponse(responseHtml) + responseHtml;
os.write(result.getBytes());
os.flush();
reader.close();
}
private static String getResponse(String responseHtml) {
return "HTTP/1.1 200 OK\r\n"
+ "Server: Server\r\n"
+ "Content-Type: text/html\r\n"
+ "Content-Length: "
+ responseHtml.length()
+ "\r\n"
+ "Connection: close\r\n\r\n";
}
private static void respond(int statusCode, String msg, OutputStream out) throws IOException {
String responseLine = "HTTP/1.1 " + statusCode + " " + msg + "\r\n\r\n";
log.info(responseLine);
out.write(responseLine.getBytes());
}
private static String handleMessagePage(Request request) throws IOException {
return handleRequestMethod(request, MESSAGE_PAGE);
}
private static String handleRequestMethod(Request request, String pageTitle) throws IOException {
StringBuffer generatedRequestHtml = new StringBuffer();
generatedRequestHtml.append(HTML_START);
if (request.getMethod().equals("POST")) {
BufferedReader reader = request.getInputReader();
String payload = "<div><h1>Payload DATA from POST = </h1>" + getPostPayloadData(reader) + "</div>" + FREE_SPACE;
generatedRequestHtml.append(pageTitle + FREE_SPACE);
generatedRequestHtml.append(payload);
request.getHeaders().forEach(
(key, value) ->
generatedRequestHtml.append(
"<p style='margin: 0; padding: 0;'><b>" + key + ": </b>" + value + "</p>"));
generatedRequestHtml.append(HTML_END);
} else {
generatedRequestHtml.append(pageTitle + FREE_SPACE);
request.getHeaders().forEach(
(key, value) ->
generatedRequestHtml.append(
"<p style='margin: 0; padding: 0;'><b>" + key + ": </b>" + value + "</p>"));
generatedRequestHtml.append(FREE_SPACE + HTML_FORM + HTML_END);
}
return String.valueOf(generatedRequestHtml);
}
private static String getPostPayloadData(BufferedReader bufferedReader) throws IOException {
String body = null;
StringBuilder stringBuilder = new StringBuilder();
char[] charBuffer = new char[128];
int bytesRead = -1;
bytesRead = bufferedReader.read(charBuffer);
stringBuilder.append(charBuffer, 0, bytesRead);
body = stringBuilder.toString();
return body;
}
}
| [
"pimalex1978@yandex.ru"
] | pimalex1978@yandex.ru |
9f7a7526bca942195400ecf9e441690e57105760 | 76e49fea4a6278d26742974c3e489493153b1270 | /src/main/java/sample3/Point.java | ecf932376dea21d42cab615d70c2617f8f449323 | [] | no_license | kimmmkihyun/Spring-01_DI_CircleExam | 9bc012ea4b219e75dd17f2f85f0bfd8d7521736a | 05afb77c81973311a64ac7be96661fb3b8d35e52 | refs/heads/master | 2022-12-24T03:44:52.433897 | 2020-10-06T08:13:47 | 2020-10-06T08:13:47 | 301,657,998 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 178 | java | package sample3;
public interface Point {
public double getXpos();
public void setXpos(double xpos);
public double getYpos();
public void setYpos(double ypos);
}
| [
"admin@DESKTOP-BK9EMJ0"
] | admin@DESKTOP-BK9EMJ0 |
2543752eedebfbef062c6874dfef12cf139d0a63 | 371269050058ac782dff2cfd91a88902c54b4949 | /MusicPlays/src/main/java/com/example/musicplays/MainActivity.java | 523e0851839516fb26461c05d44329f7ff478a7c | [] | no_license | Remember888/MyApplication | 5498cdcf43eae3ce9e5ce1541e95a972ed46ade3 | 67bc6538d36751325900a383a1fff9f4082a29bf | refs/heads/master | 2020-09-07T07:59:15.232451 | 2017-06-15T09:23:09 | 2017-06-15T09:23:09 | 94,422,742 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,054 | java | package com.example.musicplays;
import android.Manifest;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},100);
}
public void onClick01(View v) {
Intent intent = new Intent(this, MyService.class);
intent.putExtra("action", MyService.PLAY);
startService(intent);
}
public void onClick02(View v) {
Intent intent = new Intent(this, MyService.class);
intent.putExtra("action", MyService.PAUST);
startService(intent);
}
public void onClick03(View v) {
Intent intent = new Intent(this, MyService.class);
intent.putExtra("action", MyService.STOP);
startService(intent);
}
}
| [
"1305295223@qq.com"
] | 1305295223@qq.com |
6bd7771d88a31950b691ef1b1b7aedfaff54eded | e79f2c4d4e79bb4115b96e8607c98e9561b5d4d8 | /test/ar/edu/unq/tp8/tests/PokerStatusTest.java | a37cdd590cb7ff75d6b13655632bd9f3c2231662 | [] | no_license | NahuelMendez/unqui-po2-mendez | 865048bf54e77fa096261ab6892f32fdb169fa73 | c894d4e1ccb526c75cdc1c1ef98619331b89ffef | refs/heads/master | 2022-11-15T00:48:18.497053 | 2020-07-06T03:39:33 | 2020-07-06T03:39:33 | 255,412,775 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,438 | java | package ar.edu.unq.tp8.tests;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import ar.edu.unq.tp8.Carta;
import ar.edu.unq.tp8.Jugada;
import ar.edu.unq.tp8.PokerStatus;
import static org.mockito.Mockito.*;
class PokerStatusTest {
private Carta carta4P;
private Carta carta4D;
private Carta carta4C;
private Carta carta4T;
private Carta carta5T;
private Carta carta3P;
private Carta carta2D;
private Carta carta6P;
private Jugada jugada1;
private Jugada jugada2;
private PokerStatus pokerStatus;
@BeforeEach
public void setUp() {
carta4P = new Carta("4", "P");
carta4D = new Carta("4", "D");
carta4C = new Carta("4", "C");
carta4T = new Carta("4", "T");
carta5T = new Carta("5", "T");
carta3P = new Carta("3", "P");
carta2D = new Carta("2", "D");
carta6P = new Carta("6", "P");
jugada1 = new Jugada(carta4P, carta4D, carta4T, carta4C, carta6P);
jugada2 = new Jugada(carta4T, carta4D, carta4P, carta6P, carta5T);
pokerStatus = new PokerStatus();
}
@Test
void testPokerStatusVerificaPokerEnUnaJugada() {
Boolean result = pokerStatus.verificarPoker(carta4P, carta4D, carta4C, carta4T, carta5T);
assertTrue(result);
}
@Test
void testPokerStatusVerificaQueNoEsPokerEnUnaJugada() {
Boolean result = pokerStatus.verificarPoker(carta4P, carta3P, carta2D, carta6P, carta5T);
assertFalse(result);
}
@Test
void testUnPokerStatusAlVerificarUnaManoDeterminaPoker() {
String result = pokerStatus.verificar(carta4P, carta4D, carta4C, carta4T, carta5T);
assertEquals("Poker", result);
}
@Test
void testUnPokerStatusAlVerificarUnaManoDeterminaColor() {
Carta carta2T = mock(Carta.class);
Carta carta9T = mock(Carta.class);
Carta cartaJT = mock(Carta.class);
when(carta2T.getPalo()).thenReturn("T");
when(carta9T.getPalo()).thenReturn("T");
when(cartaJT.getPalo()).thenReturn("T");
String result = pokerStatus.verificar(carta2T, carta9T, cartaJT, carta4T, carta5T);
assertEquals("Color", result);
}
@Test
void testUnPokeStatusAlVerificarUnaManoDeterminaTrio() {
String result = pokerStatus.verificar(carta4P, carta4D, carta4C, carta6P, carta5T);
assertEquals("Trio", result);
}
@Test
void testUnPokerEstatusComparaJugada1YJugada2YDeclaraGanadorAJugada1() {
Jugada result = pokerStatus.jugadaGanadoraContra(jugada1, jugada2);
assertEquals(jugada1, result);
}
}
| [
"mendez.nahuel@outlook.com"
] | mendez.nahuel@outlook.com |
4b311ef11a742de5d6b7021b38589f4c8b88ccb7 | cca87c4ade972a682c9bf0663ffdf21232c9b857 | /com/tencent/mm/plugin/x/a.java | 36f9b12ea765901b7be0548849f7c03634622742 | [] | no_license | ZoranLi/wechat_reversing | b246d43f7c2d7beb00a339e2f825fcb127e0d1a1 | 36b10ef49d2c75d69e3c8fdd5b1ea3baa2bba49a | refs/heads/master | 2021-07-05T01:17:20.533427 | 2017-09-25T09:07:33 | 2017-09-25T09:07:33 | 104,726,592 | 12 | 1 | null | null | null | null | UTF-8 | Java | false | false | 438 | java | package com.tencent.mm.plugin.x;
import com.tencent.mm.modelcontrol.c;
import com.tencent.mm.u.l;
public final class a extends l {
private static a ooH;
public static synchronized a aSP() {
a aVar;
synchronized (a.class) {
if (ooH == null) {
ooH = new a();
}
aVar = ooH;
}
return aVar;
}
private a() {
super(c.class);
}
}
| [
"lizhangliao@xiaohongchun.com"
] | lizhangliao@xiaohongchun.com |
719c73569fa1d27fcafaa57741f735622b366cd3 | de0cadcbee469feeabc183c23e7ed5cb7f580f17 | /renderers/src/test/java/com/pedrogomez/renderers/PagerRendererAdapterTest.java | dbfcebfc5e4db06bcd318e2137f467f274b8dbfc | [
"Apache-2.0"
] | permissive | tuenti/Renderers | 67a3f739fa1461d7327d727ed43b8be9b8f281df | 388ed00802e0ddddde11c482c694f989577c4658 | refs/heads/master | 2020-12-31T05:57:07.204321 | 2017-02-01T18:42:16 | 2017-02-01T18:42:16 | 80,632,145 | 0 | 0 | null | 2017-02-01T15:15:13 | 2017-02-01T15:15:12 | null | UTF-8 | Java | false | false | 4,491 | java | package com.pedrogomez.renderers;
import java.util.Collection;
import java.util.LinkedList;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.notNull;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.pedrogomez.renderers.exception.NullRendererBuiltException;
@Config(emulateSdk = 16) @RunWith(RobolectricTestRunner.class) public class PagerRendererAdapterTest {
private static final int ANY_SIZE = 11;
private static final int ANY_POSITION = 2;
private static final Object ANY_OBJECT = new Object();
private static final Collection<Object> ANY_OBJECT_COLLECTION = new LinkedList<>();
private PagerRendererAdapter<Object> adapter;
@Mock private RendererBuilder mockedRendererBuilder;
@Mock private AdapteeCollection<Object> mockedCollection;
@Mock private View mockedConvertView;
@Mock private ViewGroup mockedParent;
@Mock private ObjectRenderer mockedRenderer;
@Mock private View mockedView;
@Before public void setUp() throws Exception {
initializeMocks();
initializeRVRendererAdapter();
}
@Test public void shouldReturnTheAdapteeCollection() {
assertEquals(mockedCollection, adapter.getCollection());
}
@Test public void shouldReturnCollectionSizeOnGetCount() {
when(mockedCollection.size()).thenReturn(ANY_SIZE);
assertEquals(ANY_SIZE, adapter.getCount());
}
@Test public void shouldReturnItemAtCollectionPositionOnGetItem() {
when(mockedCollection.get(ANY_POSITION)).thenReturn(ANY_OBJECT);
}
@Test public void shouldBuildRendererUsingAllNeededDependencies() {
when(mockedCollection.get(ANY_POSITION)).thenReturn(ANY_OBJECT);
when(mockedRenderer.getRootView()).thenReturn(mockedView);
when(mockedRendererBuilder.build()).thenReturn(mockedRenderer);
adapter.instantiateItem(mockedParent, ANY_POSITION);
verify(mockedRendererBuilder).withContent(ANY_OBJECT);
verify(mockedRendererBuilder).withParent(mockedParent);
verify(mockedRendererBuilder).withLayoutInflater((LayoutInflater) notNull());
}
@Test public void shouldAddElementToAdapteeCollection() {
adapter.add(ANY_OBJECT);
verify(mockedCollection).add(ANY_OBJECT);
}
@Test public void shouldAddAllElementsToAdapteeCollection() {
adapter.addAll(ANY_OBJECT_COLLECTION);
verify(mockedCollection).addAll(ANY_OBJECT_COLLECTION);
}
@Test public void shouldRemoveElementFromAdapteeCollection() {
adapter.remove(ANY_OBJECT);
verify(mockedCollection).remove(ANY_OBJECT);
}
@Test public void shouldRemoveAllElementsFromAdapteeCollection() {
adapter.removeAll(ANY_OBJECT_COLLECTION);
verify(mockedCollection).removeAll(ANY_OBJECT_COLLECTION);
}
@Test public void shouldClearElementsFromAdapteeCollection() {
adapter.clear();
verify(mockedCollection).clear();
}
@Test public void shouldSetAdapteeCollection() throws Exception {
RVRendererAdapter<Object> adapter = new RVRendererAdapter<Object>(mockedRendererBuilder);
adapter.setCollection(mockedCollection);
assertEquals(mockedCollection, adapter.getCollection());
}
@Test public void shouldBeEmptyWhenItsCreatedWithJustARendererBuilder() {
RVRendererAdapter<Object> adapter = new RVRendererAdapter<Object>(mockedRendererBuilder);
assertEquals(0, adapter.getItemCount());
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExceptionWhenSetNullCollection() {
RVRendererAdapter<Object> adapter = new RVRendererAdapter<Object>(mockedRendererBuilder);
adapter.setCollection(null);
}
@Test(expected = NullRendererBuiltException.class)
public void shouldThrowNullRendererBuiltException() {
adapter.instantiateItem(mockedParent, ANY_POSITION);
}
private void initializeMocks() {
MockitoAnnotations.initMocks(this);
when(mockedParent.getContext()).thenReturn(Robolectric.application);
}
private void initializeRVRendererAdapter() {
adapter = new PagerRendererAdapter<>(mockedRendererBuilder, mockedCollection);
adapter = spy(adapter);
}
}
| [
"mvera@tuenti.com"
] | mvera@tuenti.com |
ef9b9a8ca118749e644cc0af7bdb26b6e151883f | d78dacfa28232c43cfc0283d6c7013e35b934c59 | /src/main/java/de/fbeutel/poe/pricingagent/stash/domain/Currency.java | a6fcb1b5fc968928a71518620a96c9c58abef9ee | [] | no_license | ferencbeutel4711/pricingagent | 6daf867d12313c88e1a38faff3a2901c3141be67 | 11d4ee91953764743cec321dae25db14df11b102 | refs/heads/master | 2020-03-30T10:36:27.439131 | 2018-10-04T21:13:18 | 2018-10-04T21:13:18 | 151,127,515 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,752 | java | package de.fbeutel.poe.pricingagent.stash.domain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public enum Currency {
CHAOS, EXALTED, REGAL, ALTERATION, JEWELLERS, FUSING, REGRET, DIVINE, ALCHEMY, CHANCE, VAAL,
CHROMA, SCOURING, CHISEL, GEMCUTTERS, UNKNOWN, BLESSED;
private static final Logger logger = LoggerFactory.getLogger(Currency.class);
public static Currency parseString(final String currencySubString) {
switch (sanitize(currencySubString.toLowerCase())) {
case "chaos":
return CHAOS;
case "exa":
return EXALTED;
case "alt":
return ALTERATION;
case "jew":
return JEWELLERS;
case "fuse":
return FUSING;
case "regret":
return REGRET;
case "divine":
return DIVINE;
case "alchemy":
case "alch":
return ALCHEMY;
case "vaal":
return VAAL;
case "chance":
return CHANCE;
case "chisel":
return CHISEL;
case "chroma":
case "chrom":
return CHROMA;
case "scouring":
case "scour":
return SCOURING;
case "gcp":
return GEMCUTTERS;
case "regal":
return REGAL;
case "blessed":
return BLESSED;
}
logger.warn("unknown Currency!: {}", currencySubString);
return UNKNOWN;
}
private static final String sanitize(final String unsanitized) {
return unsanitized.replaceAll("[^a-zA-Z]+", "");
}
}
| [
"ferenc1993beutel@gmx.de"
] | ferenc1993beutel@gmx.de |
b02a526e4b9359e28e06f90bce8a2c8201a36f36 | 0fcc9b414028f7234dbf544d6017dbea3c6127a4 | /src/day48_Inheritance/AnimalTask/Dog.java | e427b5dc78997a267b52ce8c7b8a785e692297d7 | [] | no_license | Amanuel-web/B20 | e3d3ba50bc8fe2cde11b9ee1bcb4b680b3a32397 | 46c0c1d166dc7aebf334b1113bc1a55946629b19 | refs/heads/main | 2023-05-11T13:38:27.611877 | 2021-05-27T05:29:22 | 2021-05-27T05:29:22 | 371,257,982 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 253 | java | package day48_Inheritance.AnimalTask;
public class Dog extends Animal{
public Dog(String name,String size,int age,char sex){
setInfo(name, size,age,sex);
}
public void bark(){
System.out.println(name+" Barking");
}
}
| [
"girmayamanuel23@gmail.com"
] | girmayamanuel23@gmail.com |
54bf99437c9d25ef39cadf3309be063fd0ceb6cf | 82e8f1c08c1cb4396b1ba8447d46d9435146e501 | /src/main/java/com/markerhub/service/impl/UserServiceImpl.java | 2efee38ac8bc91b55d250e435ca71b6a7d9695e7 | [] | no_license | houlei654/vueblog | ac4526733ec160b685dca2a049acdb0e3415ce61 | 7d8dcb431a589efc466a0f1a858378d942d98002 | refs/heads/master | 2023-04-21T06:17:23.282700 | 2021-04-26T09:46:26 | 2021-04-26T09:46:26 | 359,844,959 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 416 | java | package com.markerhub.service.impl;
import com.markerhub.entity.User;
import com.markerhub.mapper.UserMapper;
import com.markerhub.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
| [
"1224908728@qq.com"
] | 1224908728@qq.com |
67226ea55292c2bd37a6a2c396dfc517d5d337bd | c0738780465fbbea07e04fb775eb479d76458b84 | /Graph_Area/Graph_Area.java | 7899953e5f795f3fb0b2ce2fc7a81dfebfb9ac0e | [] | no_license | darkjogger/old_projects | af4d1fa7d44aa00f1223587639ff1e993b222cc6 | a79cc2551a5e1244e689018e1163c441d05c056c | refs/heads/master | 2020-08-29T16:47:16.312111 | 2019-10-30T08:21:38 | 2019-10-30T08:21:38 | 218,098,084 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,713 | java | import java.util.Scanner;
abstract class Graph{
abstract double getA();
}
class Triangle extends Graph{
private double x,y,z;
public Triangle(int l1,int l2,int l3){
this.x = (double)l1;
this.y = (double)l2;
this.z = (double)l3;
}
public double getA(){
double p = (x+y+z)/2;
return Math.sqrt(p*(p-x)*(p-y)*(p-z));
}
}
class Rectangle extends Graph{
private double x,y;
public Rectangle(int l1,int l2){
this.x = (double)l1;
this.y = (double)l2;
}
public double getA(){
return x*y;
}
}
public class Graph_Area{
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int n = console.nextInt();
console.nextLine();
String[][] input = new String[n][];
double[] output = new double[n];
for (int i =0; i<n; i++) {
String temp = console.nextLine();
input[i] =temp.split(" ");
}
console.close();
for (int i =0; i<n; i++) {
int len = input[i].length;
int[] intArr = new int[len];
for(int j = 0; j <len; j++) {
intArr[j] = Integer.parseInt( input[i][j]);
}
//System.out.println(Arrays.toString(intArr));
if (len == 2) {
Rectangle r = new Rectangle(intArr[0], intArr[1]);
output[i]= r.getA();
}
if (len == 3) {
Triangle t = new Triangle(intArr[0], intArr[1], intArr[2]);
output[i]= t.getA();
}
}
for (double i : output) {
System.out.println(i);
}
}
} | [
"binggao@uvic.ca"
] | binggao@uvic.ca |
d0927f6c9580636cb77b12ace8cfee295b49cd6c | 295de54ea58532392077154e42094452786dd69b | /Problems/1. Beginner/1007 - Difference/Main.java | 2934aae57b686ad3c71663625d9cf8b6181d0b49 | [] | no_license | JeffersonCN/uri-online-judge-solutions | 66888d4f6be24f4ef6e0ee1273d63a4e4b033a75 | e5b354945fc6e9aa91342496e0799bea3921341d | refs/heads/master | 2020-12-24T19:28:15.531889 | 2016-04-18T15:29:24 | 2016-04-18T15:29:24 | 56,413,248 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 504 | java | // PROBLEM URL: https://www.urionlinejudge.com.br/judge/en/problems/view/1007
import java.util.Scanner;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in).useLocale(Locale.US);
int a = scan.nextInt();
int b = scan.nextInt();
int c = scan.nextInt();
int d = scan.nextInt();
int diferenca = a*b-c*d;
System.out.println(String.format("DIFERENCA = %d", diferenca));
}
} | [
"jefferson.nascimento3@fatec.sp.gov.br"
] | jefferson.nascimento3@fatec.sp.gov.br |
2ec25420eee230f41282ade89e2336944b9a5613 | b2ede73e019d6b13472451b0051df1723b1eb34f | /adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vdu/mapper/VfModuleCustomizationToVduMapper.java | f6442b625275ebf374094651997731a049ad6d65 | [
"Apache-2.0"
] | permissive | msyoon222/so | 3890986816f0dfb16625d2f604fed72eee2cdb3d | 9898169afc2281162121c298e8bb88c56f6fd6c7 | refs/heads/master | 2020-04-13T20:48:48.983260 | 2018-12-26T14:08:00 | 2018-12-26T14:08:00 | 163,440,159 | 0 | 0 | Apache-2.0 | 2018-12-28T18:47:52 | 2018-12-28T18:47:52 | null | UTF-8 | Java | false | false | 5,071 | java | /*-
* ============LICENSE_START=======================================================
* ONAP - SO
* ================================================================================
* Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.onap.so.adapters.vdu.mapper;
import java.util.List;
import org.onap.so.adapters.vdu.VduModelInfo;
import org.onap.so.adapters.vdu.VduArtifact;
import org.onap.so.adapters.vdu.VduArtifact.ArtifactType;
import org.onap.so.db.catalog.beans.HeatEnvironment;
import org.onap.so.db.catalog.beans.HeatFiles;
import org.onap.so.db.catalog.beans.HeatTemplate;
import org.onap.so.db.catalog.beans.VfModuleCustomization;
import org.springframework.stereotype.Component;
@Component
public class VfModuleCustomizationToVduMapper {
public VduModelInfo mapVfModuleCustomizationToVdu(VfModuleCustomization vfModuleCustom)
{
VduModelInfo vduModel = new VduModelInfo();
vduModel.setModelCustomizationUUID(vfModuleCustom.getModelCustomizationUUID());
// Map the cloud templates, attached files, and environment file
mapCloudTemplates(vfModuleCustom.getVfModule().getModuleHeatTemplate(), vduModel);
mapCloudFiles(vfModuleCustom,vduModel);
mapEnvironment(vfModuleCustom.getHeatEnvironment(), vduModel);
return vduModel;
}
public VduModelInfo mapVfModuleCustVolumeToVdu(VfModuleCustomization vfModuleCustom)
{
VduModelInfo vduModel = new VduModelInfo();
vduModel.setModelCustomizationUUID(vfModuleCustom.getModelCustomizationUUID());
// Map the cloud templates, attached files, and environment file
mapCloudTemplates(vfModuleCustom.getVfModule().getVolumeHeatTemplate(), vduModel);
mapCloudFiles(vfModuleCustom,vduModel);
mapEnvironment(vfModuleCustom.getVolumeHeatEnv(), vduModel);
return vduModel;
}
private void mapCloudTemplates(HeatTemplate heatTemplate, VduModelInfo vduModel) {
// TODO: These catalog objects will be refactored to be non-Heat-specific
List<VduArtifact> vduArtifacts = vduModel.getArtifacts();
// Main template. Also set the VDU timeout based on the main template.
vduArtifacts.add(mapHeatTemplateToVduArtifact(heatTemplate, ArtifactType.MAIN_TEMPLATE));
vduModel.setTimeoutMinutes(heatTemplate.getTimeoutMinutes());
// Nested templates
List<HeatTemplate> childTemplates = heatTemplate.getChildTemplates();
if (childTemplates != null) {
for(HeatTemplate childTemplate : childTemplates){
vduArtifacts.add(mapHeatTemplateToVduArtifact(childTemplate, ArtifactType.NESTED_TEMPLATE));
}
}
}
private VduArtifact mapHeatTemplateToVduArtifact(HeatTemplate heatTemplate, ArtifactType artifactType) {
VduArtifact vduArtifact = new VduArtifact();
vduArtifact.setName(heatTemplate.getTemplateName());
vduArtifact.setContent(heatTemplate.getHeatTemplate().getBytes());
vduArtifact.setType(artifactType);
return vduArtifact;
}
private void mapCloudFiles(VfModuleCustomization vfModuleCustom, VduModelInfo vduModel) {
// TODO: These catalog objects will be refactored to be non-Heat-specific
List<VduArtifact> vduArtifacts = vduModel.getArtifacts();
// Attached Files
List<HeatFiles> heatFiles = vfModuleCustom.getVfModule().getHeatFiles();
if (heatFiles != null) {
for(HeatFiles file : heatFiles){
vduArtifacts.add(mapCloudFileToVduArtifact(file, ArtifactType.TEXT_FILE));
}
}
}
private VduArtifact mapCloudFileToVduArtifact(HeatFiles heatFile, ArtifactType artifactType) {
VduArtifact vduArtifact = new VduArtifact();
vduArtifact.setName(heatFile.getFileName());
vduArtifact.setContent(heatFile.getFileBody().getBytes());
vduArtifact.setType(artifactType);
return vduArtifact;
}
private void mapEnvironment(HeatEnvironment heatEnvironment, VduModelInfo vduModel) {
// TODO: These catalog objects will be refactored to be non-Heat-specific
if (heatEnvironment != null) {
List<VduArtifact> vduArtifacts = vduModel.getArtifacts();
vduArtifacts.add(mapEnvironmentFileToVduArtifact(heatEnvironment));
}
}
private VduArtifact mapEnvironmentFileToVduArtifact(HeatEnvironment heatEnv) {
VduArtifact vduArtifact = new VduArtifact();
vduArtifact.setName(heatEnv.getName());
vduArtifact.setContent(heatEnv.getEnvironment().getBytes());
vduArtifact.setType(ArtifactType.ENVIRONMENT);
return vduArtifact;
}
}
| [
"mb388a@us.att.com"
] | mb388a@us.att.com |
ea0e661bde5dc83d22c6e3307c37275d650f4b0c | 3b97ef184b00b9198e56a48f28c787b712859b5c | /app/src/main/java/com/gongyou/rongclouddemo/mvp/view/second/SelectFriendView.java | 7fbabfcc8cbd515ecfe04088169d0f141702833b | [] | no_license | hezijie1234/RongCloudDemo | 9cb0d2b0e0fafb7df5f604984da2cc42f6caf769 | 97f897514ff3c8f99c984502510ae86049cec0ec | refs/heads/master | 2020-03-10T12:33:36.529095 | 2018-04-20T06:31:12 | 2018-04-20T06:31:12 | 129,381,164 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 324 | java | package com.gongyou.rongclouddemo.mvp.view.second;
import com.gongyou.rongclouddemo.mvp.bean.second.AllFriendsInfo;
import com.gongyou.rongclouddemo.mvp.view.BaseView;
/**
* Created by hezijie on 2018/4/11.
*/
public interface SelectFriendView extends BaseView {
void getAllUserInfo(AllFriendsInfo friendsInfo);
}
| [
"1710276127@qq.com"
] | 1710276127@qq.com |
d58d3cfcbe9c6e2c9eb03ddf80c63ec84b09fe7c | acc53af38fb2e04089225c27cf9d0ded4bfff3dd | /app/src/main/java/com/nordusk/UI/GetDate.java | 312ca9a6a7be6e57ab328164aec945b011361326 | [] | no_license | amitkp/Android | 752cb7ccd6e2d707cce3c0f3e5dbe7f95eba895a | 5b4949c242b75d961e662dfdc0257a184b75b119 | refs/heads/master | 2020-07-21T15:50:18.373791 | 2017-02-28T06:29:16 | 2017-02-28T06:29:16 | 73,845,764 | 0 | 3 | null | 2017-01-09T05:27:44 | 2016-11-15T19:02:09 | Java | UTF-8 | Java | false | false | 1,044 | java | package com.nordusk.UI;
import android.os.AsyncTask;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by NeeloyG on 1/13/2017.
*/
public class GetDate extends AsyncTask<Void,Void,Void> {
private String date;
public GetDate(){}
@Override
protected Void doInBackground(Void... params) {
date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
onContentListParserListner.OnSuccess(date);
}
private OnContentListSchedules onContentListParserListner;
public OnContentListSchedules getOnContentListParserListner() {
return onContentListParserListner;
}
public void setOnContentListParserListner(OnContentListSchedules onContentListParserListner) {
this.onContentListParserListner = onContentListParserListner;
}
public interface OnContentListSchedules {
public void OnSuccess(String date);
}
}
| [
"neeloyg@rssoftware.co.in"
] | neeloyg@rssoftware.co.in |
33c386bd21b99bbea23fe45a077202d996aa86d1 | 3eeaecf97a5d66c3d8e74727ae5464a253df9c33 | /src/streams/streams2/SynhronizedTest/BlockedMethodCaller.java | 303749dfb8b52e10dd7d2172fff8e2b87035c2c5 | [] | no_license | YriyLoz/Golovath-Java | 8aae58f93237feb5820672cce7aeacc902b081f9 | d55eadddd5827fc771ca77ac904169e5b94a1a45 | refs/heads/master | 2020-04-09T17:37:39.790239 | 2019-03-17T08:27:58 | 2019-03-17T08:27:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 403 | java | package streams.streams2.SynhronizedTest;
public class BlockedMethodCaller implements Runnable {
private final BlockedExample ref;
private final int k;
BlockedMethodCaller(BlockedExample ref, int k) {
this.ref = ref;
this.k = k;
}
@Override
public void run() {
try {
ref.f(k);
} catch (InterruptedException e) {
}
}
}
| [
"36788651+YriyLoz@users.noreply.github.com"
] | 36788651+YriyLoz@users.noreply.github.com |
d62dd50e814af4b85e5ea1e29c3eb9d476898dc0 | 8a6453cd49949798c11f57462d3f64a1fa2fc441 | /aws-java-sdk-elasticloadbalancingv2/src/main/java/com/amazonaws/services/elasticloadbalancingv2/model/SetRulePrioritiesRequest.java | bbc7383ae63f119ab72ee7dfef01580b211627ee | [
"Apache-2.0"
] | permissive | tedyu/aws-sdk-java | 138837a2be45ecb73c14c0d1b5b021e7470520e1 | c97c472fd66d7fc8982cb4cf3c4ae78de590cfe8 | refs/heads/master | 2020-04-14T14:17:28.985045 | 2019-01-02T21:46:53 | 2019-01-02T21:46:53 | 163,892,339 | 0 | 0 | Apache-2.0 | 2019-01-02T21:38:39 | 2019-01-02T21:38:39 | null | UTF-8 | Java | false | false | 4,742 | java | /*
* Copyright 2013-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.elasticloadbalancingv2.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/elasticloadbalancingv2-2015-12-01/SetRulePriorities"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SetRulePrioritiesRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The rule priorities.
* </p>
*/
private java.util.List<RulePriorityPair> rulePriorities;
/**
* <p>
* The rule priorities.
* </p>
*
* @return The rule priorities.
*/
public java.util.List<RulePriorityPair> getRulePriorities() {
return rulePriorities;
}
/**
* <p>
* The rule priorities.
* </p>
*
* @param rulePriorities
* The rule priorities.
*/
public void setRulePriorities(java.util.Collection<RulePriorityPair> rulePriorities) {
if (rulePriorities == null) {
this.rulePriorities = null;
return;
}
this.rulePriorities = new java.util.ArrayList<RulePriorityPair>(rulePriorities);
}
/**
* <p>
* The rule priorities.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setRulePriorities(java.util.Collection)} or {@link #withRulePriorities(java.util.Collection)} if you want
* to override the existing values.
* </p>
*
* @param rulePriorities
* The rule priorities.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SetRulePrioritiesRequest withRulePriorities(RulePriorityPair... rulePriorities) {
if (this.rulePriorities == null) {
setRulePriorities(new java.util.ArrayList<RulePriorityPair>(rulePriorities.length));
}
for (RulePriorityPair ele : rulePriorities) {
this.rulePriorities.add(ele);
}
return this;
}
/**
* <p>
* The rule priorities.
* </p>
*
* @param rulePriorities
* The rule priorities.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SetRulePrioritiesRequest withRulePriorities(java.util.Collection<RulePriorityPair> rulePriorities) {
setRulePriorities(rulePriorities);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getRulePriorities() != null)
sb.append("RulePriorities: ").append(getRulePriorities());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof SetRulePrioritiesRequest == false)
return false;
SetRulePrioritiesRequest other = (SetRulePrioritiesRequest) obj;
if (other.getRulePriorities() == null ^ this.getRulePriorities() == null)
return false;
if (other.getRulePriorities() != null && other.getRulePriorities().equals(this.getRulePriorities()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getRulePriorities() == null) ? 0 : getRulePriorities().hashCode());
return hashCode;
}
@Override
public SetRulePrioritiesRequest clone() {
return (SetRulePrioritiesRequest) super.clone();
}
}
| [
""
] | |
3e1d460facd8f6af440d419abf1456056724e517 | 8249672c8e138b7fae4e538327d3b885c0a4cb59 | /src/main/java/com/ph/datastructure/BasicHashMap.java | 25aee5fd02a0090c8078627dd21ebedfcb05ab60 | [] | no_license | prabal999/Data-Structure | 2d8387b94105d5a197e36ce509bb8970b527aa08 | a1e22b336239b86d8abaa7837feed9c2b1e2fd98 | refs/heads/master | 2020-03-21T00:14:11.592178 | 2018-07-06T05:17:19 | 2018-07-06T05:17:19 | 137,884,062 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,667 | java | package com.ph.datastructure;
public class BasicHashMap<K, V> {
private Node<K, V>[] table;
private int capacity;
private int size;
@SuppressWarnings("unchecked")
public BasicHashMap(int capacity) {
table = new Node[capacity];
this.capacity = capacity;
this.size = 0;
}
public int hashCode(K key) {
return key.hashCode() % capacity;
}
public void put(K key, V value) {
boolean updated = false;
int hash = hashCode(key);
Node<K, V> node = new Node<K, V>(key, value, null);
if (null == table[hash]) {
table[hash] = node;
} else {
Node<K, V> current = table[hash];
while (current.getNext() != null) {
if (current.key.equals(node.getKey())) {
current.setValue(node.getValue());
updated = true;
break;
} else {
current = current.getNext();
}
}
if (!updated) {
current.setNext(node);
size++;
}
}
}
public V get(K key) {
V value = null;
int hash = hashCode(key);
if (null != table[hash]) {
Node<K, V> current = table[hash];
while (current != null) {
if (current.getKey().equals(key)) {
value = current.getValue();
break;
}
current = current.getNext();
}
}
return value;
}
public boolean remove(K key) {
boolean removed = false;
int hash = hashCode(key);
if (null != table[hash]) {
Node<K, V> previous = null;
Node<K, V> current = table[hash];
while (current != null) {
if (current.getKey().equals(key)) {
if (previous == null) {
table[hash] = current.getNext();
current = null;
} else {
previous.setNext(current.getNext());
}
size--;
removed = true;
break;
}
previous = current;
current = current.getNext();
}
}
return removed;
}
@Override
public String toString() {
String map = "";
for (int i = 0; i < table.length; i++) {
if (null != table[i]) {
map += "\n position = " + i + " = {";
Node<K, V> current = table[i];
while (current != null) {
map += " Key = " + current.getKey() + "; Value = " + current.getValue();
current = current.getNext();
}
}
}
return map;
}
private class Node<K, V> {
private K key;
private V value;
private Node<K, V> next;
public Node(K key, V value, Node<K, V> next) {
this.key = key;
this.value = value;
this.next = next;
}
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
public Node<K, V> getNext() {
return next;
}
public void setNext(Node<K, V> next) {
this.next = next;
}
}
}
| [
"prabal9@live.com"
] | prabal9@live.com |
867e10db5fb73633c85402ef3501e3d87e1cb40a | 56c4302297e59a8d1bd1587ed4501b6f669ef91a | /alpha-user/src/main/java/com/alpha/user/service/impl/MedicalRecordServiceImpl.java | 3b3659f90260aca96ba14fe0fa20cd2c5580d410 | [] | no_license | leohyluo/alpha | 2d00789eba563700e5ee07d08cbd5d52cb29418d | 9a049d078cc06bab203b5b53a95508babee0b2a7 | refs/heads/master | 2021-01-20T04:28:52.089370 | 2018-03-02T15:45:26 | 2018-03-02T15:45:26 | 101,387,864 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,510 | java | package com.alpha.user.service.impl;
import bsh.EvalError;
import bsh.Interpreter;
import com.alpha.server.rpc.diagnosis.pojo.DiagnosisMainSymptoms;
import com.alpha.server.rpc.user.pojo.UserBasicRecord;
import com.alpha.server.rpc.user.pojo.UserDiagnosisDetail;
import com.alpha.user.dao.DiagnosisMedicalTemplateDao;
import com.alpha.user.pojo.DiagnosisMedicalTemplate;
import com.alpha.user.service.MedicalRecordService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by xc.xiong on 2017/10/12.
*/
@Service
public class MedicalRecordServiceImpl implements MedicalRecordService {
private Logger LOGGER = LoggerFactory.getLogger(getClass());
@Autowired
private DiagnosisMedicalTemplateDao diagnosisMedicalTemplateDao;
/**
* 获取当前问诊过程内容
*
* @param
* @param templateCode
*/
public void getMedicalRecord(String templateCode, List<UserDiagnosisDetail> udds, DiagnosisMainSymptoms symptom, UserBasicRecord record) {
Map<String, String> question = new HashMap<>();
for (UserDiagnosisDetail udd : udds) {
question.put(udd.getQuestionCode(), udd.getAnswerContent());
}
System.out.println(runCode1(question, symptom));
System.out.println(runCode2(question, symptom));
System.out.println(runCode3(record));
}
public String getMaminSymptomName(DiagnosisMedicalTemplate diagnosisMedicalTemplate, Map<String, String> question, DiagnosisMainSymptoms symptom) {
// String result = runCode1(question, symptom);
// System.out.println(result);
Interpreter bsh = new Interpreter();
try {
bsh.set("question", question);
bsh.set("symptom", symptom);
bsh.eval(diagnosisMedicalTemplate.getSymptomName());
String result = (String) bsh.get("result");
return result;
} catch (EvalError evalError) {
evalError.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public String getPresentIllnessHistory(DiagnosisMedicalTemplate diagnosisMedicalTemplate, Map<String, String> question, DiagnosisMainSymptoms symptom) {
// String result = runCode2(question, symptom);
// System.out.println(result);
Interpreter bsh = new Interpreter();
try {
bsh.set("question", question);
bsh.set("symptom", symptom);
bsh.eval(diagnosisMedicalTemplate.getPresentIllnessHistory());
String result = (String) bsh.get("result");
return result;
} catch (EvalError evalError) {
evalError.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public String getPresentIllnessHistoryHospital(DiagnosisMedicalTemplate diagnosisMedicalTemplate, UserBasicRecord record) {
// String result = runCode3(record);
// System.out.println(result);
Interpreter bsh = new Interpreter();
try {
bsh.set("record", record);
bsh.eval(diagnosisMedicalTemplate.getPresentIllnessHistoryHospital());
String result = (String) bsh.get("result");
return result;
} catch (EvalError evalError) {
evalError.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public String runCode1(Map<String, String> question, DiagnosisMainSymptoms symptom) {
String result = symptom.getSympName() + question.get("3319")+"天";
return result;
}
public String runCode2(Map<String, String> question, DiagnosisMainSymptoms symptom) {
StringBuffer strBuff = new StringBuffer();
strBuff.append("患儿约");
strBuff.append(question.get("3319"));
strBuff.append("天前");
if (org.apache.commons.lang3.StringUtils.isEmpty(question.get("3325"))) {
strBuff.append("无明显诱因");
} else {
strBuff.append("因");
strBuff.append(question.get("3325"));
}
strBuff.append("出现");
strBuff.append(symptom.getSympName());
strBuff.append(",");
strBuff.append("起病");
strBuff.append(question.get("3321"));
strBuff.append(",");
strBuff.append("大便为");
strBuff.append(question.get("3316"));
strBuff.append("、");
strBuff.append(question.get("3324"));
strBuff.append("、");
strBuff.append(question.get("3323"));
strBuff.append("、");
strBuff.append(question.get("3320"));
strBuff.append("次/天,伴");
strBuff.append(question.get("3338"));
strBuff.append("。");
String result = strBuff.toString();
return result;
}
public String runCode3(UserBasicRecord record) {
StringBuffer strBuff = new StringBuffer();
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
if (record.getOtherHospital() != null && record.getOtherHospital() == 1) {
strBuff.append(sdf.format(record.getOtherHospitalCureTime()));
strBuff.append("前患儿到其它医院就诊,");
if(org.apache.commons.lang3.StringUtils.isEmpty(record.getOtherHospitalDiagnosis())){
strBuff.append("具体诊断不清楚");
}else{
strBuff.append("诊断为");
strBuff.append(record.getOtherHospitalDiagnosis());
}
strBuff.append(",");
if (record.getOtherHospitalUseDrug() == 1) {
strBuff.append("给予药物治疗,病情");
strBuff.append(record.getOtherHospitalEffect());
strBuff.append(",");
} else {
strBuff.append("未进行治疗,");
}
strBuff.append("为进一步诊治今天来就诊。");
}
String result = strBuff.toString();
return result;
}
// private static String classBody = "package com.alpha.user.service;" +
// " public class Test{" +
// " public String runCode(String str){ " +
// " System.out.println(\"-------------\"+str);" +
// " System.out.println(\"-------??? ------\");" +
// " String str1=\"覆盖》》\"+str ;"+
// " return str1;"+
// " } "+
// " }";
private static String classBody = "org.apache.commons.lang3.StringUtils.isEmpty(record.getMainSymptomName());" +
"record.setMainSymptomName(\"主症状\");" +
" return record;";
public static void main(String[] args) {
Interpreter bsh = new Interpreter();
try {
bsh.set("record", new UserBasicRecord());
bsh.eval(classBody);
UserBasicRecord str = (UserBasicRecord) bsh.get("record");
System.out.println("????????????" + str.getMainSymptomName());
} catch (EvalError evalError) {
evalError.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| [
"32305819@qq.com"
] | 32305819@qq.com |
490690fa4e73e72134323e75eea824480117ab05 | 16209560469fbcc378fe703c0ed3b32b56fa0433 | /src/main/java/com/qf/mapper/UserMapper.java | ccdb0957e7de22cb7aa325af6930a29edc3bdf81 | [] | no_license | KimanStone/blog | 4beabbe71d525b86d5b2b3e82f0b0633be0d8f3d | 9b096fa4e4541999a1d07976b65a8f0d87df3640 | refs/heads/master | 2022-12-24T00:03:04.281441 | 2019-07-13T03:57:06 | 2019-07-13T03:57:06 | 196,675,521 | 0 | 0 | null | 2022-12-16T08:58:14 | 2019-07-13T03:53:33 | Java | UTF-8 | Java | false | false | 139 | java | package com.qf.mapper;
import com.qf.pojo.User;
public interface UserMapper {
User getUser(User user);
int addUser(User user);
}
| [
"936340444@qq.com"
] | 936340444@qq.com |
b83c6ca8fddfa814c3b84b69523c4fd3014b8471 | 7ec0194c493e63b18ab17b33fe69a39ed6af6696 | /masterlock/app_decompiled/sources/p008io/fabric/sdk/android/services/settings/AppRequestData.java | 519d68e6b069ea800948c8949c8d2d1241a68517 | [] | no_license | rasaford/CS3235 | 5626a6e7e05a2a57e7641e525b576b0b492d9154 | 44d393fb3afb5d131ad9d6317458c5f8081b0c04 | refs/heads/master | 2020-07-24T16:00:57.203725 | 2019-11-05T13:00:09 | 2019-11-05T13:00:09 | 207,975,557 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,195 | java | package p008io.fabric.sdk.android.services.settings;
import java.util.Collection;
import p008io.fabric.sdk.android.KitInfo;
/* renamed from: io.fabric.sdk.android.services.settings.AppRequestData */
public class AppRequestData {
public final String apiKey;
public final String appId;
public final String buildVersion;
public final String builtSdkVersion;
public final String displayVersion;
public final IconRequest icon;
public final String instanceIdentifier;
public final String minSdkVersion;
public final String name;
public final Collection<KitInfo> sdkKits;
public final int source;
public AppRequestData(String str, String str2, String str3, String str4, String str5, String str6, int i, String str7, String str8, IconRequest iconRequest, Collection<KitInfo> collection) {
this.apiKey = str;
this.appId = str2;
this.displayVersion = str3;
this.buildVersion = str4;
this.instanceIdentifier = str5;
this.name = str6;
this.source = i;
this.minSdkVersion = str7;
this.builtSdkVersion = str8;
this.icon = iconRequest;
this.sdkKits = collection;
}
}
| [
"fruehaufmaximilian@gmail.com"
] | fruehaufmaximilian@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.