blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
132
| path
stringlengths 2
382
| src_encoding
stringclasses 34
values | length_bytes
int64 9
3.8M
| score
float64 1.5
4.94
| int_score
int64 2
5
| detected_licenses
listlengths 0
142
| license_type
stringclasses 2
values | text
stringlengths 9
3.8M
| download_success
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|
11b1f974fdb04ca99cff6fa7b88e6bd51f65f653
|
Java
|
apycazo/jander-ms
|
/ms-redis/src/main/java/es/jander/ms/redis/RedisApp.java
|
UTF-8
| 424 | 1.515625 | 2 |
[
"Apache-2.0"
] |
permissive
|
package es.jander.ms.redis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
@SpringBootApplication
@EnableRedisRepositories
public class RedisApp
{
public static void main (String [] args)
{
new SpringApplication(RedisApp.class).run();
}
}
| true |
b92d058d4f7ac20c8bb125bff659cef44bbfa595
|
Java
|
debugroom/wedding
|
/wedding-microservice/wedding-frontend/wedding-web-frontend/src/main/java/org/debugroom/wedding/app/model/management/PageParam.java
|
UTF-8
| 508 | 2.03125 | 2 |
[] |
no_license
|
package org.debugroom.wedding.app.model.management;
import java.io.Serializable;
import javax.validation.constraints.Min;
import lombok.Data;
import lombok.AllArgsConstructor;
import lombok.Builder;
@AllArgsConstructor
@Builder
@Data
public class PageParam implements Serializable{
private static final long serialVersionUID = 154651265564181379L;
public PageParam(){
this.page = new Integer(0);
this.size = new Integer(10);
}
@Min(0)
private Integer size;
@Min(0)
private Integer page;
}
| true |
e8d799045fcb09fdc9e43cc55bbe03990afd005a
|
Java
|
vscom/Transmit
|
/src/com/bvcom/transmit/handle/smginfo/NvrStatusSet.java
|
UTF-8
| 13,889 | 2.171875 | 2 |
[] |
no_license
|
package com.bvcom.transmit.handle.smginfo;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import com.bvcom.transmit.core.MemCoreData;
import com.bvcom.transmit.db.DaoSupport;
import com.bvcom.transmit.util.CommonException;
import com.bvcom.transmit.util.CommonUtility;
import com.bvcom.transmit.util.DaoException;
import com.bvcom.transmit.util.UtilXML;
import com.bvcom.transmit.vo.MSGHeadVO;
import com.bvcom.transmit.vo.SMGCardInfoVO;
import com.bvcom.transmit.vo.video.ChangeProgramQueryVO;
public class NvrStatusSet {
private static Logger log = Logger.getLogger(NvrStatusSet.class.getSimpleName());
private MSGHeadVO bsData = new MSGHeadVO();
private String downString = new String();
private UtilXML utilXML = new UtilXML();
MemCoreData coreData = MemCoreData.getInstance();
public NvrStatusSet(String centerDownStr, MSGHeadVO bsData) {
this.downString = centerDownStr;
this.bsData = bsData;
}
/**
* 1. 解析通道设置协议
* 2. 修改配置文件与数据库
* @throws DaoException
*/
@SuppressWarnings("unchecked")
public void downXML() throws DaoException {
Document document=null;
try {
document = utilXML.StringToXML(downString);
} catch (CommonException e) {
log.info("字符串转换xml错误:"+e.getMessage());
}
//解析协议内容并保存
List<String> strList=parse(document);
for(int i=0;i<strList.size();i++){
String[] arrStr=strList.get(i).split(",");
int Index=Integer.parseInt(arrStr[0].trim());
int IndexType=Integer.parseInt(arrStr[1].trim());
//0 代表 停用,1 代表实时视频,2 轮播辅助,3 轮循测量,4 录像,5空闲
//1:初始的通道状态为配置文件中的状态信息
//2:通过平台修改此配置
//3:平台设置通道状态
//4:读取状态信息
//更新数据库业务类型
updateSmgCardInfo(Index,IndexType);
}
//上报给平台设置成功信息
String returnstr="";
//封装MemCoreData对象的内容 保存TransmitConfig.xml
//isErr=saveMemCoreDataToTransmitConfig(coreData);
returnstr = getReturnXML(this.bsData, 0);
try {
utilXML.SendUpXML(returnstr, bsData);
} catch (CommonException e) {
log.error("上发 "+ bsData.getStatusQueryType() +" 信息失败: " + e.getMessage());
}
//更新SMG的配置文件信息
MemCoreData coreDate = MemCoreData.getInstance();
List SMGCardList = coreDate.getSMGCardList();
SMGCardList.clear();
List<SMGCardInfoVO> NvrStatusList = new ArrayList();
@SuppressWarnings("unused")
Statement statement = null;
@SuppressWarnings("unused")
ResultSet rs = null;
try
{
@SuppressWarnings("unused")
Connection conn = DaoSupport.getJDBCConnection();
StringBuffer strBuff1 = new StringBuffer();
strBuff1.append("select * from smg_card_info order by smgIndex");
try {
statement = conn.createStatement();
rs = statement.executeQuery(strBuff1.toString());
while(rs.next()){
SMGCardInfoVO smginfo = new SMGCardInfoVO();
int index = rs.getInt("smgIndex");
smginfo.setIndex(index);
String ip = rs.getString("smgIp");
smginfo.setIP(ip);
int inputtype = rs.getInt("smgInputtype");
smginfo.setIndexType(String.valueOf(inputtype));
String url = rs.getString("smgURL");
smginfo.setURL(url);
int status = rs.getInt("smgStatus");
smginfo.setStatus(status);
NvrStatusList.add(smginfo);
}
} catch (Exception e) {
} finally {
DaoSupport.close(rs);
DaoSupport.close(statement);
}
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
for(int i =0;i <NvrStatusList.size();i++){
SMGCardInfoVO smgCardInfo = new SMGCardInfoVO();
SMGCardInfoVO smginfo = (SMGCardInfoVO)NvrStatusList.get(i);
@SuppressWarnings("unused")
SMGCardInfoVO smginfo_scan = (SMGCardInfoVO)NvrStatusList.get(i);
// 取得通道信息
smgCardInfo.setIndex(smginfo.getIndex());
smgCardInfo.setURL(smginfo.getURL());
smgCardInfo.setIP(smginfo.getIP());
smgCardInfo.setHDFlag(0);
smgCardInfo.setHDURL("http://192.168.100.101:8080/Setup/");
//通道查询的业务类型:IndexType(0 代表 停用,1 代表实时视频,2 轮播辅助,3 轮循测量,4 自动录像 ,5任务录像 ,6数据采集,7空闲)
//通道设置业务类型:0 代表 停用,1 代表实时视频,2 轮播辅助,3 轮循测量,4录像 、5空闲
// 通道类型(1:ChangeProgramQuery(手动选台, 频道扫描 和指标) 2:GetIndexSet(指标查询) AutoRecord
int inputtype = Integer.valueOf(smginfo.getIndexType());
switch(inputtype)
{
case 0:
smginfo.setIndexType("Stop");
break;
case 1:
smginfo.setIndexType("ChangeProgramQuery");
break;
case 2:
smginfo.setIndexType("StreamRoundInfoQuery");
break;
case 3:
smginfo.setIndexType("AutoAnalysisTimeQuery");
break;
case 4:
smginfo.setIndexType("AutoRecord");
break;
case 5:
smginfo.setIndexType("Free");
break;
case 6:
smginfo.setIndexType("ChannelScanQuery");//GetIndexSet
break;
case 7:
smginfo.setIndexType("Free");
break;
}
smgCardInfo.setIndexType(smginfo.getIndexType());
SMGCardList.add(smgCardInfo);
if(inputtype==6){
smgCardInfo = new SMGCardInfoVO();
smginfo = (SMGCardInfoVO)NvrStatusList.get(i);
// 取得通道信息
smgCardInfo.setIndex(smginfo.getIndex());
smgCardInfo.setURL(smginfo.getURL());
smgCardInfo.setIP(smginfo.getIP());
smgCardInfo.setIndexType("GetIndexSet");
SMGCardList.add(smgCardInfo);
}
//手动选台:实时视频
if(inputtype==1){
//更改一对一实时视频表:StatusFlag=3的SMGURL
try {
upChangeProgramTable(smgCardInfo);
} catch (DaoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//停用一对一表中的通道
if(inputtype==0){
delChannelFromChannelMapping(smginfo.getIndex());
}
else{
recoverChannelFromChannelMapping(smginfo.getIndex());
}
// 高清转码标记
//smgCardInfo.setHDFlag(Integer.valueOf(SMGCardInfo.attribute("HDFlag").getValue()));
// 高清转码URL
//smgCardInfo.setHDURL(SMGCardInfo.attribute("HDURL").getValue());
}
coreDate.setSMGCardList(SMGCardList);
}
@SuppressWarnings("unused")
private static void recoverChannelFromChannelMapping(int index) throws DaoException{
StringBuffer strBuff = new StringBuffer();
Statement statement = null;
ResultSet rs = null;
Connection conn = DaoSupport.getJDBCConnection();
strBuff.append("update channelremapping c set ");
strBuff.append("DelFlag = 0");
strBuff.append(" where DevIndex = "+index);
try {
statement = conn.createStatement();
statement.executeUpdate(strBuff.toString());
} catch (Exception e) {
log.error("一对一节目表更新数据库错误: " + e.getMessage());
} finally {
DaoSupport.close(rs);
DaoSupport.close(statement);
DaoSupport.close(conn);
}
}
@SuppressWarnings("unused")
private static void delChannelFromChannelMapping(int index) throws DaoException{
StringBuffer strBuff = new StringBuffer();
Statement statement = null;
ResultSet rs = null;
Connection conn = DaoSupport.getJDBCConnection();
strBuff.append("update channelremapping c set ");
strBuff.append("DelFlag = 1");
strBuff.append(" where DevIndex = "+index);
try {
statement = conn.createStatement();
statement.executeUpdate(strBuff.toString());
} catch (Exception e) {
log.error("一对一节目表更新数据库错误: " + e.getMessage());
} finally {
DaoSupport.close(rs);
DaoSupport.close(statement);
DaoSupport.close(conn);
}
}
/**
* 更新入库一对一表
* @throws DaoException
*/
private static void upChangeProgramTable(SMGCardInfoVO vo) throws DaoException {
StringBuffer strBuff = new StringBuffer();
Statement statement = null;
ResultSet rs = null;
Connection conn = DaoSupport.getJDBCConnection();
strBuff.append("update monitorprogramquery c set ");
// statusFlag: 0:空闲 1:一对一监视 2:轮播监测使用 3:手动选台 4:自动轮播
strBuff.append("statusFlag = 3, ");
// RunType 1:手动选台 2:一对一监测 3:轮询监测 4:轮播
strBuff.append(" RunType = 1, ");
strBuff.append(" smgURL = '"+vo.getURL()+"'");
strBuff.append(" ,lastDatatime = '" + CommonUtility.getDateTime() + "' ");
strBuff.append(" where statusFlag = 3 ");
try {
statement = conn.createStatement();
statement.executeUpdate(strBuff.toString());
} catch (Exception e) {
log.error("手动选台更新数据库错误: " + e.getMessage());
} finally {
DaoSupport.close(rs);
DaoSupport.close(statement);
DaoSupport.close(conn);
}
//log.info("手动选台更新数据库成功!");
}
//根据通道号更新业务类型信息,增加判断机制,如果有多个实时视频,报错,有多个轮询测量,报错??--平台应该做限制,前端只负责处理状态更新
private boolean updateSmgCardInfo(int index,int inputtype)
{
boolean ret = false;
Statement statement = null;
ResultSet rs = null;
StringBuffer strBuff2 = new StringBuffer();
try {
Connection conn = DaoSupport.getJDBCConnection();
strBuff2.append("update smg_card_info set smgInputtype=");
strBuff2.append(inputtype+",updateTime='");
strBuff2.append(CommonUtility.getDateTime() + "',smgRemark='");
strBuff2.append("业务类型变更' where smgIndex=");
strBuff2.append(index);
System.out.println(strBuff2.toString());
conn.setAutoCommit(false);
try {
statement=conn.createStatement();
statement.executeUpdate(strBuff2.toString());
} catch (Exception e) {
//log.info("更新通道状态表失败:"+e.getMessage());
ret = false;
}finally{
DaoSupport.close(statement);
}
ret = true;
conn.commit();
DaoSupport.close(conn);
}
catch(Exception ex){
System.out.println(ex.getMessage());
ret = false;
}
return ret;
}
private String getReturnXML(MSGHeadVO head, int value) {
StringBuffer strBuf = new StringBuffer();
strBuf.append("<?xml version=\"1.0\" encoding=\"GB2312\" standalone=\"yes\"?>");
strBuf.append("<Msg Version=\"" + head.getVersion() + "\" MsgID=\"");
strBuf.append(head.getCenterMsgID() + "\" Type=\"MonUp\" DateTime=\"");
strBuf.append(CommonUtility.getDateTime() + "\" SrcCode=\"" + head.getDstCode());
strBuf.append("\" DstCode=\"" + head.getSrcCode() + "\" ReplyID=\""+head.getCenterMsgID()+"\"> \r\n");
if(0==value){
strBuf.append("<Return Type=\""+ head.getStatusQueryType() + "\" Value=\"0\" Desc=\"成功\"/>\r\n");
}else if(1==value){
strBuf.append("<Return Type=\"" + head.getStatusQueryType() + "\" Value=\"1\" Desc=\"失败\"/>\r\n");
strBuf.append("<ErrReport>\r\n");
//<NvrStatusSetRecord Index="0" IndexType = “0” Comment="内部错误"/>
strBuf.append("<RebootSetRecord Comment=\"内部错误\"/>\r\n");
strBuf.append("</ErrReport>\r\n");
}
strBuf.append("</Msg>");
return strBuf.toString();
}
private List<String> parse(Document document){
List<String> list=new ArrayList<String>();
Element root=document.getRootElement();
for (Iterator<Element> iter=root.elementIterator(); iter.hasNext(); ) {
Element NvrStatusSet =iter.next();
for(Iterator<Element> ite=NvrStatusSet.elementIterator();ite.hasNext();){
Element NvrStatusSetRecord=ite.next();
String Index=NvrStatusSetRecord.attributeValue("Index");
String IndexType=NvrStatusSetRecord.attributeValue("IndexType");
list.add(Index+","+IndexType);
}
}
return list;
}
}
| true |
c3f1cf7f73315e917e9a5cbae0e60a3d2c63a1fc
|
Java
|
julbob/Vivarium-Pokemon-Java
|
/src/model/attacks/Coupe.java
|
UTF-8
| 184 | 2.140625 | 2 |
[] |
no_license
|
package model.attacks;
import model.Attack;
import model.Type;
public class Coupe extends Attack {
public Coupe() {
super((short) 50, (float) 0.95, (short) 30, Type.Normal);
}
}
| true |
5d93555d4b7ca9d0ca2ff2ac0d26c651afce5500
|
Java
|
Camelcade/Perl5-IDEA
|
/plugin/core/src/main/java/com/perl5/lang/perl/idea/refactoring/introduce/occurrence/PerlSequentialOccurrencesCollector.java
|
UTF-8
| 2,667 | 2.015625 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2015-2018 Alexandr Evstigneev
*
* 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.perl5.lang.perl.idea.refactoring.introduce.occurrence;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiUtilCore;
import com.perl5.lang.perl.idea.refactoring.introduce.PerlIntroduceTarget;
import com.perl5.lang.perl.psi.utils.PerlPsiUtil;
import org.jetbrains.annotations.NotNull;
import java.util.List;
class PerlSequentialOccurrencesCollector extends PerlIntroduceTargetOccurrencesCollector {
PerlSequentialOccurrencesCollector(@NotNull PerlIntroduceTarget target) {
super(target);
}
@Override
protected boolean collectOccurrences(@NotNull PsiElement element) {
PerlIntroduceTarget target = getTarget();
PsiElement targetElement = target.getPlace();
if (target.isFullRange() && PerlPsiUtil.areElementsSame(targetElement, element)) {
addOccurrence(PerlIntroduceTarget.create(element));
return true;
}
if (PsiUtilCore.getElementType(targetElement) != PsiUtilCore.getElementType(element)) {
return false;
}
List<PsiElement> targetChildren = target.getMeaningfulChildrenWithLeafs();
if (targetChildren.isEmpty()) {
return false;
}
List<PsiElement> elementChildren = PerlPsiUtil.getMeaningfulChildrenWithLeafs(element);
if (elementChildren.size() < targetChildren.size()) {
return false;
}
PsiElement firstTargetChild = targetChildren.get(0);
for (int headIndex = 0; headIndex <= elementChildren.size() - targetChildren.size(); headIndex++) {
if (!PerlPsiUtil.areElementsSame(firstTargetChild, elementChildren.get(headIndex))) {
continue;
}
int offset = 1;
for (; offset < targetChildren.size(); offset++) {
if (!PerlPsiUtil.areElementsSame(targetChildren.get(offset), elementChildren.get(headIndex + offset))) {
offset = -1;
break;
}
}
if (offset > 0) {
addOccurrence(PerlIntroduceTarget.create(element, elementChildren.get(headIndex), elementChildren.get(headIndex + offset - 1)));
headIndex += offset;
}
}
return false;
}
}
| true |
c2ea978ee68e5a8d16be57fbeb5b7fcd4a00c3b1
|
Java
|
Giri1013/todo
|
/src/main/java/Helpers/Report.java
|
UTF-8
| 1,380 | 2.296875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package Helpers;
import net.masterthought.cucumber.Configuration;
import net.masterthought.cucumber.ReportBuilder;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
public class Report {
public static void main(String args[]){
GenerateMasterthoughtReport();
}
public static void GenerateMasterthoughtReport( )
{
try
{
File reportOutputDirectory = new File("target/Report");
File dir = new File("target/cucumber-parallel");
File[] txts = dir.listFiles(new FilenameFilter()
{
public boolean accept(File dir, String name)
{
if(name.endsWith(".json"))
return true;
return false;
}
});
List< String > list = new ArrayList<String>();
for(File path:txts)
{
list.add(path.toString());
}
String buildProject = "TodoMVC";
Configuration configuration = new Configuration(reportOutputDirectory, buildProject);
ReportBuilder reportBuilder = new ReportBuilder(list, configuration);
reportBuilder.generateReports();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
| true |
47f36a5eddfe7b9d0f1aa2f21e87c7a5eb56ab37
|
Java
|
guozhongdong/bookmanage
|
/src/test/java/com/ngp/book/web/bookmanage/BookmanageApplicationTests.java
|
UTF-8
| 2,643 | 2.03125 | 2 |
[] |
no_license
|
package com.ngp.book.web.bookmanage;
import com.alibaba.fastjson.JSONObject;
import com.ngp.book.web.bookmanage.config.PageInfo;
import com.ngp.book.web.bookmanage.config.PageRequest;
import com.ngp.book.web.bookmanage.result.Result;
import com.ngp.book.web.bookmanage.result.ResultVO;
import com.ngp.book.web.bookmanage.service.BookService;
import com.ngp.book.web.bookmanage.entity.Book;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
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;
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class BookmanageApplicationTests {
@Autowired
private BookService bookService;
@Test
public void add() {
Book book = new Book();
book.setAuthor("金庸");
book.setName("倚天屠龙记");
book.setBookType("小说");
}
@Test
public void edit() {
Book book = new Book();
book.setId(1);
book.setAuthor("金庸");
book.setName("倚天屠龙记2");
book.setBookType("小说");
}
@Test
public void queryAll() {
PageRequest pageRequest = new PageRequest();
ResultVO result = bookService.queryAllBook(pageRequest);
log.info("分页查询结果为:"+ JSONObject.toJSON(result));
}
@Test
public void query2All() {
PageRequest pageRequest = new PageRequest();
pageRequest.setPage(0);
pageRequest.setSize(3);
ResultVO result = bookService.queryAllBook(pageRequest);
log.info("分页查询结果为:"+ JSONObject.toJSON(result));
}
@Test
public void insertBook() {
Book book = new Book();
book.setAuthor("金庸");
book.setName("鹿鼎记");
book.setBookType("小说");
Result result = bookService.insertBook(book);
log.info("新增结果为:"+ JSONObject.toJSON(result));
}
@Test
public void updateBook() {
Book book = new Book();
book.setId(1);
book.setAuthor("金庸");
book.setName("倚天屠龙记222");
book.setPublish("机械工业出版社");
book.setBookType("小说2");
book.setPages(900);
Result result = bookService.updateBook(book);
log.info("修改结果为:"+ JSONObject.toJSON(result));
}
@Test
public void deleteBook() {
Result result = bookService.deleteOne(1);
log.info("删除结果为:"+ JSONObject.toJSON(result));
}
}
| true |
cfd9b349f0c5bb2c631f43e373dce1811f355ce3
|
Java
|
nakpilse/care
|
/src/controllers/NewItemFormController.java
|
UTF-8
| 11,645 | 2.015625 | 2 |
[] |
no_license
|
package controllers;
import alpha.Care;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXCheckBox;
import com.jfoenix.controls.JFXDialog;
import com.jfoenix.controls.JFXTextField;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import models.ContactPerson;
import models.Item;
import nse.dcfx.controls.FXDialog;
import nse.dcfx.controls.FXDialogTask;
import nse.dcfx.controls.FXField;
import nse.dcfx.controls.FXTask;
import nse.dcfx.controls.FormController;
import nse.dcfx.controls.UIController;
import nse.dcfx.converters.NumberConverter;
import nse.dcfx.models.GlobalOption;
import nse.dcfx.mysql.SQLTable;
import org.controlsfx.control.MaskerPane;
import org.controlsfx.control.textfield.TextFields;
/**
* FXML Controller class
*
* @author Duskmourne
*/
public class NewItemFormController implements Initializable,FormController<Item> {
private static UIController UI_CONTROLLER = null;
private static JFXDialog dialog = null;
private static StackPane stackPane = null;
private Item record = null;
@FXML
private Label titleLbl;
@FXML
private JFXButton closeBtn;
@FXML
private JFXTextField codeF;
@FXML
private JFXCheckBox pnfC;
@FXML
private JFXTextField descriptionF;
@FXML
private JFXTextField genericF;
@FXML
private JFXTextField typeF;
@FXML
private JFXTextField measureF;
@FXML
private JFXTextField formF;
@FXML
private JFXTextField categoryF;
@FXML
private JFXTextField strengthF;
@FXML
private JFXTextField opt1F;
@FXML
private JFXTextField opt2F;
@FXML
private JFXTextField qtyF;
@FXML
private JFXTextField reorderF;
@FXML
private JFXCheckBox stockedC;
@FXML
private JFXTextField costF;
@FXML
private JFXTextField sellingF;
@FXML
private JFXCheckBox vatableF;
@FXML
private JFXButton saveBtn;
@FXML
void formClose(ActionEvent event) {
dialog.close();
}
@FXML
void formSave(ActionEvent event) {
try{
if(isFieldInputsValid()){
if(record.getCost() <= 0 || record.getPrice() <= 0 || record.getCost() >= record.getPrice()){
JFXButton btn = new JFXButton("Yes, I am certain!");
JFXDialog dl = FXDialog.showConfirmDialog(stackPane, "Warning", new Label("Saving item with cost="+record.getCost()+" & selling="+record.getPrice()+" ?"), FXDialog.WARNING,btn);
btn.setOnAction(evt->{
dl.close();
Care.process(saveTask);
});
}else{
Care.process(saveTask);
}
}
}catch(Exception er){
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, er);
}
}
private final FXTask saveTask = new FXTask() {
@Override
protected void load() {
try{
Platform.runLater(()->{
closeBtn.setDisable(true);
saveBtn.setDisable(true);
});
if(record.save(true) > 0){
Platform.runLater(()->{
dialog.close();
FXDialog.showMessageDialog(stackPane, "Successfull", record.getDescription()+" has been registered!", FXDialog.SUCCESS);
postAction();
});
}else{
Platform.runLater(()->{
FXDialog.showMessageDialog(stackPane, "Failure", "There has been a problem on server communication!", FXDialog.DANGER);
});
}
}catch(Exception er){
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, er);
}finally{
Platform.runLater(()->{
saveBtn.setDisable(false);
closeBtn.setDisable(false);
});
}
}
};
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
@Override
public void postAction() {
try{
if(UI_CONTROLLER instanceof InventoryUIController){
if(record.isSupply()){
UI_CONTROLLER.reloadReferences(1);
}else{
UI_CONTROLLER.reloadReferences(0);
}
}
}catch(Exception er){
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, er);
}
}
@Override
public void setUIController(UIController controller) {
UI_CONTROLLER = controller;
}
@Override
public void setFormObject(Item obj) {
this.record = obj;
}
@Override
public Item getFormObject() {
return record;
}
@Override
public boolean isFieldInputsValid() {
return codeF.validate() && descriptionF.validate() && qtyF.validate() && reorderF.validate() && costF.validate() && sellingF.validate();
}
@Override
public void loadBindings() {
try{
codeF.textProperty().bindBidirectional(record.codeProperty());
pnfC.selectedProperty().bindBidirectional(record.pnfProperty());
descriptionF.textProperty().bindBidirectional(record.descriptionProperty());
genericF.textProperty().bindBidirectional(record.genericnameProperty());
typeF.textProperty().bindBidirectional(record.typeProperty());
measureF.textProperty().bindBidirectional(record.unitmeasureProperty());
formF.textProperty().bindBidirectional(record.formProperty());
categoryF.textProperty().bindBidirectional(record.categoryProperty());
strengthF.textProperty().bindBidirectional(record.strengthProperty());
opt1F.textProperty().bindBidirectional(record.opt1Property());
opt2F.textProperty().bindBidirectional(record.opt2Property());
qtyF.textProperty().bindBidirectional(record.quantityProperty(), new NumberConverter());
reorderF.textProperty().bindBidirectional(record.reorderquantityProperty(), new NumberConverter());
stockedC.selectedProperty().bindBidirectional(record.stockedProperty());
costF.textProperty().bindBidirectional(record.costProperty(), new NumberConverter());
sellingF.textProperty().bindBidirectional(record.priceProperty(), new NumberConverter());
vatableF.selectedProperty().bindBidirectional(record.vatableProperty());
}catch(Exception er){
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, er);
}
}
@Override
public void loadCustomizations() {
try{
FXField.setCommonCharactersOnly(typeF);
FXField.setCommonCharactersOnly(categoryF);
FXField.addTrimOnFocusLost(codeF,descriptionF,genericF,typeF,categoryF,measureF,formF,strengthF,opt1F,opt2F);
}catch(Exception er){
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, er);
}
}
@Override
public void loadValidators() {
try{
FXField.addRequiredValidator(codeF);
FXField.addRequiredValidator(descriptionF);
FXField.addRequiredValidator(qtyF);
FXField.addRequiredValidator(reorderF);
FXField.addRequiredValidator(costF);
FXField.addRequiredValidator(sellingF);
FXField.addIntegerValidator(qtyF, -999999999, 999999999, 1);
FXField.addIntegerValidator(reorderF, 0, 999999999, 0);
FXField.addDoubleValidator(costF, 0.0, 999999999.99, 0.0);
FXField.addDoubleValidator(sellingF, 0.0, 999999999.99, 0.0);
FXField.addDuplicateValidator(codeF, record, Item.CODE);
FXField.addDuplicateValidator(descriptionF, record, Item.DESCRIPTION);
FXField.addFocusValidationListener(codeF,descriptionF,qtyF,reorderF,costF,sellingF);
}catch(Exception er){
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, er);
}
}
@Override
public void loadResources() {
try{
Map<String,String> opts = GlobalOption.getMap(GlobalOption.ITEM_CATEGORY);
opt1F.setPromptText(opts.get("ITEM_OPT1"));
opt2F.setPromptText(opts.get("ITEM_OPT2"));
List<String> types = SQLTable.distinct(Item.class, Item.TYPE);
List<String> categories = SQLTable.distinct(Item.class, Item.CATEGORY);
List<String> forms = SQLTable.distinct(Item.class, Item.FORM);
List<String> measures = SQLTable.distinct(Item.class, Item.UNITMEASURE);
List<String> strs = SQLTable.distinct(Item.class, Item.STRENGTH);
List<String> opt1s = SQLTable.distinct(Item.class, Item.OPT1);
List<String> opt2s = SQLTable.distinct(Item.class, Item.OPT2);
TextFields.bindAutoCompletion(typeF, types);
TextFields.bindAutoCompletion(categoryF, categories);
TextFields.bindAutoCompletion(measureF, measures);
TextFields.bindAutoCompletion(formF, forms);
TextFields.bindAutoCompletion(strengthF, strs);
TextFields.bindAutoCompletion(opt1F, opt1s);
TextFields.bindAutoCompletion(opt2F, opt2s);
}catch(Exception er){
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, er);
}
}
@Override
public void loadUIFixes() {
try{
Platform.runLater(()->{
if(record.isSupply()){
titleLbl.setText("New Hospital Supply Registration");
}else{
titleLbl.setText("New Pharmacy Item Registration");
}
});
}catch(Exception er){
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, er);
}
}
public static FXDialogTask showDialog(Item item,StackPane stackpane,MaskerPane masker, UIController ui_controller, Node... nodes) {
if (dialog == null || !dialog.isVisible()) {
try {
dialog = new JFXDialog();
FXMLLoader LOADER = new FXMLLoader(FormController.class.getResource("/views/NewItemForm.fxml"));
FXDialogTask task = new FXDialogTask(dialog, item, ui_controller, 800, 620);
task.setLOADER(LOADER);
task.setDISABLED_NODES(nodes);
task.setOnSucceeded(evt -> {
stackPane = stackpane;
dialog.show(stackpane);
});
task.show(masker);
} catch (Exception er) {
Logger.getLogger(NewItemFormController.class.getName()).log(Level.SEVERE, null, er);
return null;
}
}
return null;
}
}
| true |
185fd17f0cd0b520f20ca1f6646dc8abbdc8a14a
|
Java
|
LiZachary/zachary_Util
|
/app/src/main/java/com/zachary/util/Net/progress/ProgressCancelListener.java
|
UTF-8
| 194 | 1.796875 | 2 |
[] |
no_license
|
package com.zachary.util.Net.progress;
/**
* Created on 2016/9/8 14:08
*
* @desc 取消监听
* @auther Zachary
*/
public interface ProgressCancelListener {
void onCancelProgress();
}
| true |
e1e60e0ff48f72494cf597698d08cf5b7e557086
|
Java
|
lisax302j/109_2_Android
|
/106332013_HW10/106332013_HW10a/app/src/main/java/com/example/android/simpleasynctask/SimpleAsyncTask.java
|
UTF-8
| 8,598 | 2.890625 | 3 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (C) 2018 Google Inc.
*
* 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.example.android.simpleasynctask;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.lang.ref.WeakReference;
import java.util.Random;
/**
* The SimpleAsyncTask class extends AsyncTask to perform a very simple
* background task -- in this case, it just sleeps for a random amount of time.
*/
public class SimpleAsyncTask extends AsyncTask<Void, Integer, String> {
// The TextView where we will show results
private WeakReference<TextView> mTextView;
private ProgressBar mProgressBar;
private ProgressDialog mProgressDialog;
private Context mContext;
private boolean isProgressBar=true;
// Constructor that provides a reference to the TextView from the MainActivity
SimpleAsyncTask(Context context,TextView tv) {
mContext=context;
mTextView = new WeakReference<>(tv);
}
public void setProgressBar(ProgressBar proBar){mProgressBar=proBar;}
@Override
protected void onPreExecute(){
super.onPreExecute ();
mProgressDialog=new ProgressDialog ( mContext );
mProgressDialog.setTitle ( "Downloading" );
mProgressDialog.setMessage ( "Please wait..." );
mProgressDialog.setMax(10);
// mProgressDialog.setButton( ProgressDialog.BUTTON_NEGATIVE,"Cancel",(View.OnClickListener)(dialog, which));
// {
// dialog.cancel ( );
// cancel ( true );
// };
// if (!isProgressBar)
// mProgressDialog.show();
}
@Override
protected String doInBackground(Void... voids) {
try {
for (int i = 1; i<=10;i++){
Thread.sleep ( 1000 );
Log.i ( "Thread" , "Execute" + i );
publishProgress ( i, i*10);
}
return "Successful";
} catch (InterruptedException e) {
Log.i ( "Exception" , e.getMessage ( ) );
return "Failure!";
}
}
/**
* Runs on the background thread.
*
* @param voids No parameters in this use case.
* @return Returns the string including the amount of time that
* the background thread slept.
*/
@Override
protected void onProgressUpdate (Integer...values){
// super.onProgressUpdate(values);
int myValue1 =values[0];
int myValue2 =values[1];
if (!isProgressBar)
mProgressDialog.setProgress ( myValue1 );
else {
mProgressBar.setProgress ( myValue2 );
mProgressBar.setProgress ( myValue2+10 );
}
}
// // Generate a random number between 0 and 10.
// Random r = new Random();
// int n = r.nextInt(11);
//
// // Make the task take long enough that we have
// // time to rotate the phone while it is running.
// int s = n * 200;
//
// // Sleep for the random amount of time.
// try {
// Thread.sleep(s);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// // Return a String result.
// return "Awake at last after sleeping for " + s + " milliseconds!";
// }
/**
* Does something with the result on the UI thread; in this case
* updates the TextView.
*/
// protected void onPostExecute(String result) {
// mTextView.get().setText(result);
}
///*
// * Copyright (C) 2018 Google Inc.
// *
// * 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.example.android.simpleasynctask;
//
//import android.app.ProgressDialog;
//import android.content.Context;
//import android.content.DialogInterface;
//import android.os.AsyncTask;
//import android.util.Log;
//import android.view.View;
//import android.widget.ProgressBar;
//import android.widget.TextView;
//
//import java.lang.ref.WeakReference;
//import java.util.Random;
//
///**
// * The SimpleAsyncTask class extends AsyncTask to perform a very simple
// * background task -- in this case, it just sleeps for a random amount of time.
// */
//
//public class SimpleAsyncTask extends AsyncTask<Void,Void, String> {
//
// // The TextView where we will show results
// private WeakReference<TextView> mTextView;
// private ProgressBar mProgressBar;
// private ProgressDialog mProgressDialog;
// private Context mContext;
// private boolean isProgressBar=true;
//
// // Constructor that provides a reference to the TextView from the MainActivity
// SimpleAsyncTask(Context context,TextView tv) {
// mContext=context;
// mTextView = new WeakReference<>(tv);
// }
//
// public void setProgressBar(ProgressBar proBar){mProgressBar=proBar;}
//
// @Override
// protected void onPreExecute(){
// super.onPreExecute ();
// mProgressDialog=new ProgressDialog ( mContext );
// mProgressDialog.setTitle ( "Downloading" );
// mProgressDialog.setMessage ( "Please wait..." );
//
// mProgressDialog.setMax(10);
// mProgressDialog.setButton ( ProgressDialog.BUTTON_NEGATIVE,"Cancel",(View.OnClickListener)(dialog,which);
// {
// dialog.cancel ( );
// cancel ( true );
// };
// if (!isProgressBar)
// mProgressDialog.show();
// }
//
//
// @Override
// protected String doInBackground(Void... voids) {
//
// try {
// for (int i = 1; i<=10;i++){
// Thread.sleep ( 1000 );
// Log.i ( "Thread" , "Execute" + i );
// publishProgress ( i,i*10);
// }
// return "Successful";
// } catch (InterruptedException e) {
// Log.i ( "Exception" , e.getMessage ( ) );
// return "Failure!";
// }
//
//}
//
//
//
// /**
// * Runs on the background thread.
// *
// * @param voids No parameters in this use case.
// * @return Returns the string including the amount of time that
// * the background thread slept.
// */
//
// @Override
// protected void onProgressUpdate (Integer...values){
// super.onProgressUpdate (values);
// int myValue1 =values[0];
// int myValue2 =values[1];
// if (!isProgressBar)
// mProgressDialog.setProgress ( myValue1 );
// else {
// mProgressBar.setProgress ( myValue2 );
// mProgressBar.setProgress ( myValue2+10 );
// }
// }
//
//// // Generate a random number between 0 and 10.
//// Random r = new Random();
//// int n = r.nextInt(11);
////
//// // Make the task take long enough that we have
//// // time to rotate the phone while it is running.
//// int s = n * 200;
////
//// // Sleep for the random amount of time.
//// try {
//// Thread.sleep(s);
//// } catch (InterruptedException e) {
//// e.printStackTrace();
//// }
////
//// // Return a String result.
//// return "Awake at last after sleeping for " + s + " milliseconds!";
//// }
//
// /**
// * Does something with the result on the UI thread; in this case
// * updates the TextView.
// */
//// protected void onPostExecute(String result) {
//// mTextView.get().setText(result);
// }
//
| true |
0b3d5abe4d212454cbc5d58ad8ffd4c943e31352
|
Java
|
VrainzAccelerator/commons-legacy
|
/MCPPersistence/mcp-model/src/main/java/com/vrains/persistence/oldmodel/mcp/Suscripcion.java
|
UTF-8
| 4,202 | 1.9375 | 2 |
[] |
no_license
|
package com.vrains.persistence.oldmodel.mcp;
import java.sql.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "MCP_suscripciones")
public class Suscripcion {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false, name = "id_suscripcion", columnDefinition = "BIGINT(20)")
Integer id_suscripcion;
@Column(nullable = false, name = "ani")
String ani;
@Column(name = "canal_alta")
String canal_alta;
@Column(name = "canal_baja")
String canal_baja;
@Column(nullable = false, name = "cantidad_publicaciones", columnDefinition = "INT(10)")
Integer cantidad_publicaciones;
@Column(nullable = false, name = "cobros_no_exitosos", columnDefinition = "INT(10)")
Integer cobros_no_exitosos;
@Column(name = "esme_id", columnDefinition = "INT(11)")
Integer esme_id;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "id_estado")
Estado estado;
@Column(name = "fecha_alta", columnDefinition = "DATETIME")
Date fecha_alta;
@Column(name = "fecha_baja", columnDefinition = "DATETIME")
Date fecha_baja;
@Column(name = "fecha_creacion", columnDefinition = "DATETIME")
Date fecha_creacion;
@Column(nullable = false, name = "fecha_ultima_publicacion", columnDefinition = "DATETIME")
Date fecha_ultima_publicacion;
@Column(nullable = false, name = "fecha_ultimo_cobro", columnDefinition = "DATETIME")
Date fecha_ultimo_cobro;
@Column(nullable = false, name = "id_cliente_operador", columnDefinition = "BIGINT(20)")
Integer id_cliente_operador;
@Column(name = "trans_id")
String trans_id;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "id_palabra")
Palabra palabra;
public Integer getId_suscripcion() {
return id_suscripcion;
}
public void setId_suscripcion(Integer id_suscripcion) {
this.id_suscripcion = id_suscripcion;
}
public String getAni() {
return ani;
}
public void setAni(String ani) {
this.ani = ani;
}
public String getCanal_alta() {
return canal_alta;
}
public void setCanal_alta(String canal_alta) {
this.canal_alta = canal_alta;
}
public String getCanal_baja() {
return canal_baja;
}
public void setCanal_baja(String canal_baja) {
this.canal_baja = canal_baja;
}
public Integer getCantidad_publicaciones() {
return cantidad_publicaciones;
}
public void setCantidad_publicaciones(Integer cantidad_publicaciones) {
this.cantidad_publicaciones = cantidad_publicaciones;
}
public Integer getCobros_no_exitosos() {
return cobros_no_exitosos;
}
public void setCobros_no_exitosos(Integer cobros_no_exitosos) {
this.cobros_no_exitosos = cobros_no_exitosos;
}
public Integer getEsme_id() {
return esme_id;
}
public void setEsme_id(Integer esme_id) {
this.esme_id = esme_id;
}
public Date getFecha_alta() {
return fecha_alta;
}
public void setFecha_alta(Date fecha_alta) {
this.fecha_alta = fecha_alta;
}
public Date getFecha_baja() {
return fecha_baja;
}
public void setFecha_baja(Date fecha_baja) {
this.fecha_baja = fecha_baja;
}
public Date getFecha_creacion() {
return fecha_creacion;
}
public void setFecha_creacion(Date fecha_creacion) {
this.fecha_creacion = fecha_creacion;
}
public Date getFecha_ultima_publicacion() {
return fecha_ultima_publicacion;
}
public void setFecha_ultima_publicacion(Date fecha_ultima_publicacion) {
this.fecha_ultima_publicacion = fecha_ultima_publicacion;
}
public Date getFecha_ultimo_cobro() {
return fecha_ultimo_cobro;
}
public void setFecha_ultimo_cobro(Date fecha_ultimo_cobro) {
this.fecha_ultimo_cobro = fecha_ultimo_cobro;
}
public Integer getId_cliente_operador() {
return id_cliente_operador;
}
public void setId_cliente_operador(Integer id_cliente_operador) {
this.id_cliente_operador = id_cliente_operador;
}
public String getTrans_id() {
return trans_id;
}
public void setTrans_id(String trans_id) {
this.trans_id = trans_id;
}
}
| true |
e1825163e1c86e3c0949db6d815b8ce531f307b1
|
Java
|
johnny8353/jproject
|
/springmvc/springmvc-demo/src/main/java/com/johnny/springmvc/converters/handlers/SpringMVCTest.java
|
UTF-8
| 1,784 | 2.03125 | 2 |
[] |
no_license
|
package com.johnny.springmvc.converters.handlers;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.johnny.springmvc.crud.dao.EmployeeDao;
import com.johnny.springmvc.crud.entities.Employee;
@Controller("convertersSpringMVCTest")
public class SpringMVCTest {
@Autowired
private EmployeeDao employeeDao;
@Autowired
private ResourceBundleMessageSource messageSource;
@RequestMapping("/testConversionServiceConverer")
public String testConverter(@RequestParam("employee") Employee employee){
System.out.println("save: " + employee);
employeeDao.save(employee);
return "redirect:/emps";
}
}
| true |
cab5b352be8a157383c2ceeaf1f30ad791e60382
|
Java
|
andreinamiling/practice-programming-problems
|
/ArmstrongNumber.java
|
UTF-8
| 618 | 4.0625 | 4 |
[] |
no_license
|
import java.util.*;
class ArmstrongNumber{
public static void main(String[]args){
Scanner s = new Scanner(System.in);
int num = 0, r = 0, sum = 0, temp = 0;
System.out.print("Enter an Integer: ");
num = s.nextInt();
temp = num; //Passing the value of num to temp
while (num!=0){
r = num % 10; //Get the Integer divisible by 10
sum = sum + r*r*r; //Cube every digit of the given Integer
num = num / 10; //Part of splitting the Integer
}
if (temp == sum)
System.out.print(sum+" Armstrong Number ");
else
System.out.print(sum+" Not Armstrong Number ");
}
}
| true |
e0c3666d0241cc18c165c0b917a2ea685e9b60a6
|
Java
|
rex731083168/passport
|
/passport/src/main/java/cn/ce/passport/controller/AuthController.java
|
UTF-8
| 4,012 | 2.046875 | 2 |
[] |
no_license
|
package cn.ce.passport.controller;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.ce.passport.common.util.JsonUtil;
import cn.ce.passport.dao.persistence.Auth;
import cn.ce.passport.dao.persistence.SysInfo;
import cn.ce.passport.service.IAuthService;
import cn.ce.passport.service.IRerationService;
import cn.ce.passport.service.ISysInfoService;
import cn.ce.passport.service.IUserService;
@RequestMapping("/auth")
@Controller
public class AuthController {
@Resource
IUserService userService;
@Resource
IAuthService authService;
@Resource
ISysInfoService sysInfoService;
@Resource
IRerationService rerationService;
public static Logger logger = LoggerFactory.getLogger(AuthController.class);
@RequestMapping("/getAuths")
@ResponseBody
public String getAuths(String authName, String systemId, String isvalid) {
Map<String, Object> retMap = new HashMap<String, Object>();
retMap.put("code", 200);
retMap.put("msg", "ok");
Map<String, Object> condition = new HashMap<String, Object>();
condition.put("authName", authName);
condition.put("systemId", systemId);
condition.put("isvalid", isvalid);
List<Auth> authList = authService.getAuths(condition);
retMap.put("authList", authList);
return JsonUtil.toJson(retMap);
}
@RequestMapping("/addAuth")
@ResponseBody
public String addAuth(String authName, String url, String systemId,
long parentId) {
Map<String, Object> retMap = new HashMap<String, Object>();
retMap.put("code", 200);
retMap.put("msg", "ok");
if (systemId == null || "".equals(systemId)) {
retMap.put("code", 1);
retMap.put("msg", "systemId is required");
}
int belongSys = Integer.valueOf(systemId);
Date date = new Date();
Auth auth = new Auth();
auth.setAuthName(authName);
auth.setUrl(url);
auth.setBelongSys(belongSys);
auth.setCreateTime(date);
auth.setParentId(parentId);
auth.setIsvalid(0);
auth.setStatus(0);
int ret = authService.addAuth(auth);
if (ret == 0) {
retMap.put("code", 200);
retMap.put("msg", "insert auth failed");
return JsonUtil.toJson(retMap);
}
retMap.put("auth", auth);
return JsonUtil.toJson(retMap);
}
/**
* 获取权限
*
* @param request
* @return
*/
@RequestMapping("/getAuth")
@ResponseBody
public String getAuth(HttpServletRequest request, String authId) {
Map<String, Object> retMap = new HashMap<String, Object>();
retMap.put("code", 200);
retMap.put("msg", "ok");
long authid = Integer.parseInt(authId);
Auth auth = authService.getById(authid);
List<SysInfo> sysInfo = sysInfoService.getSysInfo();
Map<String, Object> dataMap = new HashMap<String, Object>();
dataMap.put("sysInfo", sysInfo);
dataMap.put("auth", auth);
retMap.put("data", dataMap);
return JsonUtil.toJson(retMap);
}
@RequestMapping("/updateAuth")
@ResponseBody
public String updateAuth(long authId, String authName, String url,
String systemId, long parentId) {
Map<String, Object> retMap = new HashMap<String, Object>();
retMap.put("code", 200);
retMap.put("msg", "ok");
int belongSys = Integer.valueOf(systemId);
Auth auth = new Auth();
auth.setAuthId(authId);
auth.setAuthName(authName);
auth.setUrl(url);
auth.setBelongSys(belongSys);
auth.setParentId(parentId);
int i = authService.updateAuth(auth);
if (i == 0) {
retMap.put("code", 1);
retMap.put("msg", "updateFailed");
return JsonUtil.toJson(retMap);
}
retMap.put("auth", auth);
return JsonUtil.toJson(retMap);
}
}
| true |
7fee066d0c6784f694474ba290892a86ee9b3fe3
|
Java
|
owenzip/todos-app
|
/todoapp/app/src/main/java/com/example/gamma/todoapp/AnimationEffect.java
|
UTF-8
| 1,032 | 2.234375 | 2 |
[] |
no_license
|
package com.example.gamma.todoapp;
import android.content.Context;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
/**
* Created by Bean on 17/01/2018.
*/
public class AnimationEffect {
public static Animation animCircular (Context context) {
Animation animCircular = AnimationUtils.loadAnimation(context,R.anim.anim_circular);
return animCircular;
}
public static Animation animHideToZoom (Context context) {
Animation animHideToZoom = AnimationUtils.loadAnimation(context, R.anim.anim_hide_to_zoom);
return animHideToZoom;
}
public static Animation animLeftToRight (Context context) {
Animation animLeftToRight = AnimationUtils.loadAnimation(context, R.anim.anim_left_to_right);
return animLeftToRight;
}
public static Animation animTopToBottom (Context context) {
Animation animTopToBottom = AnimationUtils.loadAnimation(context, R.anim.anim_top_to_bottom);
return animTopToBottom;
}
}
| true |
87c9fce000958c659e1386c4b8cd516573dd2bf7
|
Java
|
gvquiroz/aydoo2016
|
/extension-libreria/src/main/java/ar/edu/untref/aydoo/PublicacionPeriodica.java
|
UTF-8
| 931 | 2.890625 | 3 |
[] |
no_license
|
package ar.edu.untref.aydoo;
public class PublicacionPeriodica extends Producto implements Suscribible {
private final int periodicidadMensual;
private boolean suscripcion;
private boolean tieneDescuento;
public PublicacionPeriodica(String nombre, double monto, int nuevaPeriodicidadMensual) {
super(nombre, monto);
this.periodicidadMensual = nuevaPeriodicidadMensual;
this.tieneDescuento = false;
}
@Override
public void setSuscripcionMensual() {
if (tieneDescuento) {
double productoConDescuento = this.getValor() - (this.getValor() * 0.2);
this.setValor(this.periodicidadMensual * productoConDescuento);
} else {
this.setValor(this.periodicidadMensual * this.getValor());
}
this.suscripcion = true;
}
@Override
public void agregarDescuento() {
this.tieneDescuento = true;
}
}
| true |
0ba1549ee1b6ef1b9833030345b8d14d0ba216e6
|
Java
|
otoukebri/atom
|
/atom-game-engine/src/main/java/net/vpc/gaming/atom/ioc/AtomSpriteCreationAction.java
|
UTF-8
| 5,440 | 2.34375 | 2 |
[] |
no_license
|
package net.vpc.gaming.atom.ioc;
import net.vpc.gaming.atom.annotations.AtomSprite;
import net.vpc.gaming.atom.annotations.OnInstall;
import net.vpc.gaming.atom.engine.GameEngine;
import net.vpc.gaming.atom.engine.SceneEngine;
import net.vpc.gaming.atom.engine.SpriteTask;
import net.vpc.gaming.atom.engine.collision.SpriteCollisionManager;
import net.vpc.gaming.atom.model.Sprite;
import net.vpc.gaming.atom.presentation.Game;
import net.vpc.gaming.atom.presentation.Scene;
import java.util.HashMap;
import java.util.List;
/**
* Created by vpc on 10/7/16.
*/
class AtomSpriteCreationAction implements PostponedAction {
private AtomAnnotationsProcessor atomAnnotationsProcessor;
private final Class clazz;
private final AtomSprite s;
private final Game game;
public AtomSpriteCreationAction(AtomAnnotationsProcessor atomAnnotationsProcessor, Class clazz, AtomSprite s, Game game) {
this.atomAnnotationsProcessor = atomAnnotationsProcessor;
this.clazz = clazz;
this.s = s;
this.game = game;
}
@Override
public boolean isRunnable() {
for (String sceneEnginId : AtomAnnotationsProcessor.split(s.engine())) {
if (atomAnnotationsProcessor.container.isInjectedType(clazz, Scene.class)) {
if (!(atomAnnotationsProcessor.container.contains(sceneEnginId, "SceneEngine")
&&
game.findScenesBySceneEnginId(sceneEnginId).size() > 0)
) {
return false;
}
} else {
if (!atomAnnotationsProcessor.container.contains(sceneEnginId, "SceneEngine")) {
return false;
}
}
}
return true;
}
@Override
public int getOrder() {
return AtomAnnotationsProcessor.ORDER_SPRITE;
}
@Override
public void run() {
for (String sceneEngineId : AtomAnnotationsProcessor.split(s.engine())) {
final SceneEngine sceneEngine = game.getGameEngine().getSceneEngine(sceneEngineId);
InstancePreparator prep = new InstancePreparator() {
@Override
public void prepare(Object o) {
Sprite sprite = (Sprite) o;
sprite.setName(s.name());
sprite.setSpeed(s.speed());
sprite.setLocation(s.x(), s.y());
sprite.setDirection(s.direction());
sprite.setSize(s.width(), s.height());
sprite.setLife(s.life());
sprite.setMaxLife(s.maxLife());
sprite.setSight(s.sight());
}
};
Sprite sprite = null;
Object instance = null;
if (Sprite.class.isAssignableFrom(clazz)) {
HashMap<Class, Object> injects = new HashMap<>();
injects.put(Game.class, game);
injects.put(GameEngine.class, game.getGameEngine());
injects.put(SceneEngine.class, sceneEngine);
List<Scene> scenesBySceneEnginId = game.findScenesBySceneEnginId(sceneEngineId);
if (scenesBySceneEnginId.size() == 1) {
injects.put(Scene.class, scenesBySceneEnginId.get(0));
} else {
injects.put(Scene[].class, scenesBySceneEnginId.toArray(new Scene[scenesBySceneEnginId.size()]));
}
sprite = (Sprite) atomAnnotationsProcessor.container.create(clazz, prep, injects);
sceneEngine.addSprite(sprite);
instance = sprite;
} else {
sprite = sceneEngine.createSprite(s.kind());
sprite.setName(s.name());
HashMap<Class, Object> injects = new HashMap<>();
injects.put(Game.class, game);
injects.put(GameEngine.class, game.getGameEngine());
injects.put(SceneEngine.class, sceneEngine);
injects.put(Sprite.class, sprite);
List<Scene> scenesBySceneEnginId = game.findScenesBySceneEnginId(sceneEngineId);
if (scenesBySceneEnginId.size() == 1) {
injects.put(Scene.class, scenesBySceneEnginId.get(0));
} else {
injects.put(Scene[].class, scenesBySceneEnginId.toArray(new Scene[scenesBySceneEnginId.size()]));
}
instance = atomAnnotationsProcessor.container.create(clazz, null, injects);
prep.prepare(sprite);
sceneEngine.addSprite(sprite);
}
if (!s.task().equals(Void.class)) {
sceneEngine.setSpriteTask(sprite.getId(), (SpriteTask) atomAnnotationsProcessor.container.create(
s.task(), null, null
));
}
if (!s.collision().equals(Void.class)) {
sceneEngine.setSpriteCollisionManager(sprite.getId(), (SpriteCollisionManager) atomAnnotationsProcessor.container.create(
s.collision(), null, null
));
}
atomAnnotationsProcessor.container.register(
sceneEngineId+"/"+s.name(), "Sprite", instance);
atomAnnotationsProcessor.container.invokeMethodsByAnnotation(instance, OnInstall.class, new Object[0]);
}
}
}
| true |
08e7a1ad33a82b507487320e02aae3d043c04317
|
Java
|
JesusMaestreCarmona/MyBankSpringBoot
|
/src/main/java/com/myBank/controllers/UsuarioController.java
|
UTF-8
| 5,327 | 2.171875 | 2 |
[] |
no_license
|
package com.myBank.controllers;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
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.RestController;
import com.myBank.jwtSecurity.AutenticadorJWT;
import com.myBank.model.entities.Usuario;
import com.myBank.model.repositories.UsuarioRepository;
@CrossOrigin
@RestController
public class UsuarioController {
@Autowired
UsuarioRepository usuarioRepository;
@PostMapping("/usuario/autenticar")
public DTO autenticaUsuario (@RequestBody DatosAutenticacionUsuario datos) {
DTO dto = new DTO();
Usuario usuAutenticado = usuarioRepository.findByEmailAndPassword(datos.email, datos.password);
if (usuAutenticado != null) {
dto.put("jwt", AutenticadorJWT.codificaJWT(usuAutenticado));
}
return dto;
}
@GetMapping("/usuario/getAutenticado")
public DTO getUsuarioAutenticado (boolean imagen, HttpServletRequest request) {
DTO dtoResultado = null;
int idUsuAutenticado = AutenticadorJWT.getIdUsuarioDesdeJwtIncrustadoEnRequest(request);
if (idUsuAutenticado != -1) {
Usuario usuAutenticado = usuarioRepository.findById(idUsuAutenticado).get();
dtoResultado = DTO.getDTOFromUsuario(usuAutenticado, imagen);
}
return dtoResultado;
}
@PutMapping("/usuario/actualizarDatosUsuario")
public DTO actualizarDatosUsuario(@RequestBody DatosUsuario datosNuevoUsuario, HttpServletRequest request) {
DTO dto = new DTO();
dto.put("result", "fail");
try {
int idUsuAutenticado = AutenticadorJWT.getIdUsuarioDesdeJwtIncrustadoEnRequest(request);
if (idUsuAutenticado != -1) {
Usuario usuAutenticado = usuarioRepository.findById(idUsuAutenticado).get();
usuAutenticado.setNombre(datosNuevoUsuario.nombre);
usuAutenticado.setApellido1(datosNuevoUsuario.apellido1);
usuAutenticado.setApellido2(datosNuevoUsuario.apellido2);
if (datosNuevoUsuario.imagen != null) usuAutenticado.setImagen(Base64.decodeBase64(datosNuevoUsuario.imagen));
usuAutenticado.setFechaNac(new Date(datosNuevoUsuario.fecha_nac));
usuAutenticado.setTelefono(datosNuevoUsuario.telefono);
usuAutenticado.setDireccion(datosNuevoUsuario.direccion);
usuAutenticado.setLocalidad(datosNuevoUsuario.localidad);
usuAutenticado.setCodigoPostal(datosNuevoUsuario.codigo_postal);
if (datosNuevoUsuario.password != "") usuAutenticado.setPassword(datosNuevoUsuario.password);
this.usuarioRepository.save(usuAutenticado);
}
dto.put("result", "ok");
} catch (Exception e) {
e.printStackTrace();
}
return dto;
}
@GetMapping("/usuario/buscarEmail")
public DTO buscarEmail(String email) {
DTO dto = new DTO();
boolean emailEncontrado = false;
if (this.usuarioRepository.findByEmail(email) != null) emailEncontrado = true;
dto.put("emailEncontrado", emailEncontrado);
return dto;
}
@PutMapping("/usuario/registrarUsuario")
public DTO registrarUsuario (@RequestBody DatosUsuario datosNuevoUsuario) {
DTO dto = new DTO();
dto.put("result", "fail");
try {
Usuario usuarioARegistrar = new Usuario();
usuarioARegistrar.setNombre(datosNuevoUsuario.nombre);
usuarioARegistrar.setApellido1(datosNuevoUsuario.apellido1);
usuarioARegistrar.setApellido2(datosNuevoUsuario.apellido2);
usuarioARegistrar.setEmail(datosNuevoUsuario.email);
usuarioARegistrar.setPassword(datosNuevoUsuario.password);
if (datosNuevoUsuario.imagen != null) usuarioARegistrar.setImagen(Base64.decodeBase64(datosNuevoUsuario.imagen));
usuarioARegistrar.setFechaNac(new Date(datosNuevoUsuario.fecha_nac));
usuarioARegistrar.setTelefono(datosNuevoUsuario.telefono);
usuarioARegistrar.setDireccion(datosNuevoUsuario.direccion);
usuarioARegistrar.setLocalidad(datosNuevoUsuario.localidad);
usuarioARegistrar.setCodigoPostal(datosNuevoUsuario.codigo_postal);
this.usuarioRepository.save(usuarioARegistrar);
dto.put("result", "ok");
} catch (Exception e) {
e.printStackTrace();
}
return dto;
}
}
class DatosAutenticacionUsuario {
String email;
String password;
public DatosAutenticacionUsuario(String email, String password) {
super();
this.email = email;
this.password = password;
}
}
class DatosUsuario {
String email;
String password;
String nombre;
String apellido1;
String apellido2;
String imagen;
long fecha_nac;
String telefono;
String direccion;
String localidad;
String codigo_postal;
public DatosUsuario(String email, String password, String nombre, String apellido1, String apellido2, String imagen,
String telefono, String direccion, String localidad, String codigo_postal, long fecha_nac) {
super();
this.email = email;
this.password = password;
this.nombre = nombre;
this.apellido1 = apellido1;
this.apellido2 = apellido2;
this.imagen = imagen;
this.telefono = telefono;
this.direccion = direccion;
this.localidad = localidad;
this.codigo_postal = codigo_postal;
this.fecha_nac = fecha_nac;
}
}
| true |
bac36fc3b51445569d0a89e6a5c587c694ce67fd
|
Java
|
xsRST/MyProject
|
/Scoket/src/test/java/Test.java
|
UTF-8
| 185 | 2.09375 | 2 |
[] |
no_license
|
import org.apache.commons.lang.StringUtils;
public class Test {
public static void main(String[] args) {
System.out.println(StringUtils.stripStart("60000", "0"));
}
}
| true |
349e5e0c0be330330d0249ced84bc29ba0582fed
|
Java
|
gembin/virgo.apps
|
/org.eclipse.virgo.apps.admin.core/src/main/java/org/eclipse/virgo/apps/admin/core/state/StandardRequiredBundleHolder.java
|
UTF-8
| 3,021 | 1.710938 | 2 |
[] |
no_license
|
/*******************************************************************************
* Copyright (c) 2008, 2010 VMware Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* VMware Inc. - initial contribution
*******************************************************************************/
package org.eclipse.virgo.apps.admin.core.state;
import java.util.Map;
import org.eclipse.virgo.apps.admin.core.BundleHolder;
import org.eclipse.virgo.apps.admin.core.RequiredBundleHolder;
import org.eclipse.virgo.kernel.module.ModuleContextAccessor;
import org.eclipse.virgo.kernel.osgi.quasi.QuasiRequiredBundle;
import org.eclipse.virgo.util.osgi.VersionRange;
/**
* <p>
* StandardRequiredBundleHolder is the standard implementation of {@link RequiredBundleHolder}.
* </p>
*
* <strong>Concurrent Semantics</strong><br />
*
* StandardRequiredBundleHolder is thread-safe
*
*/
final class StandardRequiredBundleHolder implements RequiredBundleHolder {
private final QuasiRequiredBundle quasiRequiredBundle;
private final ModuleContextAccessor moduleContextAccessor;
public StandardRequiredBundleHolder(QuasiRequiredBundle quasiRequiredBundle, ModuleContextAccessor moduleContextAccessor) {
this.quasiRequiredBundle = quasiRequiredBundle;
this.moduleContextAccessor = moduleContextAccessor;
}
/**
* {@inheritDoc}
*/
public BundleHolder getProvider() {
return new StandardBundleHolder(this.quasiRequiredBundle.getProvider(), this.moduleContextAccessor);
}
/**
* {@inheritDoc}
*/
public String getRequiredBundleName() {
return this.quasiRequiredBundle.getRequiredBundleName();
}
/**
* {@inheritDoc}
*/
public BundleHolder getRequiringBundle() {
return new StandardBundleHolder(this.quasiRequiredBundle.getRequiringBundle(), this.moduleContextAccessor);
}
/**
* {@inheritDoc}
*/
public String getVersionConstraint() {
VersionRange versionConstraint = this.quasiRequiredBundle.getVersionConstraint();
if(versionConstraint == null) {
versionConstraint = VersionRange.NATURAL_NUMBER_RANGE;
}
return versionConstraint.toString().replace(", oo]", ", ∞]").replace(", oo)", ", ∞)");
}
/**
* {@inheritDoc}
*/
public Map<String, String> getAttributes() {
return ObjectFormatter.formatMapValues(this.quasiRequiredBundle.getAttributes());
}
/**
* {@inheritDoc}
*/
public Map<String, String> getDirectives() {
return ObjectFormatter.formatMapValues(this.quasiRequiredBundle.getDirectives());
}
/**
* {@inheritDoc}
*/
public boolean isResolved() {
return this.quasiRequiredBundle.isResolved();
}
}
| true |
1b379befe8ad4de77ff7884dc9a9afa9fd271248
|
Java
|
StanAlexandru/struts-learning
|
/hello-world-from-struts2/src/main/java/com/learn/processingforms/action/RegisterAction.java
|
UTF-8
| 1,357 | 2.453125 | 2 |
[] |
no_license
|
package com.learn.processingforms.action;
import org.apache.struts2.convention.annotation.Result;
import com.learn.processingforms.model.Person;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
@org.apache.struts2.convention.annotation.Action(value = "register", results = {
@Result(name = "success", location = "/thankYou.jsp"),
@Result(name = "input", location = "/register.jsp")
}
)
public class RegisterAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private Person personBean;
@Override
public String execute() throws Exception {
// call Service class to store personBean's state in database
if (personBean != null) {
return Action.SUCCESS;
} else {
return Action.INPUT;
}
}
@Override
public void validate() {
if (personBean != null) {
if (personBean.getFirstName().length() == 0) {
addFieldError("personBean.firstName", "First name is required.");
}
if (personBean.getEmail().length() == 0) {
addFieldError("personBean.email", "Email is required.");
}
if (personBean.getAge() < 18) {
addFieldError("personBean.age", "Age is required and must be 18 or older");
}
}
}
public Person getPersonBean() {
return personBean;
}
public void setPersonBean(Person personBean) {
this.personBean = personBean;
}
}
| true |
0824c151c2dfe905d8ae53d8bc2b272fef7dfc89
|
Java
|
ma2695212419/haikang
|
/src/main/java/com/mzp/haikang/face/FaceAlarmBusiness.java
|
UTF-8
| 3,260 | 2.046875 | 2 |
[] |
no_license
|
package com.mzp.haikang.face;
import com.mzp.haikang.commons.AlarmBusiness;
import com.mzp.haikang.commons.Constants;
import com.mzp.haikang.commons.HikBean;
import com.mzp.haikang.commons.HikCache;
import com.mzp.haikang.dao.ConfigMapper;
import com.mzp.haikang.model.Config;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.List;
@Component
public class FaceAlarmBusiness extends AlarmBusiness {
@Autowired
ConfigMapper configMapper;
private static ConfigMapper myUtil;
private static final Logger logger = LogManager.getLogger(FaceAlarmBusiness.class);
HikBusiness hikBusiness = new HikBusiness();
@PostConstruct
public void init() {
myUtil = configMapper;
}
public boolean open(String ip, HikBean hikBean) {
if (!hikBusiness.init(ip, hikBean)) {
logger.error("初始化失败");
return false;
}
logger.info("初始化成功");
if (hikBusiness.login() == -1) {
logger.error("登录失败");
return false;
}
logger.info("登录成功");
if (!hikBusiness.setDVRMessageCallBack()) {
logger.error("设置回调失败");
return false;
}
logger.info("设置回调成功");
if (hikBusiness.setupAlarmChan() == -1) {
logger.error("设置布防失败");
return false;
}
logger.info("设置布防成功");
return true;
}
public boolean close(String ip) {
if (!HikCache.hikBusinessMap.containsKey(ip)) {
logger.error("设备未开启, ip:" + ip);
return false;
}
hikBusiness = (HikBusiness) HikCache.hikBusinessMap.get(ip);
if (hikBusiness.lAlarmHandle.intValue() > -1 && !hikBusiness.closeAlarmChan()) {
logger.error("撤防失敗");
return false;
}
logger.info("撤防成功");
if (!hikBusiness.logout()) {
logger.error("登出失敗");
return false;
}
logger.info("登出成功");
if (!hikBusiness.cleanup()) {
logger.error("释放失敗");
return false;
}
logger.info("释放成功");
return true;
}
public static void startProgress() {
List<Config> configs = myUtil.selectAll();
for (Config config : configs) {
System.out.println(config.getIp());
HikBean hikBean = new HikBean();
hikBean.setUsername(config.getHikusername());
hikBean.setPassword(config.getHikpassword());
hikBean.setPort(Integer.parseInt(config.getHikport()));
hikBean.setAuthorization("token 123");
new FaceDetectionThread(config.getIp(), hikBean, Constants.ACTION_TYPE_OPEN).start();
}
}
public static void endProgress() {
for (int i = 0; i < HikCache.ipList.length; i++) {
new FaceDetectionThread(HikCache.ipList[i], HikCache.mHikBean, Constants.ACTION_TYPE_CLOSE).start();
}
}
}
| true |
56f497e5979ed4380f1bd7cf288b5bdc330c5e22
|
Java
|
ZoranLi/wechat_reversing
|
/com/tencent/mm/ui/tools/SquareImageView.java
|
UTF-8
| 728 | 2.234375 | 2 |
[] |
no_license
|
package com.tencent.mm.ui.tools;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
public class SquareImageView extends ImageView {
public SquareImageView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
public SquareImageView(Context context, AttributeSet attributeSet, int i) {
super(context, attributeSet, i);
}
protected void onMeasure(int i, int i2) {
int defaultSize = getDefaultSize(getSuggestedMinimumWidth(), i);
setMeasuredDimension(defaultSize, defaultSize);
}
protected void onSizeChanged(int i, int i2, int i3, int i4) {
super.onSizeChanged(i, i, i3, i4);
}
}
| true |
3a46dd27f898daee1d89ab031b582f9ad494d929
|
Java
|
GabrielMVzla/Portafolio
|
/Prácticas_Tutorías_Fundamentos/EjerciciosClase/parametros/ExplicacionMetodoLlamada.java
|
WINDOWS-1250
| 409 | 3.46875 | 3 |
[] |
no_license
|
package parametros;
public class ExplicacionMetodoLlamada
{
public static double RetornaTipoDouble()
{
double retorna = 10.0;
//retorna tiene el valor de 10 en un inicio
//la siguiente operacin es como si dijera
//10.0 + 10.0 = nuevo valor en retorna, es decir, 20.0
//recordar que las instrucciones se ejecutan de derecha a izq.
retorna = retorna + retorna;
return retorna;
}
}
| true |
7f97af36e03196caaebe8031c5d2f4b38d228af4
|
Java
|
lifelonglearner127/ssorestcommon
|
/src/main/java/com/idfconnect/ssorest/common/utils/ConfigProperties.java
|
UTF-8
| 42,049 | 2.375 | 2 |
[] |
no_license
|
/*
* Copyright 2013 IDF Connect, Inc.
* All Rights Reserved.
*/
package com.idfconnect.ssorest.common.utils;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.LoggerFactory;
import com.idfconnect.ssorest.common.SSORestException;
/**
* This is a customized map class that is used for storing <code>String</code> -based properties. It is somewhat similar to <code>java.util.Properties</code>,
* but it uses case-insensitive keys and supports multi-valued properties. A key map is maintained that maps the lower case versions of all property keys to the
* original case that is actually used to store a property. Using this map, the class allows properties to be stored and retrieved using case-insensitive keys,
* while maintaining the original-cased keys in its keyset.
* <p>
* A property can be mapped to a single value or a List object containing single values. All values are stored internally as <code>String</code> objects. Use
* <code>getProperty</code> to retrieve a property's value(s) as an <code>Object </code>(either a <code>List</code> or a <code>String</code> will be returned).
* Use the <code>isMultiProperty</code> method to determine whether a property is a single or multi-valued property. Use <code>getPropertyAsString</code> to
* retrieve the value of a single-valued property. Use <code>getPropertyAsSingleValue</code> to return a single value for a property. If used on a multi-valued
* property, this method will return its first value. Use <code>getPropertyAsList</code> to get the value of a multi-valued property. This method will return a
* list with one element if used on a single-valued property. Convenience methods exist to allow data to be set and retrieved for single-valued properties using
* non-String data types, as described below.
* <p>
* All methods of the form <code>setProperty(String key, <em>type</em> value)</code> are used to set a single-valued property whose value will be the value of
* <type> converted into a String. For each such method, there is a get property of the form
* <code>getPropertyAs<em>type</em>(String key, <em>type</em> defaultValue)</code> used to retrieve a single-valued property by converting the String value back
* into the specified type. If the key can not be found, or if the value can not be converted into the requested type, the value specified in
* <code>defaultValue</code> will be returned.
* <p>
* Additionally, for each type supported (including Strings), a method exists in the form <code>getRequiredPropertyAs<em>type</em>(String key)</code>. These
* methods are identical to their corresponding methods that do not contain "Required" except that they are used to request properties that are expected to be
* present; accordingly, they will throw exceptions if the property is not found or contains a value that can not be converted to the requested data type.
* <p>
* Note: the <code>getPropertyAsSingleValue</code> method is identical to the <code>getPropertyAsString</code> method except that it returns type Object instead
* of type <code>String</code>. This method is included for possible future expansion of this class to handle storing non-<code>String</code> properties
* internally.
* <p>
* Methods to load and store to streams are included for backwards compatibility to older versions of <code>ConfigProperties</code>. These methods delegate to
* <code>Properties</code> instances and do not support the full range of capabilities of this class.
*
* @author rsand
* @since 1.4
*/
public final class ConfigProperties implements Map<String, Object>, Serializable {
private static final long serialVersionUID = -5374943004309439412L;
/** Constant <code>TRUE="true"</code> */
public static final String TRUE = "true";
/** Constant <code>FALSE="false"</code> */
public static final String FALSE = "false";
/** Constant <code>DELIMITER="^"</code> */
public static final String DELIMITER = "^";
private static final String DOT = ".";
// the wrapped map with original-case keys
ConcurrentHashMap<String, Object> themap;
// the map of lowercase keys to the original keyname
ConcurrentHashMap<String, String> keyMap;
String delimiter = DELIMITER;
String prefix = null;
/**
* ConfigProperties constructor comment.
*
* @since 1.4.2
*/
public ConfigProperties() {
super();
keyMap = new ConcurrentHashMap<>();
themap = new ConcurrentHashMap<>();
}
/**
* ConfigProperties constructor comment.
*
* @param delimiter a {@link java.lang.String} object.
* @param prefix a {@link java.lang.String} object.
* @since 3.0.2
*/
public ConfigProperties(String delimiter, String prefix) {
super();
keyMap = new ConcurrentHashMap<>();
themap = new ConcurrentHashMap<>();
this.delimiter = delimiter;
this.prefix = prefix;
}
/**
* {@inheritDoc}
*
* We clone similarly to Hashtable here - referenced to keys and values are retained but other parts are copied
*/
@Override
public synchronized Object clone() {
ConfigProperties cpc = new ConfigProperties();
cpc.keyMap = new ConcurrentHashMap<String, String>(keyMap);
cpc.themap = new ConcurrentHashMap<String, Object>(themap);
return cpc;
}
/**
* Returns the original (fully-cased) key used to store a property.
*
* @param key
* a case-insensitive key for which to retrieve the original key
* @return the original (fully-cased) key used to store a property
*/
private String getRealKey(String key) {
// Convert key to lowercase and check the keyMap to retrieve the mixed-case key used to store that case-less key
String lkey = key.toLowerCase();
String realkey = keyMap.get(lkey);
// If there was no key in the map, use the lower case key (we don't store map keys if they are already in lower case)
if (realkey == null)
realkey = lkey;
// Now we should have the key that has actually been used to store this property
return realkey;
}
/**
* Returns the value for the specified property. This method will return a <code>String</code> for a single-valued property or a <code>List</code> for a
* multi-valued property. If the specified property is not found, <code>null</code> will be returned.
*
* @param key
* a case-insensitive key for which to retrieve a property
* @return the value associated with the specified key
* @since 1.4.2
*/
public final Object getProperty(String key) {
// Property names are accessed in a case-insensitive way but we store keys in their original cases in case we want to retrieve them later. We use the
// getRealKey() method here to go through the key index to locate the original key used to store the case-neutral version of the specified key.
String realKey = getRealKey(key);
if (realKey == null)
return null;
// Now we should have the key that has actually been used to store this property
return themap.get(realKey);
}
/**
* Returns the value for the specified property. This method will return a <code>String</code> for a single-valued property or a <code>List</code> for a
* multi-valued property. If the specified property is not found, an <code>SSORestException</code> will be thrown.
*
* @param key
* a case-insensitive key for which to retrieve a required property value
* @return the value associated with the specified key
* @throws com.idfconnect.ssorest.common.SSORestException
* if no value exists for the specified key
* @since 1.4.2
*/
public final Object getRequiredProperty(String key) throws SSORestException {
Object o = getProperty(key);
if (o == null)
throw new SSORestException("Required integer parameter missing or invalid: " + key);
return o;
}
/**
* Returns the value for the specified property. This method will return a <code>String</code> for a single-valued property or a <code>List</code> for a
* multi-valued property. If the specified value is not found, <code>defaultValue</code> will be returned.
*
* @param key
* a case-insensitive key for which to retrieve a property value
* @param defaultValue
* a {@link java.lang.Object} object.
* @return the value associated with the specified key
* @since 1.4.2
*/
public final Object getProperty(String key, Object defaultValue) {
Object val = getProperty(key);
if (val == null)
return defaultValue;
else
return val;
}
/**
* Gets a single-valued property object for the specified key. Keys are case-insensitive, so two keys whose lower-case conversions are identical will map to
* the same value.
* <p>
* If the property is not found, the request will be passed to the default property set if one is available. If the property is still not found, null will
* be returned.
* <p>
* If a multi-valued property is found, the first value will be returned (multi-valued properties are stored internally as List objects).
*
* @param key
* a case-insensitive key for which to retrieve a property value
* @return the value associated with the specified key
* @since 1.4.2
*/
public final Object getPropertyAsSingleValue(String key) {
Object val = getProperty(key);
if (val instanceof List) {
// We found a multi-valued property - return the first value only
return ((List<?>) val).isEmpty() ? null : ((List<?>) val).get(0);
} else
return val;
}
/**
* Gets a single-valued property object for the specified key. Keys are case-insensitive, so two keys whose lower-case conversions are identical will map to
* the same value.
* <p>
* If the property is not found, the request will be passed to the default property set if one is available. If the property is still not found, the
* specified default value will be returned.
* <p>
* If a multi-valued property is found, the first value will be returned (multi-valued properties are stored internally as List objects).
*
* @param key
* a case-insensitive key for which to retrieve a property value
* @param defaultValue
* a {@link java.lang.Object} object.
* @return the value associated with the specified key
* @since 1.4.2
*/
public final Object getPropertyAsSingleValue(String key, Object defaultValue) {
Object val = getPropertyAsSingleValue(key);
return (val == null) ? defaultValue : val;
}
/**
* Returns true if the value for the specified key is multi-valued. Note that multi-valued indicates that zero or more values are stored in a List object
* associated with the property's key, so it is possible for a multi-valued property to have only a single value.
* <p>
* If the property is not found, the request will be passed to the default property set if one is available. If the property is still not found, false will
* be returned.
*
* @param key
* a case-insensitive key
* @return true if the value for the specified key is multi-valued
* @since 1.4.2
*/
public final boolean isMultiProperty(String key) {
String realKey = getRealKey(key);
Object val = themap.get(realKey);
if (val == null)
return false;
return (val instanceof List<?>);
}
/**
* Gets a multi-valued property object for the specified key. Keys are case-insensitive, so two keys whose lower-case conversions are identical will map to
* the same value.
* <p>
* If the property is not found, the request will be passed to the default property set if one is available. If the property is still not found, null will
* be returned.
* <p>
* If a single-valued property is found, it is wrapped in a List and returned. Note that in this case changes made to the list will not be reflected in the
* property set since no reference to the List object is itself maintained. Also, if the single-valued property is an empty string, we interpret that as an
* empty list so the list will contain no elements.
*
* @param key
* a case-insensitive key for which to retrieve a property value
* @return the value associated with the specified key converted to a list
* @since 1.4.2
*/
@SuppressWarnings("unchecked")
public final List<String> getPropertyAsList(String key) {
Object prop = getProperty(key);
if (prop == null)
return null;
else if (prop instanceof List) {
// We found a multi-valued property - return it
return (List<String>) prop;
} else {
// We found a single-valued property - wrap it in a list and return it
List<String> mProp = new ArrayList<String>();
// We leave the list empty if prop is an empty string, otherwise add prop to the list
if (!(prop instanceof String) || (((String) prop).length() > 0))
mProp.add((String) prop);
return mProp;
}
}
/**
* Gets a multi-valued property object for the specified key. Keys are case-insensitive, so two keys whose lower-case conversions are identical will map to
* the same value.
* <p>
* If the property is not found, the request will be passed to the default property set if one is available. If the property is still not found, the
* specified default value will be returned.
* <p>
* If a single-valued property is found, it is wrapped in a List and returned. Note that in this case changes made to the list will not be reflected in the
* property set since no reference to the List object is itself maintained.
*
* @param key
* a case-insensitive key for which to retrieve a property value
* @param defaultValue
* a {@link java.util.List} object.
* @return the value associated with the specified key converted to a list
* @since 1.4.2
*/
public final List<String> getPropertyAsList(String key, List<String> defaultValue) {
List<String> val = getPropertyAsList(key);
return (val == null) ? defaultValue : val;
}
/**
* Gets a single-valued property object for the specified key. This method simply delegates to the getPropertyAsSingleValue(String) method, returning null
* if a non-String value is returned.
*
* @param key
* a case-insensitive key for which to retrieve a property value
* @return the value associated with the specified key
* @since 1.4.2
*/
public final String getPropertyAsString(String key) {
Object val = getPropertyAsSingleValue(key);
return (val instanceof String) ? (String) val : null;
}
/**
* Gets a single-valued property object for the specified key, using first the default property list then the specified default value if the value is not
* found in this property list.
*
* @param key
* a case-insensitive key for which to retrieve a property value
* @param defaultValue
* a {@link java.lang.String} object.
* @return the value associated with the specified key
* @since 1.4.2
*/
public final String getPropertyAsString(String key, String defaultValue) {
String val = getPropertyAsString(key);
return (val == null) ? defaultValue : val;
}
/**
* Sets a property with a String value or List of only String values. Any other type will cause an IllegalArgumentException to be thrown. It is recommended
* that for normal circumstances you avoid this method and instead use the various setProperty() methods instead.
*
* @param key
* the key for the property to store
* @param value
* the value of the property to store
* @since 1.4.2
*/
@SuppressWarnings("unchecked")
public void setPropertyAuto(String key, Object value) {
if (value instanceof String)
setProperty(key, (String) value);
else if (value instanceof List)
setProperty(key, (List<String>) value);
else
throw new IllegalArgumentException("Only a String value or a List of String values may be passed to this method");
}
/**
* Adds in the provided additional properties
*
* @param newprops a {@link com.idfconnect.ssorest.common.utils.ConfigProperties} object.
*/
public void addProperties(ConfigProperties newprops) {
for (Map.Entry<String, Object> entry : newprops.entrySet()) {
setPropertyAuto(entry.getKey(), entry.getValue());
};
}
/**
* Sets a property with the specified key and value. Keys are case-insensitive, so setting a value using a key whose lower-case conversion is equivalent to
* that of a previously used key will overwrite the previous value. Returns the previous value that was overwritten, if any.
*
* @param key
* the key for the property to store
* @param value
* the value of the property to store
* @return the previous value that was overwritten, if any
*/
private Object setPropertyInternal(String key, Object value) {
String keylower = key.toLowerCase();
Object oldkey = keyMap.get(keylower);
// If key, or anything equivalent to it in a case insensitive
// comparison, was previously used, we
// need to remove the old entry first:
if (oldkey != null)
remove(oldkey);
else
remove(keylower);
// If the key is not all lowercase, add a keymap entry for it
// If it is in all lowercase, remove the old mapping if there was one
if (!key.equals(keylower))
keyMap.put(keylower, key);
else
keyMap.remove(keylower);
// Now add the property using its original case
return themap.put(key, value);
}
/**
* Sets a property with the specified key and single value. Keys are case-insensitive, so setting a value using a key whose lower-case conversion is
* equivalent to that of a previously used key will overwrite the previous value. Returns the previous value that was overwritten, if any.
*
* @param key
* the key for the property to store
* @param value
* the value of the property to store
* @return the previous value that was overwritten, if any
* @since 1.4.2
*/
public final Object setProperty(String key, String value) {
return setPropertyInternal(key, value);
}
/**
* Sets a property with the specified key and multiple value. Keys are case-insensitive, so setting a value using a key whose lower-case conversion is
* equivalent to that of a previously used key will overwrite the previous value. Returns the previous value that was overwritten, if any.
*
* @param key
* the key for the property to store
* @param values
* the value of the property to store
* @return the previous value that was overwritten, if any
* @throws java.lang.IllegalArgumentException
* if the list of values contains anything except Strings
* @since 1.4.2
*/
public final Object setProperty(String key, List<String> values) {
if (values != null) {
for (int i = 0; i < values.size(); i++)
if (!(values.get(i) instanceof String))
throw new IllegalArgumentException("Only a List of String objects may be passed to this method");
return setPropertyInternal(key, values);
}
throw new NullPointerException("Null value passed to setProperty");
}
/**
* Sets a property with the specified key and multiple values. This is a convenience method that converts the array into an ArrayList and is otherwise
* identical to setProperty(String, List).
*
* @param key
* the key for the property to store
* @param values
* the value of the property to store
* @return the previous value that was overwritten, if any
* @throws java.lang.IllegalArgumentException
* if the list of values contains anything except Strings'
* @since 1.4.2
*/
public final Object setProperty(String key, Object... values) {
if (values == null)
throw new NullPointerException("Null value passed to setProperty");
ArrayList<String> al = new ArrayList<String>(values.length);
for (int i = 0; i < values.length; i++)
al.add((String) values[i]);
return setProperty(key, al);
}
/**
* Identical to getProperty except this method throws an InvalidParameterException if the requested key is not found and the defaultValue is null.
*
* @param key
* they key for the property to retrieve
* @param defaultValue
* the default value to return if no value is associated with the specified key
* @return the value associated with the specified key
* @throws com.idfconnect.ssorest.common.SSORestException
* if the specified key is not associated with a value and if the specified default value is null
* @since 1.4.2
*/
public String getRequiredPropertyAsString(String key, String defaultValue) throws SSORestException {
String val = getPropertyAsString(key, defaultValue);
if (val == null)
throw new SSORestException("Required parameter missing: " + key);
return val;
}
/**
* Identical to getPropertyAsList except this method throws an InvalidParameterException if the requested key is not found.
*
* @param key
* a case-insensitive key for which to retrieve a property value
* @param defaultValue
* the default value to return if no value is associated with the specified key
* @return the value associated with the specified key converted to a list
* @throws com.idfconnect.ssorest.common.SSORestException
* if the specified key is not associated with a value and if the specified default value is null
* @since 1.4.2
*/
public final List<String> getRequiredPropertyAsList(String key, List<String> defaultValue) throws SSORestException {
List<String> val = getPropertyAsList(key, defaultValue);
if (val == null) {
throw new SSORestException("Required parameter missing: " + key);
} else
return val;
}
/**
* Identical to getPropertyAsList except this method throws an InvalidParameterException if the requested key is not found.
*
* @param key
* a case-insensitive key for which to retrieve a property value
* @return the value associated with the specified key converted to a list
* @throws com.idfconnect.ssorest.common.SSORestException
* if the specified key is not associated with a value
* @since 1.4.2
*/
public final List<String> getRequiredPropertyAsList(String key) throws SSORestException {
return getRequiredPropertyAsList(key, null);
}
/**
* Identical to getPropertyAsString except this method throws an InvalidParameterException if the requested key is not found.
*
* @param key
* a case-insensitive key for which to retrieve a property value
* @return the value associated with the specified key converted to a list
* @throws com.idfconnect.ssorest.common.SSORestException
* if the specified key is not associated with a value
* @since 1.4.2
*/
public String getRequiredPropertyAsString(String key) throws SSORestException {
return getRequiredPropertyAsString(key, null);
}
/**
* Returns the requested property after converting its value to an integer. This method throws an InvalidParameterException if the requested key is not
* found or if its value can not be converted into an integer.
*
* @param key
* a case-insensitive key for which to retrieve a property value
* @return the value associated with the specified key converted to an int
* @throws com.idfconnect.ssorest.common.SSORestException
* if the specified key is not associated with a value
* @since 1.4.2
*/
public int getRequiredPropertyAsInt(String key) throws SSORestException {
String val = getPropertyAsString(key);
if (val != null)
try {
int i = Integer.parseInt(val);
return i;
} catch (NumberFormatException e) {
}
throw new SSORestException("Required integer parameter missing or invalid: " + key);
}
/**
* Returns the requested property after converting its value to a boolean. This method throws an InvalidParameterException if the requested key is not found
* or if its value can not be converted into a boolean.
*
* @param key
* a key which must contain a value which will match a case insensitive comparison to either "true" or "false"
* @return true if the key's value matches "true", false if it matches "false"
* @throws com.idfconnect.ssorest.common.SSORestException
* if the key does not exist or if its value can not be converted into a boolean
* @since 1.4.2
*/
public boolean getRequiredPropertyAsBoolean(String key) throws SSORestException {
String val = getPropertyAsString(key);
if (val != null) {
if (val.toLowerCase().equals(TRUE))
return true;
else if (val.toLowerCase().equals(FALSE))
return false;
}
throw new SSORestException("Required true/false parameter missing or invalid: " + key);
}
/**
* Returns the requested property after converting its value to a long. This method throws an InvalidParameterException if the requested key is not found or
* if its value can not be converted into a long.
*
* @param key
* a case-insensitive key for which to retrieve a property value
* @return the value associated with the specified key converted to a long
* @throws com.idfconnect.ssorest.common.SSORestException
* if the specified key is not associated with a value
* @since 1.4.2
*/
public long getRequiredPropertyAsLong(String key) throws SSORestException {
String val = getPropertyAsString(key);
if (val != null)
try {
long i = Long.parseLong(val);
return i;
} catch (NumberFormatException e) {
}
throw new SSORestException("Required long parameter missing or invalid: " + key);
}
/**
* {@inheritDoc}
*
* Overridden to make sure keys entered with this method end up in lower case.
* @deprecated use the appropriate setPropery() methods instead of this one
*/
@Deprecated
@Override
@SuppressWarnings("unchecked")
public synchronized Object put(String key, Object value) {
if (value instanceof String)
return setProperty(key, (String) value);
if (value instanceof List)
return setProperty(key, (List<String>) value);
throw new IllegalArgumentException("This method must be called with a String key and either a value that is a String or a List containing only Strings");
}
/**
* {@inheritDoc}
*
* Overridden to support case-insensitivity of String keys
*/
@Override
public synchronized Object remove(Object key) {
if (key instanceof String) {
// Get the underlying key used to store this entry
String realKey = getRealKey((String) key);
// Remove the keymap entry
keyMap.remove(((String) key).toLowerCase());
// Now realkey should contain the key that has actually been used to store this property
return themap.remove(realKey);
}
return themap.remove(key);
}
/**
* <p>
* getPropertyAsInt.
* </p>
*
* @param key
* a {@link java.lang.String} object.
* @param defaultValue
* a int.
* @return a int.
* @since 1.4.2
*/
public final int getPropertyAsInt(String key, int defaultValue) {
return StringUtil.parseInt(getPropertyAsString(key), defaultValue);
}
/**
* Convenience method that uses getPropertyAsList to retrieve the specified property, then creates an array of integers by converting the values (the same
* way that getPropertyAsInt does).
*
* @param key
* a case-insensitive key for which to retrieve a property value
* @param defaultValue
* the default value to return if no value is associated with the specified key
* @return the value or values of the specified property converted to an int[]
* @since 1.4.2
*/
public final int[] getPropertyAsIntArray(String key, int defaultValue) {
List<String> l = getPropertyAsList(key);
if (l == null)
return null;
else {
int[] a = new int[l.size()];
for (int i = 0; i < l.size(); i++)
a[i] = StringUtil.parseInt(l.get(i), defaultValue);
return a;
}
}
/**
* Convenience method that gets a value and converts it to a long.
*
* @param key
* a case-insensitive key for which to retrieve a property value
* @param defaultValue
* the default value to use if the specified key is not associated with a value
* @return the value associated with the specified key converted to a long
* @since 1.4.2
*/
public final long getPropertyAsLong(String key, long defaultValue) {
return StringUtil.parseLong(getPropertyAsString(key), defaultValue);
}
/**
* Retrieves the requested value and attempts to convert it into a <code>boolean</code> as follows: the value is compared to <code>trueValue</code> and if
* it matches <code>true</code> is returned; then the value if compared to <code>falseValue</code> and if it matches <code>false</code> is returned;
* otherwise <code>defaultValue</code> is returned. The comparisons are case sensitive only if <code>caseSensitive</code> is true.
*
* @param key
* the key of the property to search for
* @param trueValue
* a non-null String indicating a true value
* @param falseValue
* a non-null String indicating a false value
* @param caseSensitive
* true for case-sensitive comparisons
* @param defaultValue
* the value to return if the key is not found or if the value does not match either value provided
* @return true if the value matches trueValue, false if the value matches falseValue, otherwise defaultValue
* @since 1.4.2
*/
public final boolean getPropertyAsBoolean(String key, String trueValue, String falseValue, boolean caseSensitive, boolean defaultValue) {
String val = getPropertyAsString(key);
if (val == null)
return defaultValue;
else if (caseSensitive) {
if (val.equals(trueValue))
return true;
else if (val.equals(falseValue))
return false;
else
return defaultValue;
} else {
if (val.toLowerCase().equals(trueValue.toLowerCase()))
return true;
else if (val.toLowerCase().equals(falseValue.toLowerCase()))
return false;
else
return defaultValue;
}
}
/**
* Same as <code>getPropertyAsBoolean(key, "true", "false", false, defaultValue)</code> .
*
* @param key
* a case-insensitive key for which to retrieve a property value
* @param defaultValue
* the default value to use if the specified key is not associated with a value
* @return the value associated with the specified key converted to a boolean
* @since 1.4.2
*/
public final boolean getPropertyAsBoolean(String key, boolean defaultValue) {
return getPropertyAsBoolean(key, TRUE, FALSE, false, defaultValue);
}
/**
* Sets a property using the specified key and value. The value is converted into the string "true" or "false".
*
* @param key
* the key to associate a value with
* @param value
* the value to associate with the specified key
* @return the previous value that was overwritten, if any
* @since 1.4.2
*/
public Object setProperty(String key, boolean value) {
return setProperty(key, value ? TRUE : FALSE);
}
/**
* Sets a property using the specified key and value. The value is converted into a string.
*
* @param key
* the key to associate a value with
* @param value
* the value to associate with the specified key
* @return the previous value that was overwritten, if any
* @since 1.4.2
*/
public Object setProperty(String key, int value) {
return setProperty(key, Integer.toString(value));
}
/**
* Sets a property using the specified key and value. The value is converted into a string.
*
* @param key
* the key to associate a value with
* @param value
* the value to associate with the specified key
* @return the previous value that was overwritten, if any
* @since 1.4.2
*/
public Object setProperty(String key, long value) {
return setProperty(key, Long.toString(value));
}
/**
* Gets a single- or multi-valued property and converts it into a single String object. Multi-valued properties are concatenated into a delimited String as
* per the MvaUtil.buildMva(List) method. This is a utility method used by the store() method.
*
* @param key
* the key for which to return a single string value
* @param delimeter
* @return the value of the specified property converted to a single string object
*/
@SuppressWarnings("unchecked")
private String getPropertyAsSingleValueString(String key, String delimeter) {
String realKey = getRealKey(key);
Object val = themap.get(realKey);
if (val == null)
return null;
else if (val instanceof String)
return (String) val;
else if (val instanceof List) {
// Quick hack to make delimited string from list
List<String> values = (List<String>) val;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < values.size(); i++) {
String s = values.get(i);
if (s != null)
sb.append(s);
if (i != values.size() - 1)
sb.append(delimeter);
}
return sb.toString();
} else
// Not a String - can't use this
return null;
}
/**
* Save properties to an OutputStream.
* <p>
* This task is delegated to a Properties instance and the properties are copied over to this object. Multi-valued properties are converted to delimited
* strings.
* </p>
*
* @param out
* a {@link java.io.OutputStream} object.
* @param header
* a {@link java.lang.String} object.
* @throws java.io.IOException
* if any.
* @since 1.4.2
*/
public synchronized void storePropertiesToStream(OutputStream out, String header) throws IOException {
storePropertiesToStream(out, header, delimiter);
}
/**
* Save properties to an OutputStream.
* <p>
* This task is delegated to a Properties instance and the properties are copied over to this object. Multi-valued properties are converted to delimited
* strings.
* </p>
*
* @param out
* a {@link java.io.OutputStream} object.
* @param header
* a {@link java.lang.String} object.
* @param delimeter
* a {@link java.lang.String} object.
* @throws java.io.IOException
* if any.
* @since 1.4.2
*/
public synchronized void storePropertiesToStream(OutputStream out, String header, String delimeter) throws IOException {
// Create a Properties object to delegate to
Properties props = new Properties();
// Copy all of our properties into it
Iterator<String> iter = keySet().iterator();
while (iter.hasNext()) {
String key = iter.next();
String val = getPropertyAsSingleValueString(key, delimeter);
if (prefix != null)
key = prefix + DOT;
if (val != null) {
LoggerFactory.getLogger(getClass()).trace("Storing [key={}][value={}]", key, val);
props.setProperty(key, val);
}
}
// Store 'em
props.store(out, header);
}
/**
* Returns true if the properties set contains a mapping for the specified key. The comparison is case-insensitve. Use this method instead of containsKey to
* avoid false negatives (because containsKey is not case-insensitive). If this object was constructed with another ConfigProperties object to be used for
* defaults, that object will not be consulted when checking for the presence of the specified key. This method will only return true if this object alone
* contains the specified key. This method can therefore be used to determine whether a property value was taken from this object or from the defaults
* object.
*
* @param key
* the key to check for
* @return a boolean.
* @since 1.4.2
*/
public boolean containsPropertyKey(String key) {
return themap.containsKey(getRealKey(key));
}
/**
* Returns a new ConfigProperties object that is a subset of the current instance. The new object will contain all of the keys that start with
* <code><tag> + "."</code>.
*
* @param tag
* a {@link java.lang.String} object.
* @return a {@link com.idfconnect.ssorest.common.utils.ConfigProperties} object.
* @since 1.4.2
*/
public ConfigProperties getSubProperties(final String tag) {
if (tag == null)
return null;
String usetag = tag.toLowerCase() + DOT;
ConfigProperties sub = new ConfigProperties();
Enumeration<String> en = themap.keys();
while (en.hasMoreElements()) {
String nextkeyraw = en.nextElement();
String nextkey = nextkeyraw.toLowerCase();
if (nextkey.startsWith(usetag)) {
String newkey = nextkeyraw.substring(usetag.length());
sub.setPropertyInternal(newkey, this.getProperty(nextkeyraw));
}
}
return sub;
}
/** {@inheritDoc} */
@Override
public int size() {
return themap.size();
}
/** {@inheritDoc} */
@Override
public boolean isEmpty() {
return themap.isEmpty();
}
/** {@inheritDoc} */
@Override
@Deprecated
public boolean containsKey(Object key) {
return themap.containsKey(key);
}
/** {@inheritDoc} */
@Override
public boolean containsValue(Object value) {
return themap.containsValue(value);
}
/** {@inheritDoc} */
@Override
@Deprecated
public Object get(Object key) {
return themap.get(key);
}
/** {@inheritDoc} */
@Override
@Deprecated
public void putAll(Map<? extends String, ? extends Object> m) {
for (Entry<? extends String, ? extends Object> e : m.entrySet()) {
put(e.getKey(), e.getValue());
}
}
/** {@inheritDoc} */
@Override
public void clear() {
themap.clear();
keyMap.clear();
}
/** {@inheritDoc} */
@Override
public Set<String> keySet() {
return themap.keySet();
}
/** {@inheritDoc} */
@Override
public Collection<Object> values() {
return themap.values();
}
/** {@inheritDoc} */
@Override
public Set<java.util.Map.Entry<String, Object>> entrySet() {
return themap.entrySet();
}
/** {@inheritDoc} */
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ConfigProperties [");
builder.append(themap);
builder.append("]");
return builder.toString();
}
}
| true |
375e5ec4544b87f8a47cb0908a02a05d78d60902
|
Java
|
msmacorin/jump
|
/admin/src/main/java/br/com/jump/admin/service/iface/IUsuarioService.java
|
UTF-8
| 318 | 1.789063 | 2 |
[] |
no_license
|
package br.com.jump.admin.service.iface;
import br.com.jump.model.admin.Usuario;
import br.com.jump.core.service.iface.IGenericService;
public interface IUsuarioService extends IGenericService<Usuario, Long> {
public Usuario buscarPorEmail(String email);
public Usuario buscarPorUsuario(String usuario);
}
| true |
b1d1ea4fa9b89417ef45b9de50783e70d127610e
|
Java
|
EdGruberman/MessageManager
|
/src/edgruberman/bukkit/messagemanager/commands/TimestampFormat.java
|
UTF-8
| 679 | 2.515625 | 3 |
[] |
no_license
|
package edgruberman.bukkit.messagemanager.commands;
import edgruberman.bukkit.messagemanager.commands.util.Action;
import edgruberman.bukkit.messagemanager.commands.util.Context;
import edgruberman.bukkit.messagemanager.commands.util.Handler;
class TimestampFormat extends Action {
TimestampFormat(final Handler handler) {
super(handler, "format");
new TimestampFormatGet(this);
new TimestampFormatSet(this);
}
@Override
public boolean perform(final Context context) {
// Example: /<command> format([ get][ <Player>]| set[ <Player>] <Format>)
return this.children.get(0).perform(context);
}
}
| true |
fabd7f3fb716c5addcff7585f566d9abd6426b4f
|
Java
|
xuehairui/flowable-ui-example
|
/src/main/java/com/promote/app/config/MyBatisPlusConfig.java
|
UTF-8
| 1,044 | 1.953125 | 2 |
[] |
no_license
|
package com.promote.app.config;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
*
* mybatisplusconfig
* @author xue.hairui
*
*/
@Configuration
public class MyBatisPlusConfig {
/**
* mybaitsplus自带分页生效
* @return
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
/**
* 使得pagerhelper生效
* @return
*/
@Bean
ConfigurationCustomizer mybatisConfigurationCustomizer() {
return new ConfigurationCustomizer() {
@Override
public void customize(MybatisConfiguration configuration) {
configuration.addInterceptor(new com.github.pagehelper.PageInterceptor());
}
};
}
}
| true |
4174e3d9a365f7686d6ae43e8b5c8cdd52fe8f07
|
Java
|
yuhongwen-coder/pad_2.4
|
/app/src/main/java/com/maxvision/tech/robot/utils/ImageEngineUtils.java
|
UTF-8
| 6,520 | 2.40625 | 2 |
[] |
no_license
|
package com.maxvision.tech.robot.utils;
import android.content.Context;
import android.text.TextUtils;
import android.util.Base64;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.maxvision.tech.robot.R;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import top.zibin.luban.Luban;
/**
* Created by yuhongwen
* on 2021/4/7
* 图片加载框架
*/
public class ImageEngineUtils {
private ImageEngineUtils() {
}
private static ImageEngineUtils instance;
public static ImageEngineUtils createImageEngine() {
if (null == instance) {
synchronized (ImageEngineUtils.class) {
if (null == instance) {
instance = new ImageEngineUtils();
}
}
}
return instance;
}
/**
* 加载人脸上传本地图片
* @param context 上下文
* @param url 图片地址
* @param imageView 图片控件
*/
public void loadLocalImage(@NonNull Context context, String url, ImageView imageView){
Glide.with(context)
.load(url)
.apply(new RequestOptions()
.bitmapTransform(new RoundedCorners(10))
.diskCacheStrategy(DiskCacheStrategy.NONE))
.into(imageView);
}
/**
* 将图片转换成Base64编码的字符串
*/
public String imageToBase64Sync(String srcPath,Context context){
if(TextUtils.isEmpty(srcPath)){
return null;
}
// 将图片原样压缩
if (!TextUtils.isEmpty(getPicture(srcPath))) {
compressImageForSync(context, srcPath, srcPath);
return imageToBase64ForCompress(srcPath);
}
return imageToBase64ForCompress(srcPath);
}
/**
* 同步压缩图片
* @param appContext
* @param srcPath
* @param destImage
* @return
*/
public static List<File> compressImageForSync(Context appContext, String srcPath, String destImage) {
String reFileName = "";
if (!TextUtils.isEmpty(srcPath)) {
String[] imagePaths = srcPath.split(destImage);
if (imagePaths != null && imagePaths.length >= 2) {
reFileName = imagePaths[1];
if (reFileName.startsWith("/")) {
// 删掉 "/"
reFileName = reFileName.substring(1);
}
}
}
final String finalReFileName = reFileName;
try {
return Luban.with(appContext)
.load(srcPath)
.ignoreBy(100)
.setRenameListener(filePath -> finalReFileName)
.setTargetDir(destImage)
.filter(path -> !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"))).get();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static String imageToBase64ForCompress(String srcPath) {
InputStream is = null;
byte[] data = null;
String result = null;
try{
is = new FileInputStream(srcPath);
//创建一个字符流大小的数组。
data = new byte[is.available()];
//写入数组
is.read(data);
//用默认的编码格式进行编码
result = Base64.encodeToString(data, Base64.NO_CLOSE);
}catch (Exception e){
e.printStackTrace();
}finally {
if(null !=is){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
// 现有的算法只能压缩图片
private static String getPicture(String strPath) {
File file = new File(strPath);
if (file.isFile()) {
int idx = file.getPath().lastIndexOf(".");
if (idx <= 0) {
return "";
}
String suffix = file.getPath().substring(idx);
if (suffix.toLowerCase().equals(".jpg") ||
suffix.toLowerCase().equals(".jpeg") ||
suffix.toLowerCase().equals(".bmp") ||
suffix.toLowerCase().equals(".png") ||
suffix.toLowerCase().equals(".gif")) {
return file.getPath();
}
}
return "";
}
public void loadImage(Context context,String imagePath,ImageView iv) {
Glide.with(context)
.load(imagePath)
.apply(new RequestOptions()
.placeholder(R.mipmap.default_image)
.diskCacheStrategy(DiskCacheStrategy.NONE))
.into(iv);
}
public boolean decodeImage(String sourceImagePic,String filePath) {
if (sourceImagePic == null) {
return false;
}
FileOutputStream outputStream = null;
BufferedOutputStream bufferedOutputStream = null;
try {
byte[] decodeByte = Base64.decode(sourceImagePic,Base64.NO_CLOSE);
File photoFile = new File(filePath);
photoFile.createNewFile();
outputStream = new FileOutputStream(photoFile);
bufferedOutputStream = new BufferedOutputStream(outputStream);
bufferedOutputStream.write(decodeByte);
bufferedOutputStream.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
}finally {
// 关闭创建的流对象
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bufferedOutputStream != null) {
try {
bufferedOutputStream.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
return false;
}
}
| true |
1aed8267b93fce0149da47c16bc3dbf7e3bd8964
|
Java
|
elhamidi/Aidoo
|
/AidooProject/src/main/java/be/bt/entities/Comment.java
|
UTF-8
| 1,716 | 2.28125 | 2 |
[] |
no_license
|
package be.bt.entities;
import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;
/**
* The persistent class for the comment database table.
*
*/
@Entity
@NamedQuery(name="Comment.findAll", query="SELECT c FROM Comment c")
public class Comment implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private int id;
@Column(name="comment_cotation")
private int commentCotation;
private String content;
@Temporal(TemporalType.DATE)
@Column(name="date_created")
private Date dateCreated;
//bi-directional many-to-one association to Person
@ManyToOne
@JoinColumn(name="commentator_id")
private Person person1;
//bi-directional many-to-one association to Person
@ManyToOne
@JoinColumn(name="commented_id")
private Person person2;
public Comment() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public int getCommentCotation() {
return this.commentCotation;
}
public void setCommentCotation(int commentCotation) {
this.commentCotation = commentCotation;
}
public String getContent() {
return this.content;
}
public void setContent(String content) {
this.content = content;
}
public Date getDateCreated() {
return this.dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public Person getPerson1() {
return this.person1;
}
public void setPerson1(Person person1) {
this.person1 = person1;
}
public Person getPerson2() {
return this.person2;
}
public void setPerson2(Person person2) {
this.person2 = person2;
}
}
| true |
a549ee9815a62d51bed0bb82623be9644f2f1e4b
|
Java
|
Clark-caipeiyuan/sampleSDK
|
/XiXiSdk/src/main/java/com/xixi/sdk/serialpos/SerialPosClient.java
|
UTF-8
| 5,084 | 2.046875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.xixi.sdk.serialpos;
import java.util.Map;
import java.util.TreeMap;
import com.xixi.sdk.CustomizedCRCConverter;
import com.xixi.sdk.LLSDKUtils;
import com.xixi.sdk.android_serialport_api.device.service.LongLakeDataPumpService;
import com.xixi.sdk.app.LongLakeApplication;
import com.xixi.sdk.logger.Log;
import com.xixi.sdk.utils.file.IoCompletionListener1;
import com.xixi.sdk.utils.file.IoCompletionListener3;
import com.xixi.sdk.utils.thread.UIThreadDispatcher;
import android.content.Context;
public class SerialPosClient implements ISerialDataEnum, IoCompletionListener1<SerialPosEvent> {
private static SerialPosClient instance;
private LongLakeDataPumpService mService = null;
private SerialPosClient(LongLakeDataPumpService service) {
Log.i(LongLakeApplication.DANIEL_TAG, "Get Serials Port Client!");
mService = service;
service.registerAsObserver(this, true);
openSerialPort();
}
public static synchronized SerialPosClient getInstance(LongLakeDataPumpService service) {
if (instance == null) {
instance = new SerialPosClient(service);
}
return instance;
}
public static final SerialPosClient instance() {
if (instance != null)
return instance;
throw new RuntimeException("Serial Port Client not instantiated yet");
}
private final Map<Byte, IoCompletionListener3<byte[]>> callbackMap = new TreeMap<Byte, IoCompletionListener3<byte[]>>();
public void sendDataViaCom(final boolean enablefloor, final byte[] requestedData,
final IoCompletionListener1<byte[]> io) {
if (requestedData[2] == (byte) 20) {
io.onFinish(requestedData, Boolean.valueOf(true));
} else if (requestedData[2] == (byte) 21) {
io.onFinish(requestedData, Boolean.valueOf(true));
}
}
private int counter = 0;
public boolean testSendDataViaCom(final byte[] requestedData, final IoCompletionListener1<byte[]> io) {
counter++;
if ( counter <= 1 ) {
sendDataViaCom(requestedData, io);
} else {
io.onFinish(requestedData, Boolean.valueOf(false));
}
return true;
}
public boolean sendDataViaCom(final byte[] requestedData, final IoCompletionListener1<byte[]> io) {
try {
requestedData[LENGTH_KEY_OFFSET] = (byte) (requestedData.length + 2); // 2
// for
// crc
int cmd = requestedData[CMD_KEY_OFFSET];
int c = CustomizedCRCConverter.createCRC(requestedData);
final byte[] openBJ = new byte[requestedData.length + 2];
System.arraycopy(requestedData, 0, openBJ, 0, requestedData.length);
openBJ[requestedData.length] = (byte) (c & 0xFF);
openBJ[requestedData.length + 1] = (byte) (c >> 8);
Log.d(LongLakeApplication.DANIEL_TAG, "SB" + CustomizedCRCConverter.bytesToHexString(openBJ));
if (io != null) {
final Byte bb = Byte.valueOf((byte) cmd);
IoCompletionListener3<byte[]> io1 = null;
synchronized (callbackMap) {
io1 = callbackMap.remove(bb);
}
if (io1 != null) {
LLSDKUtils.danielAssert(false);
UIThreadDispatcher.removeCallbacks(io1);
io1.run();
}
io1 = new IoCompletionListener3<byte[]>() {
@Override
public void run() {
synchronized (callbackMap) {
callbackMap.remove(bb);
}
onFinish(requestedData, CmdErrorCode.valueOf(CMD_EXECUTE_TIMEOUT));
}
@Override
public void onFinish(byte[] data, Object context) {
io.onFinish(data == null ? requestedData : data, context);
}
};
synchronized (callbackMap) {
callbackMap.put(bb, io1);
}
UIThreadDispatcher.dispatch(io1, 3000);
}
mService.writeDataViaSerialPort(openBJ);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public boolean sendDataViaCom(byte[] requestedData) {
return sendDataViaCom(requestedData, null);
}
public void connect(Context ctx, Class<? extends LongLakeDataPumpService> class1) {
mOnEventListener.onConnected(this);
}
public void disconnect() {
mOnEventListener.onDisconnected(this);
}
private void openSerialPort() {
if (mService != null) {
mService.openSerialPort(SERIAL_PORT_ADDR, SERIAL_PORT_BAUDRATE);
Log.i(LongLakeApplication.DANIEL_TAG, "Serials Port opened!");
}
}
public void closeSerialPort() {
if (mService != null) {
mService.closeSerialPort();
}
}
protected OnEventListener mOnEventListener = null;
public interface OnEventListener {
public void onConnected(SerialPosClient c);
public void onDisconnected(SerialPosClient c);
}
public void setOnEventListener(OnEventListener l) {
mOnEventListener = l;
}
private final IoCompletionListener1<Byte> callback_io = new IoCompletionListener1<Byte>() {
@Override
public void onFinish(Byte data, Object context) {
IoCompletionListener3<byte[]> io = null;
synchronized (callbackMap) {
io = callbackMap.remove(data);
}
if (io != null) {
UIThreadDispatcher.removeCallbacks(io);
io.onFinish(null, context);
}
}
};
@Override
public void onFinish(SerialPosEvent event, Object context) {
SerialDataParser.preprocess(event.data, callback_io);
}
}
| true |
4ebaf050f410cfc138ab16b9477f9a3b26c0a882
|
Java
|
raidcraft/rcgroups
|
/src/main/java/de/raidcraft/rcgroups/exception/GroupPlayerNotLeaderException.java
|
UTF-8
| 387 | 2.046875 | 2 |
[] |
no_license
|
package de.raidcraft.rcgroups.exception;
/**
*
*/
public class GroupPlayerNotLeaderException extends GroupException {
private static final long serialVersionUID = 7307013697144637838L;
public GroupPlayerNotLeaderException() {
super("Player not group leader");
}
public GroupPlayerNotLeaderException(final String message) {
super(message);
}
}
| true |
630c622c32c8d4f275af55613bcd7d90b69b8750
|
Java
|
gajendrahedau/payrollJPA
|
/CGPayrollSystemJPAHibernate/src/com/cg/project/services/PayrollServices.java
|
UTF-8
| 568 | 2.03125 | 2 |
[] |
no_license
|
package com.cg.project.services;
import java.util.ArrayList;
import com.cg.project.beans.Associate;
public interface PayrollServices {
int acceptAssociateDetails(int yearlyInvestmentUnder80C,String firstName,String lastName,
String department,String designation,String panCard ,String emailId,
int basicSalary, int epf, int companyPf,
int accountNumber,
String bankName, String ifscCode);
int calculateNetSalary(int associateId);
Associate getAssociateDetails(int associateId);
ArrayList<Associate> getAllAssociateDetails();
}
| true |
93a29b342328e830882684cb1463d2138f2e4ae7
|
Java
|
chaug2018/web
|
/com.yzj.ebs.report/src/com/yzj/ebs/report/biz/impl/FocusReportBizImpl.java
|
UTF-8
| 10,516 | 1.914063 | 2 |
[] |
no_license
|
package com.yzj.ebs.report.biz.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.yzj.ebs.common.IBasicInfoAdm;
import com.yzj.ebs.common.ICheckMainDataAdm;
import com.yzj.ebs.common.XDocProcException;
import com.yzj.ebs.common.param.PageParam;
import com.yzj.ebs.report.biz.IFocusReportBiz;
import com.yzj.ebs.report.pojo.FocusResult;
import com.yzj.ebs.util.FinalConstant;
import com.yzj.wf.common.WFLogger;
/**
* 创建于:2013-04-01<br>
* 版权所有(C) 2012 深圳市银之杰科技股份有限公司<br>
* 对账集中情况统计 业务实现
*
* @author 单伟龙
* @version 1.0.0
*/
public class FocusReportBizImpl implements IFocusReportBiz{
private static final java.text.DecimalFormat df = new java.text.DecimalFormat("#.##");
private FocusResult result; // 统计结果类
private List<FocusResult> resultList = new ArrayList<FocusResult>(); // 统计结果类集合,为了前台显示方便
private IBasicInfoAdm basicinfoAdm;
private static WFLogger logger = WFLogger.getLogger(FocusReportBizImpl.class);
public List<FocusResult> getFocusReportList(
Map<String, String> queryMap, PageParam queryParam,
boolean isPaged,String selectCount) {
result = null;
resultList.clear();
try {
List<?> idBranchNameList = null;
Map<String,String> idBranchNameMap = new HashMap<String,String>();
//获得所有清算中心的名字
idBranchNameList = basicinfoAdm.getAllIdBranchName();
for (int i = 0; i < idBranchNameList.size(); i++) {
String idBranch = "";
String idBranchName = "";
Object[] obj = (Object[]) idBranchNameList.get(i);
for (int j = 0; j < obj.length; j++) {
switch (j) {
case 0:
if (obj[j] != null
&& obj[j].toString().trim().length() > 0) {
idBranch = obj[j].toString();
}
break;
case 1:
if (obj[j] != null
&& obj[j].toString().trim().length() > 0) {
idBranchName = obj[j].toString();
idBranchName = idBranchName.replace("清算中心", "");
}
break;
}
}
idBranchNameMap.put(idBranch, idBranchName);
}
List<?> list = basicinfoAdm.getFocusReportList(queryMap,
queryParam,isPaged,selectCount);
if(selectCount!=null && selectCount.equals("countIdBank")){
if (list != null && list.size() > 0) {
String idCenter = "";
String idBank = ""; // 机构号
String bankName = ""; // 机构名称
long mailCount = 0; //邮寄对账账户数
long netCount = 0; //网银对账账户数
long faceCount = 0; //面对面对账账户数
long counterCount = 0; //柜台对账账户数
long otherCount = 0; //其它对账账户数
long checkCount = 0; //需对账账户数
String focusPercent = ""; //集中度
for (int i = 0; i < list.size(); i++) {
Object[] obj = (Object[]) list.get(i);
for (int j = 0; j < obj.length; j++) {
switch (j) {
case 0:
if (obj[j] != null
&& obj[j].toString().trim().length() > 0) {
idCenter = obj[j].toString();
}
break;
case 1:
if (obj[j] != null
&& obj[j].toString().trim().length() > 0) {
idBank = obj[j].toString();
}
break;
case 2:
if (obj[j] != null
&& obj[j].toString().trim().length() > 0) {
bankName = obj[j].toString();
}
break;
case 3:
if (obj[j] != null
&& obj[j].toString().trim().length() > 0) {
mailCount = Long.parseLong(obj[j].toString());
}
break;
case 4:
if (obj[j] != null
&& obj[j].toString().trim().length() > 0) {
netCount = Long.parseLong(obj[j].toString());
}
break;
case 5:
if (obj[j] != null
&& obj[j].toString().trim().length() > 0) {
faceCount = Long.parseLong(obj[j].toString());
}
break;
case 6:
if (obj[j] != null
&& obj[j].toString().trim().length() > 0) {
counterCount = Long.parseLong(obj[j].toString());
}
break;
case 7:
if (obj[j] != null
&& obj[j].toString().trim().length() > 0) {
otherCount = Long.parseLong(obj[j].toString());
}
break;
case 8:
if (obj[j] != null
&& obj[j].toString().trim().length() > 0) {
checkCount = Long.parseLong(obj[j].toString());
}
break;
}
}
float focusPercentTmp = 0;
if (checkCount == 0) {
} else {
focusPercentTmp = (float) (mailCount+netCount+faceCount) / (float) checkCount * 100;
}
focusPercent = df.format(focusPercentTmp) + "%";
result = new FocusResult(idCenter, idBank, bankName,
mailCount, netCount, faceCount, counterCount,
otherCount, checkCount, focusPercent);
resultList.add(result);
}
}
}
if(selectCount!=null && selectCount.equals("countIdCenter")){
if (list != null && list.size() > 0) {
String idCenter = "";
String idBank = ""; // 机构号
String bankName = ""; // 机构名称
long mailCount = 0; //邮寄对账账户数
long netCount = 0; //网银对账账户数
long faceCount = 0; //面对面对账账户数
long counterCount = 0; //柜台对账账户数
long otherCount = 0; //其它对账账户数
long checkCount = 0; //需对账账户数
String focusPercent = ""; //集中度
for (int i = 0; i < list.size(); i++) {
Object[] obj = (Object[]) list.get(i);
for (int j = 0; j < obj.length; j++) {
switch (j) {
case 0:
if (obj[j] != null
&& obj[j].toString().trim().length() > 0) {
idCenter = obj[j].toString();
}
break;
case 1:
if (obj[j] != null
&& obj[j].toString().trim().length() > 0) {
mailCount = Long.parseLong(obj[j].toString());
}
break;
case 2:
if (obj[j] != null
&& obj[j].toString().trim().length() > 0) {
netCount = Long.parseLong(obj[j].toString());
}
break;
case 3:
if (obj[j] != null
&& obj[j].toString().trim().length() > 0) {
faceCount = Long.parseLong(obj[j].toString());
}
break;
case 4:
if (obj[j] != null
&& obj[j].toString().trim().length() > 0) {
counterCount = Long.parseLong(obj[j].toString());
}
break;
case 5:
if (obj[j] != null
&& obj[j].toString().trim().length() > 0) {
otherCount = Long.parseLong(obj[j].toString());
}
break;
case 6:
if (obj[j] != null
&& obj[j].toString().trim().length() > 0) {
checkCount = Long.parseLong(obj[j].toString());
}
break;
}
}
idBank = idCenter;
bankName = idBranchNameMap.get(idCenter);
float focusPercentTmp = 0;
if (checkCount == 0) {
} else {
focusPercentTmp = (float) (mailCount+netCount+faceCount) / (float) checkCount * 100;
}
focusPercent = df.format(focusPercentTmp) + "%";
result = new FocusResult(idCenter, idBank, bankName,
mailCount, netCount, faceCount, counterCount,
otherCount, checkCount, focusPercent);
resultList.add(result);
}
}
}
if(selectCount!=null && selectCount.equals("countIdBranch")){
if (list != null && list.size() > 0) {
String idCenter = FinalConstant.ROOTORG;
String idBank = FinalConstant.ROOTORG; // 机构号
String bankName = "华融湘江总行"; // 机构名称
long mailCount = 0; //邮寄对账账户数
long netCount = 0; //网银对账账户数
long faceCount = 0; //面对面对账账户数
long counterCount = 0; //柜台对账账户数
long otherCount = 0; //其它对账账户数
long checkCount = 0; //需对账账户数
String focusPercent = ""; //集中度
for (int i = 0; i < list.size(); i++) {
Object[] obj = (Object[]) list.get(i);
for (int j = 0; j < obj.length; j++) {
switch (j) {
case 0:
if (obj[j] != null
&& obj[j].toString().trim().length() > 0) {
mailCount = Long.parseLong(obj[j].toString());
}
break;
case 1:
if (obj[j] != null
&& obj[j].toString().trim().length() > 0) {
netCount = Long.parseLong(obj[j].toString());
}
break;
case 2:
if (obj[j] != null
&& obj[j].toString().trim().length() > 0) {
faceCount = Long.parseLong(obj[j].toString());
}
break;
case 3:
if (obj[j] != null
&& obj[j].toString().trim().length() > 0) {
counterCount = Long.parseLong(obj[j].toString());
}
break;
case 4:
if (obj[j] != null
&& obj[j].toString().trim().length() > 0) {
otherCount = Long.parseLong(obj[j].toString());
}
break;
case 5:
if (obj[j] != null
&& obj[j].toString().trim().length() > 0) {
checkCount = Long.parseLong(obj[j].toString());
}
break;
}
}
float focusPercentTmp = 0;
if (checkCount == 0) {
} else {
focusPercentTmp = (float) (mailCount+netCount+faceCount) / (float) checkCount * 100;
}
focusPercent = df.format(focusPercentTmp) + "%";
result = new FocusResult(idCenter, idBank, bankName,
mailCount, netCount, faceCount, counterCount,
otherCount, checkCount, focusPercent);
resultList.add(result);
}
}
}
} catch (XDocProcException e) {
logger.error("对账率统计查询数据库错误", e);
return null;
}
return resultList;
}
public FocusResult getResult() {
return result;
}
public void setResult(FocusResult result) {
this.result = result;
}
public List<FocusResult> getResultList() {
return resultList;
}
public void setResultList(List<FocusResult> resultList) {
this.resultList = resultList;
}
public IBasicInfoAdm getBasicinfoAdm() {
return basicinfoAdm;
}
public void setBasicinfoAdm(IBasicInfoAdm basicinfoAdm) {
this.basicinfoAdm = basicinfoAdm;
}
public static java.text.DecimalFormat getDf() {
return df;
}
}
| true |
0fa004fab544d888ee6c37a25790976ffd035ce9
|
Java
|
t-paudel/JettyServer
|
/src/main/java/com/demo/jettyServerPOC/jettyUtils/Handler.java
|
UTF-8
| 1,070 | 2.546875 | 3 |
[] |
no_license
|
package com.demo.jettyServerPOC.jettyUtils;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
public class Handler extends AbstractHandler{
final String assetName;
final int portNumber;
final String url;
public Handler(String assetName, int portNumber, String url) {
super();
this.assetName = assetName;
this.portNumber = portNumber;
this.url = url;
}
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html; charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
out.println("<h3>" + assetName + " : " + portNumber + "</h3>");
out.println("<br>route : " + url);
baseRequest.setHandled(true);
}
}
| true |
e4bd6acef87ec685e374001933a039fae75f280c
|
Java
|
alejandroSagrera/someAlgorithms
|
/Algorithms/src/javaAlgorithms/GrafoL.java
|
UTF-8
| 8,787 | 3.015625 | 3 |
[] |
no_license
|
/*
* 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 javaAlgorithms;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
import javaAlgorithms.HashObjeto.TipoPunto;
public class GrafoL {
private int size;
private int largoV;
private int tope;
private ListaAdy[] listaAdyacencia;
private boolean[] nodosUsados;
public GrafoL(int n, int cant) {
this.size = 0;
this.largoV = n;
this.tope = cant;
this.listaAdyacencia = new ListaAdy[this.largoV];
for (int i = 0; i <= this.largoV - 1; i++) {
this.listaAdyacencia[i] = new ListaAdy();
}
this.nodosUsados = new boolean[this.largoV];
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public int getLargoV() {
return largoV;
}
public void setLargoV(int largoV) {
this.largoV = largoV;
}
public int getTope() {
return tope;
}
public void setTope(int tope) {
this.tope = tope;
}
public ListaAdy[] getListaAdyacencia() {
return listaAdyacencia;
}
public void setListaAdyacencia(ListaAdy[] listaAdyacencia) {
this.listaAdyacencia = listaAdyacencia;
}
public boolean[] getNodosUsados() {
return nodosUsados;
}
public void setNodosUsados(boolean[] nodosUsados) {
this.nodosUsados = nodosUsados;
}
public boolean agregarArista(int origen, int destino, int peso) {
this.listaAdyacencia[origen].agregarOrd(destino, peso);
return true;
}
public void agregarVertice(int v) {
this.nodosUsados[v] = true;
this.size++;
}
public void eliminarArista(int origen, int destino) {
this.listaAdyacencia[origen].eliminar(destino);
}
public boolean esVacio() {
return this.size == 0;
}
public boolean sonAdyacentes(int a, int b) {
NodoListaAdy l = this.listaAdyacencia[a].inicio;
return this.listaAdyacencia[a].pertenece(l, b);
}
public void eliminarVertice(int v) {
this.nodosUsados[v] = false;
this.size--;
//Elimino las aristas donde v es miembro
this.listaAdyacencia[v] = new ListaAdy();
//BUSCAR EN TODOS LOS VERTICES LA ARISTA
for (int i = 1; i <= largoV; i++) {
this.listaAdyacencia[i].eliminar(v);
}
}
public ListaAdy verticesAdyacentes(int v) {
return this.listaAdyacencia[v];
}
public boolean estaVertice(int v) {
return this.nodosUsados[v];
}
public Lista BFS(int nodoI) {
Queue<Integer> q = new LinkedList<>();
Lista l = new Lista();
boolean[] visitados = new boolean[size];
visitados[nodoI] = true;
l.agregarFinal(nodoI);
q.add(nodoI);
while (!q.isEmpty()) {
int x = q.remove();
for (int i = 0; i < this.largoV; i++) {
if (this.sonAdyacentes(x, i) && !visitados[i]) {
q.add(i);
l.agregarFinal(BFS(i));
visitados[i] = true;
}
}
}
return l;
}
public Lista DFS(int nodoI) {
Lista l = new Lista();
Stack p = new Stack();
boolean[] visitados = new boolean[size];
visitados[nodoI] = true;
p.push(nodoI);
l.agregarFinal(nodoI);
while (!p.isEmpty()) {
int x = (int) p.pop();
int siguienteNodo = obtengoNodosAdyacentesNoVisitados(visitados, x);
if (siguienteNodo == -1) {
p.pop();
} else {
visitados[siguienteNodo] = true;
p.push(siguienteNodo);
l.agregarFinal(siguienteNodo);
}
}
return l;
}
private int obtengoNodosAdyacentesNoVisitados(boolean[] visitados, int x) {
for (int j = 0; j < this.largoV; j++) {
if (this.sonAdyacentes(x, j) && !visitados[j]) {
return j;
}
}
return -1;
}
public String buscoRutaCp(int o, Hash h) {
boolean[] visitados = new boolean[this.getLargoV()];
int IndiceMin = 0;
String salida = "";
int[] dist = new int[this.largoV];
int[] ant = new int[this.getLargoV()];
int[] losQueSirven = new int[this.getLargoV()];
caminoMinimo(o, visitados, dist, ant);
HashObjeto elTampo = h.getV()[o];
for (int i = 0; i < dist.length; i++) {
if (dist[i] != Integer.MAX_VALUE) {
if (h.getV()[i].getCapacidad() >= elTampo.getCapacidad() /*&& h.getV()[i].getTipOb().equals(TipoPunto.CENTRO_PASTEURIZADO)*/) {
losQueSirven[i] = dist[i];
}
}
}
salida += elTampo.getCoordX() + ";" + elTampo.getCoordY() + "|";
for (int k = 0; k < losQueSirven.length; k++) {
IndiceMin = k;
int j = k;
while (j <= losQueSirven.length - 1) {
if (j != o && losQueSirven[j] != 0) {
if (dist[j] < dist[IndiceMin]) {
IndiceMin = j;
}
}
j++;
}
if (ant[IndiceMin] != 0 && !this.sonAdyacentes(o, IndiceMin)) {
salida += (" " + h.getV()[ant[IndiceMin]].getCoordX() + ";" + h.getV()[ant[IndiceMin]].getCoordY());
salida += ("|");
}
int anterior = h.getV()[ant[IndiceMin]].getIndice();
if (ant[anterior] != 0) {
salida += h.getV()[anterior].getCoordX() + ";" + h.getV()[anterior].getCoordX() + "|";
} else {
k = losQueSirven.length;
}
}
salida += (" " + h.getV()[IndiceMin].getCoordX() + ";" + h.getV()[IndiceMin].getCoordY());
h.getV()[IndiceMin].setCapacidadRemanenete(h.getV()[IndiceMin].getCapacidad()-elTampo.getCapacidad());
return salida;
}
private void caminoMinimo(int o, boolean[] visitados, int[] dist, int[] ant) {
int inf = Integer.MAX_VALUE;
int candidato = 0;
visitados[o] = true;
dist[o] = 0;
for (int j = 0; j < dist.length; j++) {
if (o != j && this.sonAdyacentes(o, j)) {
dist[j] = this.listaAdyacencia[o].obtengoPeso(j);
ant[j] = o;
} else {
dist[j] = inf;
}
}
for (int k = 0; k < this.largoV - 2; k++) {
boolean sirve = false;
for (int l = 0; l < this.largoV; l++) {
if (!visitados[l] && !sirve || dist[candidato] > dist[l]) {
candidato = l;
sirve = true;
}
}
}
visitados[candidato] = true;
for (int m = 0; m < this.largoV; m++) {
if (m != o) {
if (this.sonAdyacentes(candidato, m)
&& dist[candidato] + this.listaAdyacencia[candidato].obtengoPeso(m) < dist[m]) {
dist[m] = dist[candidato] + this.listaAdyacencia[candidato].obtengoPeso(m);
ant[m] = candidato;
}
}
}
}
public String tambosEnCiudad(int o, int m, Hash h) {
boolean[] visitados = new boolean[this.largoV];
int[] dist = new int[this.largoV];
int[] ant = new int[this.largoV];
String salida = "";
caminoMinimo(o, visitados, dist, ant);
HashObjeto elTampo = h.getV()[o];
for (int i = 0; i < dist.length; i++) {
if (dist[i] <= 20) {
if (ant[i] != 0) {
salida += (" " + h.getV()[ant[i]].getCoordX() + ";" + h.getV()[ant[i]].getCoordY());
}
salida += ("|");
salida += (" " + h.getV()[i].getCoordX() + ";" + h.getV()[i].getCoordY());
}
}
return salida;
}
public Lista devuelvoPuntos(Hash h){
Lista ret = new Lista();
int largo = h.getV().length-1;
for(int i=0;i<largo;i++){
if(h.getV()!=null){
ret.agregarFinal(h.getV()[i]);
}
}
return ret;
}
}
| true |
c32a7bf7975bd5b38cae156bf540c5de1b1f1c90
|
Java
|
iamamir/UCLAFeeds
|
/Server_End/150415 - Buzz-Server/Buzz-Server/app/dao/common/NonShardedDao.java
|
UTF-8
| 1,620 | 2.390625 | 2 |
[] |
no_license
|
package dao.common;
import javax.persistence.Query;
import models.db.common.DbEntity;
import dao.shard.ShardManager.AccessMode;
public class NonShardedDao extends GenericDao {
private final static String defaultDS_RW = "default";
private final static String defaultDS_RO = "default_ro";
public static Query createNamedQuery(String name) {
return NonShardedDao.createNamedQuery(name, AccessMode.READ_ONLY);
}
public static Query createNamedQuery(String name, AccessMode accessMode) {
if (accessMode == AccessMode.READ_ONLY) {
return GenericDao.createNamedQuery(name, NonShardedDao.defaultDS_RO);
}
else {
return GenericDao.createNamedQuery(name, NonShardedDao.defaultDS_RW);
}
}
public static Query createNativeQuery(String name) {
return NonShardedDao.createNativeQuery(name, AccessMode.READ_ONLY);
}
public static Query createNativeQuery(String name, AccessMode accessMode) {
if (accessMode == AccessMode.READ_ONLY) {
return GenericDao.createNativeQuery(name, NonShardedDao.defaultDS_RO);
}
else {
return GenericDao.createNativeQuery(name, NonShardedDao.defaultDS_RW);
}
}
public static void create(DbEntity entity) {
GenericDao.create(entity, NonShardedDao.defaultDS_RW);
}
public static void delete(DbEntity entity) {
GenericDao.delete(entity, NonShardedDao.defaultDS_RW);
}
public static void update(DbEntity entity) {
GenericDao.update(entity, NonShardedDao.defaultDS_RW);
}
public static void flush() {
GenericDao.flush(NonShardedDao.defaultDS_RW);
}
public static void clear() {
GenericDao.clear(NonShardedDao.defaultDS_RW);
}
}
| true |
ca05546f7d5e699422df990e56d36c90d6a78eeb
|
Java
|
alzimmermsft/azure-sdk-for-java
|
/sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/compute/generated/VirtualMachineExtensionsListSamples.java
|
UTF-8
| 1,852 | 1.90625 | 2 |
[
"LGPL-2.1-or-later",
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference",
"CC0-1.0",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.compute.generated;
/** Samples for VirtualMachineExtensions List. */
public final class VirtualMachineExtensionsListSamples {
/*
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-11-01/examples/virtualMachineExamples/VirtualMachineExtensions_List_MinimumSet_Gen.json
*/
/**
* Sample code: VirtualMachineExtensions_List_MinimumSet_Gen.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void virtualMachineExtensionsListMinimumSetGen(com.azure.resourcemanager.AzureResourceManager azure) {
azure
.virtualMachines()
.manager()
.serviceClient()
.getVirtualMachineExtensions()
.listWithResponse("rgcompute", "aaaaaaaaaaaaaaaaaaaaaaaaaaa", null, com.azure.core.util.Context.NONE);
}
/*
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/ComputeRP/stable/2022-11-01/examples/virtualMachineExamples/VirtualMachineExtensions_List_MaximumSet_Gen.json
*/
/**
* Sample code: VirtualMachineExtensions_List_MaximumSet_Gen.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void virtualMachineExtensionsListMaximumSetGen(com.azure.resourcemanager.AzureResourceManager azure) {
azure
.virtualMachines()
.manager()
.serviceClient()
.getVirtualMachineExtensions()
.listWithResponse("rgcompute", "aaaaaaaaaaaaa", "aaaaaaaaaaaaaaaaa", com.azure.core.util.Context.NONE);
}
}
| true |
9f840c5805f7beb2d3b7b91fd9f71ecf6eb39d15
|
Java
|
mamjong/Bioscoop
|
/app/src/main/java/com/example/whrabbit/bioscoop/ReviewListActivity.java
|
UTF-8
| 3,315 | 2.078125 | 2 |
[] |
no_license
|
package com.example.whrabbit.bioscoop;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import com.example.whrabbit.bioscoop.API.Film;
import com.example.whrabbit.bioscoop.DatabaseLayer.DatabaseHandler;
import com.example.whrabbit.bioscoop.Domain.Review;
import com.example.whrabbit.bioscoop.Domain.ReviewAdapter;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
/**
* Created by mark on 2-4-2017.
*/
public class ReviewListActivity extends AppCompatActivity {
private Button ticketsTabBttn, infoTabBttn, makeReviewBttn;
private ImageView filmBackdrop;
private Bundle extra;
private Film film;
private ListView reviewsList;
private ReviewAdapter reviewAdapter;
private ArrayList<Review> reviews;
private DatabaseHandler dbh;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_review_list);
dbh = new DatabaseHandler(getApplicationContext(), null, null, 1);
extra = getIntent().getExtras();
film = extra.getParcelable("FILM");
filmBackdrop = (ImageView) findViewById(R.id.filmBackdrop);
if(film.getBackdrop_path() != null) {
Picasso.with(this).load("https://image.tmdb.org/t/p" + "/w500" + "/" + film.getBackdrop_path()).into(filmBackdrop);
} else {
Picasso.with(this).load("http://placehold.it/0x0").into(filmBackdrop);
}
ticketsTabBttn = (Button) findViewById(R.id.ticketsTabBttn);
ticketsTabBttn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), PlaytimesActivity.class);
i.putExtra("FILM", film);
startActivity(i);
}
});
infoTabBttn = (Button) findViewById(R.id.infoTabBttn);
infoTabBttn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), FilmInfoActivity.class);
i.putExtra("FILM", film);
startActivity(i);
}
});
makeReviewBttn = (Button) findViewById(R.id.makeReviewBttn);
makeReviewBttn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), ReviewActivity.class);
i.putExtra("FILM", film);
startActivity(i);
}
});
reviewsList = (ListView) findViewById(R.id.reviewsList);
reviews = new ArrayList<>();
reviews = dbh.getReviews(film.getId());
reviewAdapter = new ReviewAdapter(getApplicationContext(), reviews);
reviewsList.setAdapter(reviewAdapter);
reviewAdapter.notifyDataSetChanged();
}
/*
@Override
public void onReviewAvailable(Review review) {
reviews.add(review);
reviewAdapter.notifyDataSetChanged();
}
*/
}
| true |
cc43b9fd179a14b1b8a80f273e37985e22551d5b
|
Java
|
CyberspaceStudio/uapply
|
/src/main/java/com/volunteer/uapply/sevice/impl/UserServiceImpl.java
|
UTF-8
| 3,272 | 2.171875 | 2 |
[] |
no_license
|
package com.volunteer.uapply.sevice.impl;
import com.volunteer.uapply.mapper.DepartmentMemberMapper;
import com.volunteer.uapply.mapper.UserMessageMapper;
import com.volunteer.uapply.pojo.DepartmentMember;
import com.volunteer.uapply.pojo.User;
import com.volunteer.uapply.pojo.info.TokenPO;
import com.volunteer.uapply.pojo.info.WxResponseInfo;
import com.volunteer.uapply.sevice.UserService;
import com.volunteer.uapply.utils.Tokenutil;
import com.volunteer.uapply.utils.WeChatUtil;
import com.volunteer.uapply.utils.enums.ResponseResultEnum;
import com.volunteer.uapply.utils.response.UniversalResponseBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* @author 郭树耸
* @version 1.0
* @date 2020/4/6 14:38
*/
@Service
@Slf4j
public class UserServiceImpl implements UserService {
@Resource
private WeChatUtil weChatUtil;
@Resource
private Tokenutil tokenutil;
@Resource
private UserMessageMapper userMapper;
@Resource
private DepartmentMemberMapper departmentMemberMapper;
@Override
public UniversalResponseBody<TokenPO<User>> userWxLogin(String code) {
WxResponseInfo wxResponseInfo = weChatUtil.getWeChatResponseBody(code);
//Code无效
if (wxResponseInfo.getErrcode() != null) {
//将微信返回错误代码及结果记录到日志中
log.error("微信登录出错" + code + wxResponseInfo.getErrcode() + "\t" + wxResponseInfo.getErrmsg());
return new UniversalResponseBody(ResponseResultEnum.CODE_IS_INVALID.getCode(), ResponseResultEnum.CODE_IS_INVALID.getMsg());
}
String token = null;
TokenPO<User> tokenPO = null;
User user = userMapper.getUserByOpenid(wxResponseInfo.getOpenid());
//数据库中已经存在该用户
if (user != null) {
token = tokenutil.TokenByUserId(user.getUserId());
tokenPO = new TokenPO(user, token);
return new UniversalResponseBody<TokenPO<User>>(ResponseResultEnum.USER_HAVE_EXIST.getCode(), ResponseResultEnum.USER_HAVE_EXIST.getMsg(), tokenPO);
} else {
//插入用户
user = new User(wxResponseInfo.getOpenid());
userMapper.insertUser(user);
//根据userId生成token
token = tokenutil.TokenByUserId(user.getUserId());
tokenPO = new TokenPO(user, token);
return new UniversalResponseBody<TokenPO<User>>(ResponseResultEnum.USER_LOGIN_SUCCESS.getCode(), ResponseResultEnum.USER_LOGIN_SUCCESS.getMsg(), tokenPO);
}
}
@Override
public UniversalResponseBody<List<DepartmentMember>> getUserPermission(Integer userId) {
//查部门成员数据库中
List<DepartmentMember> departmentMemberList = departmentMemberMapper.getUserAuthority(userId);
if (departmentMemberList == null) {
return new UniversalResponseBody(ResponseResultEnum.SUCCESS.getCode(), ResponseResultEnum.SUCCESS.getMsg());
} else {
return new UniversalResponseBody<List<DepartmentMember>>(ResponseResultEnum.SUCCESS.getCode(), ResponseResultEnum.SUCCESS.getMsg(), departmentMemberList);
}
}
}
| true |
33699d296dbb3dabd5b8f303a918b55c8cfe1f13
|
Java
|
Joseavilez20/SemilleroHBT
|
/ambiente/semillero-hbt/semillero-padre/semillero-servicios/src/main/java/com/hbt/semillero/ejb/GestionarPersonajeBean.java
|
UTF-8
| 4,228 | 2.625 | 3 |
[] |
no_license
|
package com.hbt.semillero.ejb;
import com.hbt.semillero.dto.PersonajeDTO;
import com.hbt.semillero.entidad.Comic;
import com.hbt.semillero.entidad.Personaje;
import com.hbt.semillero.interfaz.IGestionarPersonajeLocal;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.FetchType;
import javax.persistence.ManyToOne;
import javax.persistence.PersistenceContext;
import org.apache.log4j.Logger;
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class GestionarPersonajeBean implements IGestionarPersonajeLocal{
private static final Logger logger = Logger.getLogger(GestionarPersonajeBean.class);
/**
* Atributo em que se usa para interacturar con el contexto de persistencia.
*/
@PersistenceContext
private EntityManager entityManager;
//@Override
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void crearPersonaje(PersonajeDTO personajeDTO) {
logger.debug("inicia crearPersonaje()");
Personaje personaje = convertirPersonajeDTOToPersonaje(personajeDTO);
entityManager.persist(personaje);
logger.debug("finaliza crearPersonaje()");
}
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void actualizarPersonaje() {
logger.debug("inicia ");
logger.debug("finaliza ");
}
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void eliminarPersonaje(Long idPersona) {
logger.debug("inicia ");
logger.debug("finaliza ");
}
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public List<PersonajeDTO> consultarPersonajes() {
logger.debug("inicia metodo consultarPersonajes");
String query = "SELECT personaje FROM Personaje personaje";
List<Personaje> listaPersonajes = entityManager.createQuery(query).getResultList();
List<PersonajeDTO> listaPersonajesDTO = new ArrayList<>();
for(Personaje personaje: listaPersonajes){
listaPersonajesDTO.add(convertirPersonajeToPersonajeDTO(personaje));
}
logger.debug("finaliza ");
return listaPersonajesDTO;
}
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public List<PersonajeDTO> consultarPersonajes(Long idComic) {
logger.debug("inicia consultarPersonajes con parametro ");
String query = "SELECT personaje "+"FROM Personaje personaje "+ "WHERE personaje.comic.id= :idComic";
List<Personaje> listaPersonajes = entityManager.createQuery(query).setParameter("idComic", idComic).getResultList();
List<PersonajeDTO> listaPersonajesDTO = new ArrayList<>();
for(Personaje personaje: listaPersonajes){
listaPersonajesDTO.add(convertirPersonajeToPersonajeDTO(personaje));
}
logger.debug("finaliza ");
return listaPersonajesDTO;
}
/**
*
* Metodo encargado de transformar un personaje a un personajeDTO
*
* @param personaje
* @return personajeDTO
*/
private PersonajeDTO convertirPersonajeToPersonajeDTO(Personaje personaje){
PersonajeDTO personajeDTO = new PersonajeDTO();
if(personaje.getId()!= null){
personajeDTO.setId(personaje.getId());
}
personajeDTO.setNombre(personaje.getNombre());
personajeDTO.setEstado(personaje.getEstado());
personajeDTO.setSuperPoder(personaje.getSuperpoder());
personajeDTO.setIdComic(personaje.getComic().getId());
return personajeDTO;
}
/**
*
* Metodo encargado de transformar un personajeDTO a un personaje
*
* @param personajeDTO
* @return personaje
*/
private Personaje convertirPersonajeDTOToPersonaje(PersonajeDTO personajeDTO){
Personaje personaje = new Personaje();
if(personajeDTO.getId()!= null){
personaje.setId(personajeDTO.getId());
}
personaje.setNombre(personajeDTO.getNombre());
personaje.setEstado(personajeDTO.getEstado());
personaje.setSuperpoder(personajeDTO.getSuperPoder());
personaje.setComic(new Comic()); //al utilizar @ManyToOne(fetch = FetchType.LAZY) en el atributo comic de la entidad
personaje.getComic().setId(personajeDTO.getIdComic());
return personaje;
}
}
| true |
70547ffa2b5571345fcac410f153c5331041ce1b
|
Java
|
jditlee/democloud
|
/service-feign/src/main/java/com/lingyunxin/servicefeign/service/impl/FeignServiceImpl.java
|
UTF-8
| 362 | 1.96875 | 2 |
[] |
no_license
|
package com.lingyunxin.servicefeign.service.impl;
import com.lingyunxin.servicefeign.service.FeignService;
import org.springframework.stereotype.Component;
@Component
public class FeignServiceImpl implements FeignService {
@Override
public String sayHiFromEurekaCli(String name) {
return "sorry,"+name+",error error error !!!!!!!!!!!";
}
}
| true |
88951314bb5405afd75e48153f9a89d8654ef220
|
Java
|
kushunet/mall
|
/mall-dao/src/main/java/cn/dnaizn/mall/mapper/StatementsMapper.java
|
UTF-8
| 890 | 1.890625 | 2 |
[] |
no_license
|
package cn.dnaizn.mall.mapper;
import cn.dnaizn.mall.pojo.Statements;
import cn.dnaizn.mall.pojo.StatementsExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface StatementsMapper {
int countByExample(StatementsExample example);
int deleteByExample(StatementsExample example);
int deleteByPrimaryKey(Integer id);
int insert(Statements record);
int insertSelective(Statements record);
List<Statements> selectByExample(StatementsExample example);
Statements selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") Statements record, @Param("example") StatementsExample example);
int updateByExample(@Param("record") Statements record, @Param("example") StatementsExample example);
int updateByPrimaryKeySelective(Statements record);
int updateByPrimaryKey(Statements record);
}
| true |
8f1ef05d37f38b07137ee59ead03e2af1c0e3c77
|
Java
|
saasquatch/apache-client5-reactive
|
/src/test/java/com/saasquatch/client5reactive/LifecycleTests.java
|
UTF-8
| 1,307 | 2.328125 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.saasquatch.client5reactive;
import io.reactivex.rxjava3.core.Flowable;
import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
import org.junit.jupiter.api.Test;
public class LifecycleTests {
private static final String EXAMPLE_URL = "https://www.example.com";
@Test
public void testNonStarted() throws Exception {
try (CloseableHttpAsyncClient asyncClient = HttpAsyncClients.createDefault()) {
// Not started
final HttpReactiveClient reactiveClient = HttpReactiveClients.create(asyncClient);
Flowable.fromPublisher(reactiveClient.execute(SimpleRequestBuilder.get(EXAMPLE_URL).build()))
.test().assertError(IllegalStateException.class);
}
}
@Test
public void testClosed() throws Exception {
final HttpReactiveClient reactiveClient;
try (CloseableHttpAsyncClient asyncClient = HttpAsyncClients.createDefault()) {
asyncClient.start();
reactiveClient = HttpReactiveClients.create(asyncClient);
}
// Closed
Flowable.fromPublisher(reactiveClient.execute(SimpleRequestBuilder.get(EXAMPLE_URL).build()))
.test().assertError(IllegalStateException.class);
}
}
| true |
b027481805c4d4d626d507ceccf089969e19f1cf
|
Java
|
u0652804/Java-practice-print_aToz
|
/src/StringPrint1/src/StringPrint1/StringPrint.java
|
UTF-8
| 506 | 3.921875 | 4 |
[] |
no_license
|
package StringPrint1;
/***
* @author Bo-Xun Liao
*
***/
public class StringPrint {
public StringPrint() {
String str = "";
// init. str = "a1"~"z1"
for(char i = 'a'; i <= 'z'; i ++)
if(i == 'z')
str = str + i + ' ';
else
str = str + i + ',';
System.out.print("The String : " + str + "\n");
System.out.println("print as below : ");
// print a1 b1 c1...
for(int i = 0; i < str.toCharArray().length; i += 2)
System.out.println(str.charAt(i) + "" + '1');
}
}
| true |
e9bfa91290ee0c31efadce705e01a724d1672be8
|
Java
|
shreeshasa/eureka
|
/src/main/java/io/github/shreeshasa/selenium/AbstractPage.java
|
UTF-8
| 4,091 | 2.640625 | 3 |
[
"Apache-2.0"
] |
permissive
|
package io.github.shreeshasa.selenium;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.PostConstruct;
import java.time.Duration;
/**
* An abstraction class for a page object the can be executed for browsers.
* <br><br>
* Extend this in your page like:
* <pre>
* <code>
* @Page
* public class MyPage extends AbstractPage {
* }
* </code>
* </pre>
*
* @author shreeshasa
*/
public abstract class AbstractPage {
@Autowired
protected WebDriver driver;
@PostConstruct
public void init() {
PageFactory.initElements(driver, this);
}
/**
* Waits until Clickable for given <code>webElement</code> upto <code>timeOutInSeconds</code> seconds
*
* @param timeOutInSeconds
*/
private Wait<WebDriver> getWait(final long timeOutInSeconds) {
return new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(timeOutInSeconds))
.pollingEvery(Duration.ofSeconds(1))
.ignoring(Exception.class);
}
/**
* Waits until Clickable for given <code>webElement</code> upto 10 seconds
*
* @param webElement
*/
protected WebElement waitUntilClickable(final WebElement webElement) {
return waitUntilClickable(webElement, 10);
}
/**
* Waits until Clickable for given <code>webElement</code> upto <code>timeOutInSeconds</code> seconds
*
* @param webElement
* @param timeOutInSeconds
*/
protected WebElement waitUntilClickable(final WebElement webElement, final long timeOutInSeconds) {
return getWait(timeOutInSeconds).until(ExpectedConditions.elementToBeClickable(webElement));
}
/**
* Waits until Clickable for given <code>locator</code> upto 5 seconds
*
* @param locator
*/
protected WebElement waitUntilClickable(final By locator) {
return waitUntilClickable(locator, 10);
}
/**
* Waits until Clickable for given <code>locator</code> upto <code>timeOutInSeconds</code> seconds
*
* @param locator
* @param timeOutInSeconds
*/
protected WebElement waitUntilClickable(final By locator, final long timeOutInSeconds) {
return getWait(timeOutInSeconds).until(ExpectedConditions.elementToBeClickable(locator));
}
/**
* Waits until Visibility for given <code>webElement</code> upto 10 seconds
*
* @param webElement
*/
protected WebElement waitUntilVisibility(final WebElement webElement) {
return waitUntilVisibility(webElement, 10);
}
/**
* Waits until Visibility for given <code>webElement</code> upto <code>timeOutInSeconds</code> seconds
*
* @param webElement
* @param timeOutInSeconds
*/
protected WebElement waitUntilVisibility(final WebElement webElement, final long timeOutInSeconds) {
return getWait(timeOutInSeconds).until(ExpectedConditions.visibilityOf(webElement));
}
/**
* Waits until Visibility for given <code>locator</code> upto 10 seconds
*
* @param locator
*/
protected WebElement waitUntilVisibility(final By locator) {
return waitUntilVisibility(locator, 10);
}
/**
* Waits until Visibility for given <code>locator</code> upto <code>timeOutInSeconds</code> seconds
*
* @param locator
* @param timeOutInSeconds
*/
protected WebElement waitUntilVisibility(final By locator, final long timeOutInSeconds) {
return getWait(timeOutInSeconds).until(ExpectedConditions.visibilityOfElementLocated(locator));
}
/**
* Waits until Visibility for given <code>webElement</code> upto <code>timeOutInSeconds</code> seconds
*
* @param webElement
* @param timeOutInSeconds
*/
protected boolean waitUntilInvisibility(final WebElement webElement, final long timeOutInSeconds) {
return getWait(timeOutInSeconds).until(ExpectedConditions.invisibilityOf(webElement));
}
}
| true |
8773e368e217a7a6f8eab50fa04e797b18363c07
|
Java
|
AlJamilSuvo/AutoTaskEmailSend
|
/src/al/jamil/suvo/autoemail/fx/AutoEmailSender.java
|
UTF-8
| 4,569 | 2.25 | 2 |
[] |
no_license
|
package al.jamil.suvo.autoemail.fx;
import al.jamil.suvo.autoemail.controller.AutoEmailController;
import al.jamil.suvo.autoemail.traynotification.animations.Animations;
import al.jamil.suvo.autoemail.traynotification.notification.Notification;
import al.jamil.suvo.autoemail.traynotification.notification.Notifications;
import al.jamil.suvo.autoemail.traynotification.notification.TrayNotification;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import javafx.util.Duration;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class AutoEmailSender extends Application {
AutoEmailController controller;
boolean isDarkTheme = false;
Scene scene;
@Override
public void start(Stage primaryStage) throws Exception {
Platform.setImplicitExit(false);
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("auto_email_main_new.fxml"));
Parent parent = fxmlLoader.load();
controller = fxmlLoader.getController();
scene = new Scene(parent);
primaryStage.setScene(scene);
primaryStage.setTitle("Auto Task Email Send");
File file = new File("img/icon.png");
Image icon = new Image("file:///" + file.getAbsolutePath());
primaryStage.getIcons().add(icon);
createSystemTrayIcon(primaryStage);
primaryStage.resizableProperty().setValue(Boolean.FALSE);
primaryStage.show();
primaryStage.setOnCloseRequest(event -> {
if (SystemTray.isSupported() && controller.showSendToSystemTray()) {
hide(primaryStage);
} else System.exit(0);
});
}
private void createSystemTrayIcon(Stage stage) {
if (SystemTray.isSupported()) {
SystemTray tray = SystemTray.getSystemTray();
java.awt.Image image = null;
try {
File file = new File("img/icon_tray.png");
URL url = new URL("file:///" + file.getAbsolutePath());
image = ImageIO.read(url);
} catch (IOException ex) {
ex.fillInStackTrace();
}
ActionListener showListener = e -> Platform.runLater(stage::show);
ActionListener closeListener = e -> System.exit(0);
ActionListener sendEmailNowListener = e -> {
Platform.runLater(controller::doSendEmail);
};
ActionListener cancelAutoSendListener = e -> {
Platform.runLater(controller::doCancelAutoSend);
};
PopupMenu popup = new PopupMenu();
MenuItem showItem = new MenuItem("Show");
showItem.addActionListener(showListener);
popup.add(showItem);
MenuItem sendEmailNow = new MenuItem("Send Email Now");
sendEmailNow.addActionListener(sendEmailNowListener);
popup.add(sendEmailNow);
MenuItem cancelAutoSend = new MenuItem("Cancel Auto Send");
cancelAutoSend.addActionListener(cancelAutoSendListener);
popup.add(cancelAutoSend);
MenuItem closeItem = new MenuItem("Close");
closeItem.addActionListener(closeListener);
popup.add(closeItem);
TrayIcon trayIcon = new TrayIcon(image, "Auto Task Email Send", popup);
trayIcon.addActionListener(showListener);
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.err.println(e);
}
}
}
private void hide(final Stage stage) {
Platform.runLater(() -> {
if (SystemTray.isSupported()) {
stage.hide();
showProgramIsMinimizedMsg();
} else {
System.exit(0);
}
});
}
private void showProgramIsMinimizedMsg() {
String title = "Still Running...";
String message = "Auto task email Send is on system tray";
Notification notification = Notifications.INFORMATION;
TrayNotification tray = new TrayNotification();
tray.setTitle(title);
tray.setMessage(message);
tray.setNotification(notification);
tray.setAnimation(Animations.POPUP);
tray.showAndDismiss(new Duration(10 * 1000));
}
}
| true |
e941d1ac2110827701e42601d5f3424c6505bb57
|
Java
|
aburgosu/AT10-logicalPlayer
|
/src/main/java/com/fundation/logic/view/loadSaveCriteria/PopupLoadSave.java
|
UTF-8
| 1,269 | 2.484375 | 2 |
[] |
no_license
|
/**
* Copyright (c) 2019 Jalasoft.
*
* This software is the confidential and proprietary information of Jalasoft.
* ("Confidential Information"). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Jalasoft.
*/
package com.fundation.logic.view.loadSaveCriteria;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
/**
* Implements PopupLoadSave class which is in charge of delete or load criteria.
*
* @author Melissa Román
* @version 1.0
*/
public class PopupLoadSave extends JPopupMenu {
private JMenuItem loadItem;
private JMenuItem deleteItem;
/**
* Initializes PopupMenu with options to load or delete selected criteria.
*/
public PopupLoadSave() {
loadItem = new JMenuItem("Load");
add(loadItem);
deleteItem = new JMenuItem("Delete");
add(deleteItem);
}
/**
* Allows to get load item from the menu.
* @return Load item.
*/
public JMenuItem getLoadItem() {
return loadItem;
}
/**
* Allows to get delete item from the menu.
* @return Delete item.
*/
public JMenuItem getDeleteItem() {
return deleteItem;
}
}
| true |
8918c969b1adaa6d3fc9109300992002eae68c08
|
Java
|
wsgan001/c2001
|
/src/net/c2001/utils/ui/atom/JTextFieldPanel.java
|
UTF-8
| 2,860 | 2.9375 | 3 |
[
"BSD-2-Clause",
"MIT"
] |
permissive
|
package net.c2001.utils.ui.atom;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.event.MouseListener;
import javax.swing.JTextField;
/**
* Create a {@link JPanel} which contains a {@link JTextField}.
* @author Lin Dong
*
*/
public class JTextFieldPanel extends JPanel implements Checkable
{
private static final long serialVersionUID = 1L;
private JTextField jTextField = null;
private int len = 0;
/**
* Create a {@link JTextFieldPanel}.
*/
public JTextFieldPanel()
{
super();
initialize();
}
/**
* Create a {@link JTextFieldPanel}.
* @param len width of {@link JTextField} in this {@link JTextFieldPanel}.
*/
public JTextFieldPanel(int len)
{
super();
this.len = len;
initialize();
}
/**
* This method initializes this
*
* @return void
*/
private void initialize()
{
this.setLayout(new BorderLayout());
this.add(getJTextFieldPrivate(), BorderLayout.CENTER);
}
/**
* This method initializes jTextField
*
* @return {@link JTextField}
*/
private JTextField getJTextFieldPrivate()
{
if (jTextField == null)
{
if(len > 0)
jTextField = new JTextField(len);
else
jTextField = new JTextField();
}
return jTextField;
}
/**
* Get the text in {@link JTextField} on this {@link JTextFieldPanel}.
* @return text in {@link JTextField} on success, {@code null} on failure.
*/
public String getText()
{
if(checkAll())
{
return jTextField.getText();
}
return null;
}
/**
* Get the text in {@link JTextField} on this {@link JTextFieldPanel}.
* @param text test to display in the {@link JTextField}.
*/
public void setText(String text)
{
if(checkInit())
{
jTextField.setText(text);
}
}
/**
* Get the {@link JTextField} object on this {@link JTextFieldPanel}.
*
* @return the {@link JTextField} object on this {@link JTextFieldPanel}
* on success, {@code null} on failure.
*/
public JTextField getJTextFiled()
{
if (checkInit())
return jTextField;
else
return null;
}
/**
* Set whether the {@link JTextField} is enabled. If it is disabled, the
* listener bonded to it will be removed automatically.
* @param enable {@code true} for enable, {@code false} for disable.
*/
public void setFieldEnabled(boolean enable)
{
if(checkInit())
{
jTextField.setEnabled(enable);
if(enable == false)
{
MouseListener[] listeners = jTextField.getListeners(MouseListener.class);
for (MouseListener listener : listeners)
{
jTextField.removeMouseListener(listener);
}
}
}
}
@Override
public boolean checkAll()
{
if(checkInit() && jTextField.getText().trim().isEmpty() != true)
return true;
else
return false;
}
@Override
public boolean checkInit()
{
if (jTextField != null)
return true;
else
return false;
}
}
| true |
98a238bbce8b314379c3bff5b6a1214aa4bd3de3
|
Java
|
BandwidthOnDemand/nsi-common-lib
|
/src/main/java/net/es/nsi/common/signing/SimpleKeySelectorResult.java
|
UTF-8
| 398 | 2.09375 | 2 |
[
"BSD-3-Clause-LBNL"
] |
permissive
|
package net.es.nsi.common.signing;
import java.security.Key;
import java.security.PublicKey;
import javax.xml.crypto.KeySelectorResult;
/**
*
* @author hacksaw
*/
public class SimpleKeySelectorResult implements KeySelectorResult {
private final PublicKey pk;
SimpleKeySelectorResult(PublicKey pk) {
this.pk = pk;
}
@Override
public Key getKey() { return pk; }
}
| true |
d0ccbdc4082667550c6f9d91f6ad37432ec16402
|
Java
|
joelmwood/Contact-Info-DB-with-Java
|
/ContactInfo/src/ContactInfoInput.java
|
UTF-8
| 501 | 2.75 | 3 |
[] |
no_license
|
/**
*
* @author Wood
*/
import javax.swing.JFrame;
public class ContactInfoInput {
public static void main(String[] args) {
ContactInputForm mainFrame = new ContactInputForm();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize( 400, 400 );//set frame size
mainFrame.setResizable(false);//keeps the user from resizing the window
mainFrame.setVisible ( true );//display frame
}//end main
}//end class
| true |
ee88a4d097e45e82b217e5e2434da1bd4a21724e
|
Java
|
biaolv/com.instagram.android
|
/src/com/instagram/android/activity/y.java
|
UTF-8
| 2,437 | 1.59375 | 2 |
[] |
no_license
|
package com.instagram.android.activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.Window;
import com.facebook.z;
import com.instagram.android.a.f;
import com.instagram.android.nux.a.bb;
import com.instagram.service.a.c;
import com.instagram.ui.dialog.k;
final class y
extends BroadcastReceiver
{
y(MainTabActivity paramMainTabActivity) {}
public final void onReceive(Context paramContext, Intent paramIntent)
{
if (paramIntent.getAction().equals("LogoutManager.BROADCAST_POST_LOGOUT")) {
bb.a(a, null, true);
}
do
{
return;
if (paramIntent.getAction().equals("LogoutManager.BROADCAST_POST_ACCOUNT_SWITCH"))
{
if (paramIntent.getBooleanExtra("LogoutHelper.FORCED_SWITCH", false))
{
new k(a).a(z.error).a(false).a(a.getResources().getString(z.forced_logout_error, new Object[] { paramIntent.getStringExtra("LogoutHelper.OLD_USERNAME") })).a(z.ok, new v(this)).b().show();
return;
}
MainTabActivity.a(a, (Intent)paramIntent.getParcelableExtra("LogoutHelper.EXTRA_INTENT"));
return;
}
if (paramIntent.getAction().equals("MainTabActivity.BROADCAST_ADD_ACCOUNT"))
{
if (c.a().d())
{
if (!f.a(a))
{
f.a(a, false);
return;
}
paramContext = new Bundle();
paramContext.putBoolean("SignedOutFragmentActivity.IS_ADD_ACCOUNT_FLOW", true);
bb.a(a.getCurrentActivity(), paramContext, false);
return;
}
new k(a.getWindow().getContext()).a(z.unable_to_add_account).a(false).b(z.maximum_accounts_logged_in).a(z.ok, new w(this)).b().show();
return;
}
} while (!paramIntent.getAction().equals("LogoutHelper.BROADCAST_ACCOUNT_SWITCH_FAIL"));
paramContext = paramIntent.getStringExtra("LogoutHelper.DEST_USER_ID");
paramIntent = paramIntent.getStringExtra("LogoutHelper.OLD_USERNAME");
c.a().b(paramContext);
new k(a).a(z.error).a(false).a(a.getResources().getString(z.forced_logout_error, new Object[] { paramIntent })).a(z.ok, new x(this)).b().show();
}
}
/* Location:
* Qualified Name: com.instagram.android.activity.y
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
| true |
69668a3102f108f6d2a9739cb4cc6c207ab229c6
|
Java
|
cuong369/FirstProject
|
/FirstProjects/src/project4/CalculatesLetter.java
|
UTF-8
| 652 | 3.15625 | 3 |
[] |
no_license
|
package project4;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class CalculatesLetter {
public static Map<String, Integer> numberLetter(String inputString) {
Set<String> calculates = new HashSet<String>();
for (String i : inputString.split("")) {
if (i.equals(" "))
continue;
calculates.add(i);
}
Map<String, Integer> result = new HashMap<String, Integer>();
for (String j : calculates) {
int s = 0;
for (String i : inputString.split("")) {
if(i.equals(" "))
continue;
if (i.equals(j)) {
result.put(j, ++ s);
}
}
}
return result;
}
}
| true |
1f94adce1e96a4e616bc598dffad9aedd4485a7b
|
Java
|
gprabhakar/SimSys
|
/Game Generator/src/edu/utdallas/gamegeneratorcollection/ComponentSelection/SearchAlgo.java
|
UTF-8
| 7,028 | 2.796875 | 3 |
[] |
no_license
|
package edu.utdallas.gamegeneratorcollection.ComponentSelection;
import java.util.LinkedList;
import Jama.EigenvalueDecomposition;
import Jama.Matrix;
/*Control Class
*/
public class SearchAlgo {
private String xmlCharacters;
private String xmlLessons;
private String xmlChallenges;
private String xmlLocale;
private String xmlSubject;
private String xmlTheme;
private String[] allFiles = new String[6];
private String[] gameComponents = { "Characters", "Lesson", "Challenge", "Locale", "Subject", "Theme"};
private int[] allFileNumbers = new int[6];
private InputWizard inputs;
public SearchAlgo()//LinkedList<String> CriteriaList, LinkedList<String>inputedCriteriaList)
{
xmlCharacters="Characters0";
xmlLessons="Lesson0";
xmlChallenges="Challenge0";
xmlLocale="Locale0";
xmlSubject="Subject0";
xmlTheme="Theme0";
Matrix[] componentInputs = new Matrix[6];
//SearchInput input;
SearchSpace[] searchSpaces = new SearchSpace[6];
Matrix[] componentInputSearchSpace=new Matrix[6];
///////////////////////////
// System.out.println("Test1, Start of SearchAlgo");
for(int x=0; x<componentInputs.length; x++)
{
searchSpaces[x]= new SearchSpace(gameComponents[x]);
//searchSpace which should be from the metadata tags
componentInputSearchSpace[x]= new Matrix(searchSpaces[x].getSearchSpace());
//changes the SearchSpace array into a Matrix object
}
for(int x=0; x<componentInputs.length; x++)
{
componentInputs[x]= new Matrix(new double[searchSpaces[x].getNumberOfCriteria()][searchSpaces[x].getNumberOfCriteria()]);
}//end of loop with x
//REPLACES ABOVE LOOP WITH WIZARD INPUTS
componentInputs = getWizardInputs(componentInputs);
printAllMatrixes(componentInputs);
//AHP Matrix Math
for(int x=gameComponents.length-1; x>=0; x--)
{
System.out.println("Matrcies for "+ gameComponents[x]);
System.out.println("Search Input");
printMatrix(componentInputs[x]);//brings the input into this class
//OLDCODE- this code uses the JAMA Matrix library to get the eigenvector matrix. However due to inconsistent results, it has been scrapped.
// EigenvalueDecomposition eigenDecomp= componentInputs[x].eig();
//creates new object that contains the eigenvector
// Matrix weightedMatrix = eigenDecomp.getV();//makes the eigenvector matrix of the input
// System.out.println("Real Eigenvalues");
// printArray(eigenDecomp.getRealEigenvalues());
// System.out.println("Imiganary Eigenvalues");
// printArray(eigenDecomp.getImagEigenvalues());
System.out.println("Weighted Matrix / Eigenvector");
Matrix weightedMatrix = eigenvectorCalculation(componentInputs[x]);
printMatrix(weightedMatrix);
System.out.println("Component Metadata Input");
printMatrix(componentInputSearchSpace[x]);
Matrix criteriaScore = componentInputSearchSpace[x].times(weightedMatrix);
//multiplies the weighted score matrix by the input matrix.
printMatrix(criteriaScore);
allFileNumbers[x]= getLargestValue(criteriaScore, x);
allFiles[x]=gameComponents[x]+allFileNumbers[x];
System.out.println(allFiles[x]);
}// end of loop with x
//Get rid of this when SearchInput is working.
// allFiles[0]=xmlCharacters;
// allFiles[1]=xmlLessons;
// allFiles[2]=xmlChallenges;
// allFiles[3]=xmlLocale;
// allFiles[4]=xmlSubject;
// allFiles[5]=xmlTheme;
}
/*
* FAKE EIGENVECTOR CALCULATION
* The original eigenvector calculation through the library returned poor, unreadable
* results with no documentation. This prompted me (Kaleb) to find and employ this
* alternative method. Its basicly weighting the matrix and putting into a 1 dimensional
* matrix.
*/
private Matrix eigenvectorCalculation(Matrix inputMatrix)
{
double[][] inputArray = inputMatrix.getArray();
double[][] outputArray = new double[inputArray.length][1];
int rowLength = inputMatrix.getRowDimension();
double[] rowSums = new double[inputArray.length];
for(int y=0; y<inputArray.length;y++)
{
for(int x=0; x<inputArray[y].length; x++)
{
rowSums[x]+=inputArray[x][y];
}
}
double rowSumsTotal =0;
for(int x=0; x< rowSums.length; x++)
{
rowSums[x]= Math.pow(rowSums[x],1.0/rowSums.length);
rowSumsTotal += rowSums[x];
}
for(int x=0; x< rowSums.length; x++)
{
rowSums[x]/=rowSumsTotal;
}
for(int x=0; x< rowSums.length; x++)
{
outputArray[x][0] = rowSums[x];
}
return new Matrix(outputArray) ;
}
private void printArray(double[] input)
{
for(int x =0; x<input.length;x++ )
{
System.out.println(x+": "+input[x]);
}
}
//Creates, calls, and returns the input wizard inputs
private Matrix[] getWizardInputs(Matrix[] componentInputs)
{
inputs = new InputWizard(componentInputs);
return inputs.getWizardInputs();
}
private void printAllMatrixes(Matrix[] componentInputs)
{
for(int x=0; x<componentInputs.length;x++)
{
System.out.println(gameComponents[x]);
printMatrix(componentInputs[x]);
}
}
public String getFileLocation()
{
return inputs.getFileLocation();
}
public int getLargestValue(Matrix in, int componentNumber)
{
double[][] inputArray = in.getArray();
double largestValue=inputArray[0][0];
int largestIndex=0;
for(int x = 0; x<inputArray.length; x++)
{
if(inputArray[x][0]>largestValue)
{
largestValue = inputArray[x][0];
largestIndex = x;
}
if(inputArray[x][0]==largestValue && (componentNumber==1 || componentNumber ==2) && x==allFileNumbers[4])
{
System.out.println("Adjusting "+gameComponents[componentNumber]+" "+x+" to Subject "+allFileNumbers[4]);
largestValue = inputArray[x][0];
largestIndex = x;
}
}//end of loop with x
return largestIndex;
}
public Matrix getLastColumn(Matrix inputMatrix)
{
double[][] inputArray = inputMatrix.getArray();
double[][] outputArray = new double[inputArray[0].length][1];
for(int x =0; x<inputArray[0].length;x++ )
{
outputArray[x][0]=inputArray[x][0];//inputArray.length-1];
}
// System.out.println("Eigenvector alone");
// printMatrix(new Matrix (outputArray));
return new Matrix(outputArray);
}
public void printMatrix(Matrix inputMatrix)
{
double[][] inputArray = inputMatrix.getArray();
for(int x=0; x < inputArray.length; x++)
{
for (int y =0; y < inputArray[x].length; y++)
{
System.out.printf("%.3f ",inputArray[x][y]);
}
System.out.println("");
}
}
// Getter Methods
public String getCharacters(){
return xmlCharacters;
}
public String getLessons(){
return xmlLessons;
}
public String getChallenges(){
return xmlChallenges;
}
public String getLocale(){
return xmlLocale;
}
public String getSubject(){
return xmlSubject;
}
public String getTheme(){
return xmlTheme;
}
public String[] searchResults(){
return allFiles;
}
}
| true |
4819c9ff71b7ac91f9715d0257ecf5b25daacdd7
|
Java
|
gahlawat4u/repoName
|
/rda0105-agl-aus-java-a43926f304e3/xms-persistence/src/main/java/com/gms/xms/persistence/service/note/NoteServiceImp.java
|
UTF-8
| 1,554 | 2.015625 | 2 |
[] |
no_license
|
package com.gms.xms.persistence.service.note;
import com.gms.xms.common.exception.DaoException;
import com.gms.xms.filter.note.NoteFilter;
import com.gms.xms.persistence.dao.NoteDao;
import com.gms.xms.txndb.vo.NoteVo;
import java.util.List;
import java.util.Map;
/**
* Posted from NoteServiceImp
* <p>
* Author DatTV Oct 1, 2015
*/
public class NoteServiceImp implements INoteService {
@Override
public List<NoteVo> selectByFilter(NoteFilter filter) throws DaoException {
NoteDao noteDao = new NoteDao();
return noteDao.selectByFilter(filter);
}
@Override
public long countByFilter(NoteFilter filter) throws DaoException {
NoteDao noteDao = new NoteDao();
return noteDao.countByFilter(filter);
}
@Override
public NoteVo selectById(Long noteId) throws DaoException {
NoteDao noteDao = new NoteDao();
return noteDao.selectById(noteId);
}
@Override
public void delete(Map<String, String> context, Long noteId) throws DaoException {
NoteDao noteDao = new NoteDao();
noteDao.delete(context, noteId);
}
@Override
public void insert(Map<String, String> context, NoteVo note) throws DaoException {
NoteDao noteDao = new NoteDao();
noteDao.insert(context, note);
}
@Override
public void update(Map<String, String> context, NoteVo note) throws DaoException {
NoteDao noteDao = new NoteDao();
noteDao.update(context, note);
}
}
| true |
e94cf0de8d439516cfde5361a3ed48e8643e4751
|
Java
|
kutaydemireren/Monopoly
|
/test/unittesting/LandCardsTest.java
|
UTF-8
| 920 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
package unittesting;
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
import game.LandCards;
import game.Player;
public class LandCardsTest {
private static LandCards landCard;
private static Player p1;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
landCard=new LandCards("LakeStreet","lightPink",30, 1, 5, 15, 45, 80, 125, 625, 50, 15);
p1=new Player("Kutay", 1500, "GREEN");
p1.giveMoney(landCard.getLandPrice());
p1.addCard(landCard);
landCard.setSold(true);
landCard.setLandOwner(p1);
String color = landCard.getLandColor();
p1.getCardsWithColor().get(color)[0]++;
int[] building = new int[] {0,0,0,0,0};
p1.getBuildings().put(landCard, building);
}
@Test
public void testGetLandOwner(){
Player x= landCard.getLandOwner();
assertEquals(p1, x);
landCard.repOk();
}
}
| true |
58107477f36d32cea99b08b8c85732ce7250cf36
|
Java
|
yasmineA/bank-account-back
|
/src/main/java/com/sg/bankaccountback/model/Balance.java
|
UTF-8
| 293 | 1.882813 | 2 |
[] |
no_license
|
package com.sg.bankaccountback.model;
import com.sun.javafx.beans.IDProperty;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Balance {
@Id
@GeneratedValue
private Long id;
private float amount;
}
| true |
e148b0e30db0ac86a5171da6abe5651894c257ab
|
Java
|
Zhandos-Hello-World/Introduction-to-Java
|
/Chapter_19/Exercise19.10/Main.java
|
UTF-8
| 808 | 3.953125 | 4 |
[] |
no_license
|
/*
(Smallest element in ArrayList) Write the following method that returns the
smallest element in an ArrayList:
public static <E extends Comparable<E>> E min(ArrayList<E> list)
*/
import java.util.ArrayList;
public class Main {
public static void main(String[]args){
ArrayList<Integer>list = new ArrayList<>();
for(int i = 0; i < 10; i++){
list.add((int)(Math.random() * 1000 + 0));
}
System.out.println(list);
System.out.println("Min number is: " + min(list));
}
public static <E extends Comparable<E>> E min(ArrayList<E> list){
E min = list.get(0);
for(int i = 0; i < list.size(); i++){
if(min.compareTo(list.get(i)) > 0){
min = list.get(i);
}
}
return min;
}
}
| true |
df328037fb6b9baa50ebd61255acd9e56bcef352
|
Java
|
karlfehd/GraphNode
|
/graph-node/src/main/java/com/sample/GNodeImpl.java
|
UTF-8
| 2,072 | 3.03125 | 3 |
[] |
no_license
|
package com.sample;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class GNodeImpl implements GNode {
private final String name;
private final ArrayList<GNode> children = new ArrayList<>();
public GNodeImpl(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
public String toString() {
return name;
}
@Override
public void addChild(GNode gNode) {
children.add(gNode);
}
@Override
public GNode[] getChildren() {
return children.toArray(new GNode[0]);
}
@Override
public ArrayList<GNode> walkGraph(GNode gNode) {
Collection<GNode> visitedNodes = new ArrayList<>();
List<GNode> notVisitedNodes = new ArrayList<>(Collections.singletonList(gNode));
while (!notVisitedNodes.isEmpty()) {
List<GNode> newNodes =
(ArrayList<GNode>) notVisitedNodes.stream().map(GNode::getChildren).flatMap(Arrays::stream)
.filter(node -> !visitedNodes.contains(node))
.collect(Collectors.toList());
visitedNodes.addAll(notVisitedNodes);
notVisitedNodes = newNodes;
}
return (ArrayList<GNode>) visitedNodes.stream().distinct().collect(Collectors.toList());
}
@Override
public ArrayList<ArrayList<GNode>> paths(GNode gNode) {
ArrayList<ArrayList<GNode>> tempList = new ArrayList<>();
if (gNode.getChildren().length > 0) {
for (GNode child : gNode.getChildren()) {
tempList.addAll(paths(child));
}
tempList.forEach(child -> child.add(0, gNode));
} else {
ArrayList<GNode> node = new ArrayList<>();
node.add(gNode);
tempList.add(node);
}
return tempList;
}
}
| true |
2a5f0bf7a1262049df572483a9f0e4d16a3f97a9
|
Java
|
PetoMichalak/EsperOn
|
/app/src/main/java/eu/uk/ncl/pet5o/esper/epl/expression/core/ExprFilterSpecLookupable.java
|
UTF-8
| 2,509 | 1.90625 | 2 |
[] |
no_license
|
/*
***************************************************************************************
* Copyright (C) 2006 EsperTech, Inc. All rights reserved. *
* http://www.espertech.com/esper *
* http://www.espertech.com *
* ---------------------------------------------------------------------------------- *
* The software in this package is published under the terms of the GPL license *
* a copy of which has been included with this distribution in the license.txt file. *
***************************************************************************************
*/
package eu.uk.ncl.pet5o.esper.epl.expression.core;
import eu.uk.ncl.pet5o.esper.client.EventPropertyGetter;
import eu.uk.ncl.pet5o.esper.util.JavaClassHelper;
import java.io.Serializable;
import java.io.StringWriter;
public class ExprFilterSpecLookupable implements Serializable {
private static final long serialVersionUID = 3576828533611557509L;
private final String expression;
private transient final EventPropertyGetter getter;
private final Class returnType;
private final boolean isNonPropertyGetter;
public ExprFilterSpecLookupable(String expression, EventPropertyGetter getter, Class returnType, boolean isNonPropertyGetter) {
this.expression = expression;
this.getter = getter;
this.returnType = JavaClassHelper.getBoxedType(returnType); // For type consistency for recovery and serde define as boxed type
this.isNonPropertyGetter = isNonPropertyGetter;
}
public String getExpression() {
return expression;
}
public EventPropertyGetter getGetter() {
return getter;
}
public Class getReturnType() {
return returnType;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ExprFilterSpecLookupable that = (ExprFilterSpecLookupable) o;
if (!expression.equals(that.expression)) return false;
return true;
}
public int hashCode() {
return expression.hashCode();
}
public void appendTo(StringWriter writer) {
writer.append(expression);
}
public String toString() {
return "expression='" + expression + '\'';
}
public boolean isNonPropertyGetter() {
return isNonPropertyGetter;
}
}
| true |
84e28d55ade82fbb704777a9fb4513582e3a6300
|
Java
|
matezov/ref
|
/KiszurosAmoba/src/amoba/model/Board.java
|
UTF-8
| 4,603 | 3.109375 | 3 |
[] |
no_license
|
package amoba.model;
import java.util.ArrayList;
import java.util.Random;
public class Board {
private int size;
private Symbol[][] gameBoard;
private Symbol actualPlayer;
private int freeField;
private ArrayList<Point> symX = new ArrayList<>();
private ArrayList<Point> symO = new ArrayList<>();
public Board(int size) {
this.size = size;
gameBoard = new Symbol[size][size];
actualPlayer = Symbol.X;
freeField = size * size;
for (int i=0; i < size; ++i) {
for (int j=0; j < size; ++j) {
gameBoard[i][j] = Symbol.UNFILLED;
}
}
}
public Symbol step(int i, int j) {
if (gameBoard[i][j] != Symbol.UNFILLED) {
return gameBoard[i][j];
}
gameBoard[i][j] = actualPlayer;
--freeField;
if (actualPlayer == Symbol.X) {
symX.add(new Point(i, j));
}
if (actualPlayer == Symbol.O) {
symO.add(new Point(i, j));
}
if (actualPlayer == Symbol.X) {
actualPlayer = Symbol.O;
} else {
actualPlayer = Symbol.X;
}
return gameBoard[i][j];
}
public Point trick(Symbol sym) {
Symbol temp = sym;
int rand;
++freeField;
if (temp == Symbol.X) {
rand = getRandomNumber(0, symX.size() - 1);
Point p = symX.get(rand);
symX.remove(rand);
gameBoard[p.x][p.y] = Symbol.UNFILLED;
return p;
}
if (temp == Symbol.O) {
rand = getRandomNumber(0, symO.size() - 1);
Point p = symO.get(rand);
symO.remove(rand);
gameBoard[p.x][p.y] = Symbol.UNFILLED;
return p;
}
return null;
}
public boolean someInARow(Symbol sym, int i, int j, int symNumMin, int symNumMax) {
return findWinner(i, j, sym, symNumMin, symNumMax) != Symbol.UNFILLED;
}
private static int getRandomNumber(int min, int max) {
Random r = new Random();
return r.nextInt((max - min) + 1) + min;
}
public Symbol findWinner(final int x, final int y, Symbol sym, int symNumMin, int symNumMax) {
// Vízszintes ellenőrzés
int c = 1;
for (int j = y + 1; j < y + symNumMin && isInRange(x,j) && gameBoard[x][j] == sym ; ++j) {
++c;
}
for (int j = y - 1; j > y - symNumMin && isInRange(x,j) && gameBoard[x][j] == sym ; --j) {
++c;
}
if (c >= symNumMin && c <= symNumMax) return sym;
// Függőleges ellenőrzés
c = 1;
for (int i = x + 1; i < x + symNumMin && isInRange(i,y) && gameBoard[i][y] == sym ; ++i) {
++c;
}
for (int i = x - 1; i > x - symNumMin && isInRange(i,y) && gameBoard[i][y] == sym ; --i) {
++c;
}
if (c >= symNumMin && c <= symNumMax) return sym;
// Átlós ellenőrzés 1
c = 1;
int a = x + 1;
int b = y + 1;
while (isInRange(a,b) && a < x + symNumMin && b < y + symNumMin && gameBoard[a][b] == sym) {
++c;
++a;
++b;
}
a = x - 1;
b = y - 1;
while (isInRange(a,b) && a > x - symNumMin && b > y - symNumMin && gameBoard[a][b] == sym) {
++c;
--a;
--b;
}
if (c >= symNumMin && c <= symNumMax) return sym;
// Átlós ellenőrzés 2
c = 1;
a = x + 1;
b = y - 1;
while (isInRange(a,b) && a < x + symNumMin && b > y - symNumMin && gameBoard[a][b] == sym) {
++c;
++a;
--b;
}
a = x - 1;
b = y + 1;
while (isInRange(a,b) && a > x - symNumMin && b < y + symNumMin && gameBoard[a][b] == sym) {
++c;
--a;
++b;
}
if (c >= symNumMin && c <= symNumMax) return sym;
return Symbol.UNFILLED;
}
public boolean isInRange(int a, int b) {
return a < size && b < size && a >= 0 && b >= 0;
}
public Symbol getActualPlayer() {
return actualPlayer;
}
public int getSize() {
return size;
}
public boolean draw() {
return freeField == 0;
}
}
| true |
402b94b1ea0764e6a379830e394a266a694a55ad
|
Java
|
quophyie/javashared
|
/src/main/java/com/quantal/javashared/dto/LogTraceId.java
|
UTF-8
| 1,195 | 2.40625 | 2 |
[] |
no_license
|
package com.quantal.javashared.dto;
import com.quantal.javashared.constants.CommonConstants;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* Created by dman on 09/10/2017.
*/
@Data
@Builder
@EqualsAndHashCode(callSuper = true)
public class LogTraceId extends LogField{
private String traceId;
//private String msg;
public LogTraceId(String traceId){
this();
super.setValue(traceId);
this.traceId = traceId;
}
public LogTraceId(){
super();
super.setKey(CommonConstants.TRACE_ID_MDC_KEY);
}
@Override
public void setKey(String key) {
throw new IllegalArgumentException(String.format("TraceId key name cannot be changed. It will always remain as %s", CommonConstants.TRACE_ID_MDC_KEY));
}
@Override
public void setValue (Object value){
if (!(value instanceof String))
throw new IllegalArgumentException("value must be a string");
super.setValue(value);
this.traceId = (String) value;
}
public static class LogTraceIdBuilder extends LogFieldBuilder{
LogTraceIdBuilder(){
super();
}
}
}
| true |
58785935dc3bd330994641e3100a72ff04a34575
|
Java
|
nadeni/National-MD
|
/NationalMd/src/Login_in/Connective.java
|
UTF-8
| 552 | 2.109375 | 2 |
[] |
no_license
|
package Login_in;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Connective {
public static java.sql.Connection getConnection() throws SQLException, ClassNotFoundException{
String driver ="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/Game";
String password="1234";
String user="root";
Class.forName(driver);
return DriverManager.getConnection(url, user, password);
// System.out.println("完成");
}
}
| true |
e48dd7b32f3522cb591af840b8c4e0da6953b604
|
Java
|
xia-lin/ScratchFileReader
|
/src/com/roscopeco/scratch/io/objects/False.java
|
UTF-8
| 228 | 2.15625 | 2 |
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
package com.roscopeco.scratch.io.objects;
public class False extends ScratchBool {
public static final False instance = new False();
private False() {}
@Override
protected boolean value() {
return false;
}
}
| true |
146f7211f5f4b8c44f47552584cde73367c0955d
|
Java
|
andrewbhennessy/CS1332
|
/hw8/src/Sorting.java
|
UTF-8
| 12,170 | 3.828125 | 4 |
[] |
no_license
|
import java.util.LinkedList;
import java.util.Comparator;
import java.util.Random;
/**
* Your implementation of various sorting algorithms.
*
* @author Andrew Hennessy
* @userid ahennessy6
* @GTID 903309743
* @version 1.0
*/
public class Sorting {
/**
* Implement insertion sort.
*
* It should be:
* in-place
* stable
*
* Have a worst case running time of:
* O(n^2)
*
* And a best case running time of:
* O(n)
*
* @throws IllegalArgumentException if the array or comparator is null
* @param <T> data type to sort
* @param arr the array that must be sorted after the method runs
* @param comparator the Comparator used to compare the data in arr
*/
public static <T> void insertionSort(T[] arr, Comparator<T> comparator) {
if (arr == null) {
throw new IllegalArgumentException("Arr is null therefore "
+ "cannot be sorted");
}
if (comparator == null) {
throw new IllegalArgumentException("comparator is null therefore "
+ "cannot be sorted");
}
int length = arr.length;
for (int i = 1; i <= length - 1; i++) {
int j = i;
while (j > 0 && comparator.compare(arr[j - 1], arr[j]) > 0) {
T buffer = arr[j - 1];
T swap = arr[j];
arr[j] = buffer;
arr[j - 1] = swap;
j--;
}
}
}
/**
* Implement selection sort.
*
* It should be:
* in-place
* unstable
*
* Have a worst case running time of:
* O(n^2)
*
* And a best case running time of:
* O(n^2)
*
* @throws IllegalArgumentException if the array or comparator is null
* @param <T> data type to sort
* @param arr the array that must be sorted after the method runs
* @param comparator the Comparator used to compare the data in arr
*/
public static <T> void selectionSort(T[] arr, Comparator<T> comparator) {
if (arr == null) {
throw new IllegalArgumentException("Arr is null therefore "
+ "cannot be sorted");
}
if (comparator == null) {
throw new IllegalArgumentException("comparator is null therefore "
+ "cannot be sorted");
}
for (int i = 0; i <= arr.length - 1; i++) {
T smallest = arr[i];
int smallestIndex = i;
for (int j = i + 1; j <= arr.length - 1; j++) {
if (comparator.compare(arr[j], smallest) < 0) {
smallest = arr[j];
smallestIndex = j;
}
}
T buffer = arr[i];
T swap = arr[smallestIndex];
arr[i] = swap;
arr[smallestIndex] = buffer;
}
}
/**
* Implement merge sort.
*
* It should be:
* out-of-place
* stable
*
* Have a worst case running time of:
* O(n log n)
*
* And a best case running time of:
* O(n log n)
*
* You can create more arrays to run mergesort, but at the end, everything
* should be merged back into the original T[] which was passed in.
*
* When splitting the array, if there is an odd number of elements, put the
* extra data on the right side.
*
* @throws IllegalArgumentException if the array or comparator is null
* @param <T> data type to sort
* @param arr the array to be sorted
* @param comparator the Comparator used to compare the data in arr
*/
public static <T> void mergeSort(T[] arr, Comparator<T> comparator) {
if (arr == null) {
throw new IllegalArgumentException("Arr is null therefore "
+ "cannot be sorted");
}
if (comparator == null) {
throw new IllegalArgumentException("comparator is null therefore "
+ "cannot be sorted");
}
int length = arr.length;
int midIndex = length / 2;
T[] leftArray = (T[]) createArray(arr, 0, midIndex - 1);
T[] rightArray = (T[]) createArray(arr, midIndex, length - 1);
if (length < 2) {
return;
}
mergeSort(leftArray, comparator);
mergeSort(rightArray, comparator);
int leftIndex = 0;
int rightIndex = 0;
int currentIndex = 0;
while (leftIndex < midIndex && rightIndex < length - midIndex) {
if (comparator.compare(leftArray[leftIndex],
rightArray[rightIndex]) <= 0) {
arr[currentIndex] = leftArray[leftIndex];
leftIndex++;
} else {
arr[currentIndex] = rightArray[rightIndex];
rightIndex++;
}
currentIndex++;
}
while (leftIndex < midIndex) {
arr[currentIndex] = leftArray[leftIndex];
leftIndex++;
currentIndex++;
}
while (rightIndex < length - midIndex) {
arr[currentIndex] = rightArray[rightIndex];
rightIndex++;
currentIndex++;
}
}
/**
* private helper method to create arrays given a set of indices.
*
* @param arr the array to be split
* @param leftPtr the left most index from the arr that will be 0th elem in
* new arr.
* @param rightPtr the right most index from the arr that will be 0th
* elem in new arr.
* @param <T> generic type parameter
* @return array of objects that will be casted to generic type.
*/
private static <T> T[] createArray(T[] arr, int leftPtr,
int rightPtr) {
T[] output = (T[]) new Object[rightPtr - leftPtr + 1];
for (int i = 0; i <= rightPtr - leftPtr; i++) {
//System.out.println(arr[i + leftPtr]);
output[i] = arr[i + leftPtr];
}
return output;
}
/**
* Implement quick sort.
*
* Use the provided random object to select your pivots. For example if you
* need a pivot between a (inclusive) and b (exclusive) where b > a, use
* the following code:
*
* int pivotIndex = rand.nextInt(b - a) + a;
*
* If your recursion uses an inclusive b instead of an exclusive one,
* the formula changes by adding 1 to the nextInt() call:
*
* int pivotIndex = rand.nextInt(b - a + 1) + a;
*
* It should be:
* in-place
* unstable
*
* Have a worst case running time of:
* O(n^2)
*
* And a best case running time of:
* O(n log n)
*
* Make sure you code the algorithm as you have been taught it in class.
* There are several versions of this algorithm and you may not receive
* credit if you do not use the one we have taught you!
*
* @throws IllegalArgumentException if the array or comparator or rand is
* null
* @param <T> data type to sort
* @param arr the array that must be sorted after the method runs
* @param comparator the Comparator used to compare the data in arr
* @param rand the Random object used to select pivots
*/
public static <T> void quickSort(T[] arr, Comparator<T> comparator,
Random rand) {
if (arr == null) {
throw new IllegalArgumentException("Arr is null therefore "
+ "cannot be sorted");
}
if (comparator == null) {
throw new IllegalArgumentException("comparator is null therefore "
+ "cannot be sorted");
}
if (rand == null) {
throw new IllegalArgumentException("rand is null therefore "
+ "cannot be sorted");
}
quickSort(arr, comparator, rand, 0, arr.length);
}
/**
*
* @param arr the array that must be sorted after the method runs
* @param comparator the Comparator used to compare the data in arr
* @param rand rand the Random object used to select pivots
* @param left marker
* @param right marker
* @param <T> data type to sort
*/
private static <T> void quickSort(T[] arr, Comparator<T> comparator,
Random rand, int left, int right) {
if (right - left < 1) {
return;
}
int pivotIndex = rand.nextInt(right - left) + left;
T pivot = arr[pivotIndex];
T leftSwap = arr[left];
T pivotSwap = arr[pivotIndex];
arr[left] = pivotSwap;
arr[pivotIndex] = leftSwap;
int leftIndex = left + 1;
int rightIndex = right - 1;
while (leftIndex <= rightIndex) {
while (leftIndex <= rightIndex && comparator.compare(
arr[leftIndex], pivot) <= 0) {
leftIndex++;
}
while (leftIndex < rightIndex
&& comparator.compare(arr[rightIndex], pivot) >= 0) {
rightIndex--;
}
if (leftIndex <= rightIndex) {
T leftBufferSwap = arr[leftIndex];
T rightBufferSwap = arr[rightIndex];
arr[leftIndex] = rightBufferSwap;
arr[rightIndex] = leftBufferSwap;
leftIndex++;
rightIndex--;
}
}
T pivotBufferSwap = arr[left];
T pivotRightSwap = arr[rightIndex];
arr[left] = pivotRightSwap;
arr[rightIndex] = pivotBufferSwap;
quickSort(arr, comparator, rand, left, rightIndex);
quickSort(arr, comparator, rand, rightIndex + 1, right);
}
/**
* Implement LSD (least significant digit) radix sort.
*
* Make sure you code the algorithm as you have been taught it in class.
* There are several versions of this algorithm and you may not get full
* credit if you do not implement the one we have taught you!
*
* Remember you CANNOT convert the ints to strings at any point in your
* code! Doing so may result in a 0 for the implementation.
*
* It should be:
* out-of-place
* stable
*
* Have a worst case running time of:
* O(kn)
*
* And a best case running time of:
* O(kn)
*
* You are allowed to make an initial O(n) passthrough of the array to
* determine the number of iterations you need.
*
* Refer to the PDF for more information on LSD Radix Sort.
*
* You may use {@code java.util.ArrayList} or {@code java.util.LinkedList}
* if you wish, but it may only be used inside radix sort and any radix sort
* helpers. Do NOT use these classes with other sorts.
*
* Do NOT use anything from the Math class except Math.abs().
*
* @throws IllegalArgumentException if the array is null
* @param arr the array to be sorted
*/
public static void lsdRadixSort(int[] arr) {
if (arr == null) {
throw new IllegalArgumentException("Arr is null therefore "
+ "cannot be sorted");
}
LinkedList<Integer>[] buckets = (LinkedList<Integer>[])
new LinkedList[19];
int mod = 10;
int div = 1;
boolean cont = true;
while (cont) {
cont = false;
for (int num : arr) {
int bucket = num / div;
if (bucket / 10 != 0) {
cont = true;
}
if (buckets[bucket % mod + 9] == null) {
buckets[bucket % mod + 9] = new LinkedList<>();
}
buckets[bucket % mod + 9].add(num);
}
int arrIdx = 0;
for (int k = 0; k < buckets.length; k++) {
if (buckets[k] != null) {
for (int num : buckets[k]) {
arr[arrIdx++] = num;
}
buckets[k].clear();
}
}
div *= 10;
}
}
}
| true |
8ec1027628f3e27e082c39d064dff6a389899968
|
Java
|
ajayk-git/myBatis-XML
|
/Student/src/main/java/com/mybatis/Student/controllers/WebController.java
|
UTF-8
| 847 | 2.234375 | 2 |
[] |
no_license
|
package com.mybatis.Student.controllers;
import com.mybatis.Student.entities.User;
import com.mybatis.Student.mappers.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.security.Principal;
@Controller
public class WebController {
@Autowired
UserMapper userMapper;
@RequestMapping(value = "/")
public String index(Principal principal) {
User user = userMapper.findByUserName(principal.getName());
// System.out.println(user.getRole());
if (user.getRole().equalsIgnoreCase("ROLE_ADMIN"))
return "index";
else return "indexUser";
}
@RequestMapping(value = "/login")
public String login() {
return "login";
}
}
| true |
640dfe6c9ef9a2f6453cc2e066bb956b2462e699
|
Java
|
wapalxj/Java
|
/javaworkplace/SXT/src/c77_GameBasic/GameFrame5.java
|
MacCentralEurope
| 779 | 2.71875 | 3 |
[
"Apache-2.0"
] |
permissive
|
package c77_GameBasic;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/**
* Constant,MyFrame
* @param args
*/
public class GameFrame5 extends MyFrame{
Image img =GameUtil.getImage("images_Solar/tou.png") ;
private double x=100,y=100;
private double degree=3.14/3;//[0,2pi]
private double speed=10;
@Override
public void paint(Graphics g) {
g.drawImage(img, (int)x,(int)y,null);
x=100+100*Math.cos(degree);
y=200+50*Math.sin(degree);
degree+=0.1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
GameFrame5 gf=new GameFrame5();
gf.launchFrame();
}
}
| true |
cea966388ed716cab89a3b99a4972505abb084bd
|
Java
|
buddavalladevikumari/data
|
/src/main/java/com/example/demo/controller/Data_Controller.java
|
UTF-8
| 669 | 2.09375 | 2 |
[] |
no_license
|
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class Data_Controller {
@RequestMapping(value="/")
public String init(Model model) {
model.addAttribute("details","car details");
return "index";
}
@ModelAttribute("group1")
public String[] status() {
return new String[] {"sold","unsold"};
}
@ModelAttribute("group2")
public String[] model() {
return new String[] {"hyundai","toyota","fortuner","suzuki"};
}
}
| true |
e835d5564848964251b5dab945b33cf654848e87
|
Java
|
ramtej/Qi4j.Feature.Spatial
|
/samples/dci-cargo/dcisample_b/src/main/java/org/qi4j/sample/dcicargo/sample_b/data/structure/voyage/Voyage.java
|
UTF-8
| 3,131 | 2.671875 | 3 |
[
"Apache-2.0",
"MIT",
"BSD-3-Clause"
] |
permissive
|
/*
* Copyright 2011 Marc Grue.
*
* 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.qi4j.sample.dcicargo.sample_b.data.structure.voyage;
import java.text.SimpleDateFormat;
import org.qi4j.api.mixin.Mixins;
import org.qi4j.api.property.Property;
import org.qi4j.sample.dcicargo.sample_b.data.structure.location.Location;
/**
* Voyage
*
* A voyage is a ship, train, flight etc carrying a cargo from one location
* to another. A {@link Schedule} describes the route it takes.
*
* A cargo can be loaded onto part of, or the whole voyage.
*
* All properties are mandatory and immutable.
*/
@Mixins( Voyage.Mixin.class )
public interface Voyage
{
Property<VoyageNumber> voyageNumber();
Property<Schedule> schedule();
// Side-effects free and UI agnostic convenience methods
CarrierMovement carrierMovementDepartingFrom( Location departure );
String print();
public abstract class Mixin
implements Voyage
{
public CarrierMovement carrierMovementDepartingFrom( Location departure )
{
for( CarrierMovement carrierMovement : schedule().get().carrierMovements().get() )
{
if( carrierMovement.departureLocation().get().equals( departure ) )
{
return carrierMovement;
}
}
return null;
}
public String print()
{
StringBuilder sb = new StringBuilder( "\nVOYAGE " )
.append( voyageNumber().get().number().get() )
.append( " -----------------------------------------------------" );
for( int i = 0; i < schedule().get().carrierMovements().get().size(); i++ )
{
printLeg( i, sb, schedule().get().carrierMovements().get().get( i ) );
}
return sb.append( "\n---------------------------------------------------------------\n" ).toString();
}
private void printLeg( int i, StringBuilder sb, CarrierMovement carrierMovement )
{
sb.append( "\n (Leg " ).append( i ).append( ")" );
sb.append( " Departure " );
sb.append( new SimpleDateFormat( "yyyy-MM-dd" ).format( carrierMovement.departureTime().get() ) );
sb.append( " " ).append( carrierMovement.departureLocation().get() );
sb.append( " Arrival " );
sb.append( new SimpleDateFormat( "yyyy-MM-dd" ).format( carrierMovement.arrivalTime().get() ) );
sb.append( " " ).append( carrierMovement.arrivalLocation().get() );
}
}
}
| true |
951a3ea544d0230c6cde01f3b9b1df5684dae7f1
|
Java
|
vaibhav1412627/Online-Food
|
/app/src/main/java/com/example/win7/onlinefood/C.java
|
UTF-8
| 4,622 | 2.078125 | 2 |
[] |
no_license
|
package com.example.win7.onlinefood;
import android.content.Intent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class C extends AppCompatActivity {
ListView listView;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
ArrayList<String> arrayList = new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
Bundle b = new Bundle();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_c);
Bundle b2 = getIntent().getExtras();
String DATABASE_PATH = b2.getString("Path");
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference(DATABASE_PATH);
ActionBar actionBar = getSupportActionBar();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
listView = (ListView) findViewById(R.id.listView);
//Toast.makeText(this, "ok", Toast.LENGTH_SHORT).show();
databaseReference.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
final String value=dataSnapshot.getValue(String.class);
arrayList.add(value);
arrayAdapter = new ArrayAdapter<String>(C.this, android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
// TODO Auto-generated method stub
//Toast.makeText(C.this, arrayList.get(position), Toast.LENGTH_SHORT).show();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.hasChild(""+arrayList.get(position)+"")) {
// run some code
//Toast.makeText(C.this,"Child is exist",Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(),D.class);
b.putString("Path",""+arrayList.get(position)+"");
i.putExtras(b);
startActivity(i);
}
else {
Toast.makeText(C.this,"Child is not exist",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| true |
684d3e140d7980d5f117720b128732912474552c
|
Java
|
OEarchive/edisonAPITestTool
|
/src/main/java/Model/DataModels/Alarms/AlarmsHistoryResponse.java
|
UTF-8
| 572 | 2.21875 | 2 |
[] |
no_license
|
package Model.DataModels.Alarms;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
public class AlarmsHistoryResponse {
@JsonProperty("message")
private String message;
@JsonProperty("timestamp")
private String timestamp;
@JsonProperty("histories")
private List<AlarmListEntry> histories;
public String getMessage() {
return message;
}
public String getTimestamp() {
return timestamp;
}
public List<AlarmListEntry> getAlarmHistoryEntries() {
return histories;
}
}
| true |
4cdf40f22fca86f5ebc286ca2cc1c5a09e257756
|
Java
|
BBVA/cognito-mfa-singlestep-authorization-plugin
|
/src/main/java/cd/go/authorization/cognitomfasinglestep/CognitoSingleStepLoginManager.java
|
UTF-8
| 4,138 | 2.15625 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2019 Banco Bilbao Vizcaya Argentaria, S.A.
*
* 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 cd.go.authorization.cognitomfasinglestep;
import cd.go.authorization.cognitomfasinglestep.exception.InvalidCognitoUserCredentialsException;
import cd.go.authorization.cognitomfasinglestep.exception.InvalidCognitoUserStateException;
import com.amazonaws.services.cognitoidp.AWSCognitoIdentityProvider;
import com.amazonaws.services.cognitoidp.model.*;
import static cd.go.authorization.cognitomfasinglestep.CognitoMFASingleStepPlugin.LOG;
public class CognitoSingleStepLoginManager {
final private AWSCognitoIdentityProvider cognito;
final private String cognitoClientId;
public CognitoSingleStepLoginManager(AWSCognitoIdentityProvider client, String clientId) {
cognito = client;
cognitoClientId = clientId;
}
public GetUserResult login(String user, String password, String totp) {
GetUserResult userResult;
// NOTE: This weird-looking try-catch block shouldn't be split.
// To ensure we comply with PCI information disclosure policy this block erase the information about which of
// the steps taken in the authentication process actually fails.
try {
InitiateAuthResult auth = startAuth(user, password);
if (!auth.getChallengeName().equals("SOFTWARE_TOKEN_MFA")) {
throw new InvalidCognitoUserStateException("Invalid challenge type: " + auth.getChallengeName());
}
RespondToAuthChallengeResult login = finishAuth(auth.getSession(), user, totp);
if (login.getChallengeName() != null) {
throw new InvalidCognitoUserStateException("Unexpected challenge: " + auth.getChallengeName());
}
GetUserRequest userRequest = new GetUserRequest();
userRequest.setAccessToken(login.getAuthenticationResult().getAccessToken());
userResult = cognito.getUser(userRequest);
} catch (InvalidCognitoUserCredentialsException e) {
LOG.error("Cognito authentication failed for user: " + user);
return null;
}
LOG.info("Cognito authentication succeeded for user: " + user);
return userResult;
}
private InitiateAuthResult startAuth(String user, String password) {
InitiateAuthRequest authRequest = new InitiateAuthRequest();
authRequest.setAuthFlow("USER_PASSWORD_AUTH");
authRequest.setClientId(cognitoClientId);
authRequest.addAuthParametersEntry("USERNAME", user);
authRequest.addAuthParametersEntry("PASSWORD", password);
try {
return cognito.initiateAuth(authRequest);
} catch (UserNotFoundException | NotAuthorizedException e) {
throw new InvalidCognitoUserCredentialsException("Invalid user or password");
}
}
private RespondToAuthChallengeResult finishAuth(String session, String user, String totp) {
RespondToAuthChallengeRequest challengeRequest = new RespondToAuthChallengeRequest();
challengeRequest.setChallengeName(ChallengeNameType.SOFTWARE_TOKEN_MFA);
challengeRequest.setSession(session);
challengeRequest.setClientId(cognitoClientId);
challengeRequest.addChallengeResponsesEntry("USERNAME", user);
challengeRequest.addChallengeResponsesEntry("SOFTWARE_TOKEN_MFA_CODE", totp);
try {
return cognito.respondToAuthChallenge(challengeRequest);
} catch (CodeMismatchException e) {
throw new InvalidCognitoUserCredentialsException("Invalid TOTP");
}
}
}
| true |
2f56e6f6f2b7c2daefcb61dedf25d9662fd059c9
|
Java
|
alunegov/TeamCity-Telegram
|
/src/main/java/alunegov/teamcity/message/MessageFormat.java
|
UTF-8
| 152 | 1.828125 | 2 |
[] |
no_license
|
package alunegov.teamcity.message;
/**
* Created by Alexander on 19.08.2016.
*/
public enum MessageFormat {
PlainText,
Markdown,
Html
}
| true |
93b7a3998bb50e0bcbd6b5621923e9d7a663751a
|
Java
|
Sugie-306/OHOHO
|
/src/jp/co/eintecs/servlet/UpdateUserServlet.java
|
UTF-8
| 2,573 | 2.5 | 2 |
[] |
no_license
|
package jp.co.eintecs.servlet;
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 javax.servlet.http.HttpSession;
import jp.co.eintecs.beans.UserBean;
import jp.co.eintecs.dao.UserDAO;
import jp.co.eintecs.filter.Security;
/**
* 会員更新サーブレット
* @author sasaki
*/
public class UpdateUserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
//文字化け対策
req.setCharacterEncoding("UTF-8");
//ユーザーIDを取得
HttpSession session = req.getSession();
String userId = (String) session.getAttribute("userId");
//メッセージ変数を宣言
String message = "";
//入力を取得
String name = Security.escape(req.getParameter("name"));
String address = Security.escape(req.getParameter("address"));
String post = Security.escape(req.getParameter("post"));
String phone = Security.escape(req.getParameter("phone"));
String mail = Security.escape(req.getParameter("mail"));
String username = Security.escape(req.getParameter("username"));
String userpass = Security.escape(req.getParameter("userpass"));
System.out.println(name + "名前は取得できているか");
//UserBeanのインスタンスを生成
UserBean user = new UserBean();
//UserBeanのインスタンスに値をセット
user.setName(name);
user.setAddress(address);
user.setPost(post);
user.setPhone(phone);
user.setMail(mail);
user.setUsername(username);
user.setUserpass(userpass);
user.setUserid(userId);
//DB更新(person)
if (UserDAO.updatePerson(user)) {
//DB更新(customer)
if (UserDAO.updateCustomer(user)) {
message = "更新に成功しました。";
System.out.println("更新に成功しました。");
} else {
message = "更新に失敗しました。";
System.out.println("更新に失敗しました。1");
}
} else {
message = "更新に失敗しました。";
System.out.println("更新に失敗しました。2");
}
//メッセージをsetAttributeに格納
req.setAttribute("message", message);
//遷移先へ移動
RequestDispatcher rd = req.getRequestDispatcher("customer-output.jsp");
rd.forward(req, res);
}
}
| true |
531750cbec3c24ba5ef3c413079babe279395b6c
|
Java
|
lxs-code/springcloud01
|
/eureka-provider/src/main/java/com/zking/eurekaprovider/model/Commodity.java
|
UTF-8
| 1,849 | 1.945313 | 2 |
[] |
no_license
|
package com.zking.eurekaprovider.model;
import lombok.Data;
import java.util.Date;
@Data
public class Commodity {
private Integer tComid;
private String tComname;
private Double tComprice;
private String tComremark;
private String tComnodata;
private Integer tState;
private String tAmount;
public Commodity(Integer tComid, String tComname, Double tComprice, String tComremark, String tComnodata, Integer tState, String tAmount) {
this.tComid = tComid;
this.tComname = tComname;
this.tComprice = tComprice;
this.tComremark = tComremark;
this.tComnodata = tComnodata;
this.tState = tState;
this.tAmount = tAmount;
}
public Commodity() {
super();
}
public Integer gettComid() {
return tComid;
}
public void settComid(Integer tComid) {
this.tComid = tComid;
}
public String gettComname() {
return tComname;
}
public void settComname(String tComname) {
this.tComname = tComname;
}
public Double gettComprice() {
return tComprice;
}
public void settComprice(Double tComprice) {
this.tComprice = tComprice;
}
public String gettComremark() {
return tComremark;
}
public void settComremark(String tComremark) {
this.tComremark = tComremark;
}
public String gettComnodata() {
return tComnodata;
}
public void settComnodata(String tComnodata) {
this.tComnodata = tComnodata;
}
public Integer gettState() {
return tState;
}
public void settState(Integer tState) {
this.tState = tState;
}
public String gettAmount() {
return tAmount;
}
public void settAmount(String tAmount) {
this.tAmount = tAmount;
}
}
| true |
c15abd2d49c8097048ace9440b9c575c58ef4837
|
Java
|
shijir38/OpenNotification
|
/src/net/reliableresponse/notification/broker/impl/sql/GenericSQLTemplateBroker.java
|
UTF-8
| 4,550 | 2.109375 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Created on Jun 27, 2007
*
*Copyright Reliable Response, 2007
*/
package net.reliableresponse.notification.broker.impl.sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
import net.reliableresponse.notification.broker.BrokerFactory;
import net.reliableresponse.notification.broker.TemplateBroker;
import net.reliableresponse.notification.template.Template;
import net.reliableresponse.notification.usermgmt.User;
public abstract class GenericSQLTemplateBroker implements TemplateBroker {
public abstract Connection getConnection();
public String[] getAllTemplateUuids() {
String sql = "SELECT uuid FROM template";
Vector<String> uuids = new Vector<String>();
PreparedStatement stmt = null;
Connection connection = getConnection();
ResultSet rs = null;
try {
stmt = connection.prepareStatement(sql);BrokerFactory.getLoggingBroker().logDebug("sql="+(sql));
rs = stmt.executeQuery();
while (rs.next()) {
uuids.add(rs.getString(1));
}
} catch (SQLException e) {
BrokerFactory.getLoggingBroker().logError(e);
} finally {
try {
if (rs != null)
rs.close();
if (stmt != null)
stmt.close();
if (connection != null)
connection.close();
} catch (SQLException e1) {
BrokerFactory.getLoggingBroker().logError(e1);
}
}
return uuids.toArray(new String[0]);
}
public Template[] getAllTemplates() {
String sql = "SELECT uuid, recipientType, senderType, classname FROM template";
Vector<Template> templates = new Vector<Template>();
PreparedStatement stmt = null;
Connection connection = getConnection();
ResultSet rs = null;
try {
stmt = connection.prepareStatement(sql);BrokerFactory.getLoggingBroker().logDebug("sql="+(sql));
rs = stmt.executeQuery();
while (rs.next()) {
try {
Template template = (Template)Class.forName(rs.getString("classname")).newInstance();
template.init(rs.getString("recipientType"), rs.getString("senderType"));
templates.add(template);
} catch (Exception e) {
BrokerFactory.getLoggingBroker().logError(e);
}
}
} catch (SQLException e) {
BrokerFactory.getLoggingBroker().logError(e);
} finally {
try {
if (rs != null)
rs.close();
if (stmt != null)
stmt.close();
if (connection != null)
connection.close();
} catch (SQLException e1) {
BrokerFactory.getLoggingBroker().logError(e1);
}
}
return templates.toArray(new Template[0]);
}
public Template getTemplateByUuid(String uuid) {
String sql = "SELECT uuid, recipientType, senderType, classname FROM template WHERE uuid=?";
PreparedStatement stmt = null;
Connection connection = getConnection();
ResultSet rs = null;
try {
stmt = connection.prepareStatement(sql);BrokerFactory.getLoggingBroker().logDebug("sql="+(sql));
stmt.setString(1, uuid);
rs = stmt.executeQuery();
if (rs.next()) {
try {
Template template = (Template)Class.forName(rs.getString("classname")).newInstance();
template.init(rs.getString("recipientType"), rs.getString("senderType"));
return template;
} catch (Exception e) {
BrokerFactory.getLoggingBroker().logError(e);
}
}
} catch (SQLException e) {
BrokerFactory.getLoggingBroker().logError(e);
} finally {
try {
if (rs != null)
rs.close();
if (stmt != null)
stmt.close();
if (connection != null)
connection.close();
} catch (SQLException e1) {
BrokerFactory.getLoggingBroker().logError(e1);
}
}
return null;
}
public void addTemplate (String templateClassName, String recipientType, String senderType) {
PreparedStatement stmt = null;
Connection connection = getConnection();
ResultSet rs = null;
try {
stmt = connection.prepareStatement("INSERT INTO template(uuid, recipientType, senderType, classname) VALUES(?, ?, ?, ?)");BrokerFactory.getLoggingBroker().logDebug("sql="+("INSERT INTO schedule(uuid, name) VALUES(?, ?)"));
stmt.setString(1, BrokerFactory.getUUIDBroker().getUUID());
stmt.setString(2, recipientType);
stmt.setString(2, senderType);
stmt.setString(2, templateClassName);
stmt.executeUpdate();
} catch (SQLException e) {
BrokerFactory.getLoggingBroker().logError(e);
} finally {
try {
if (stmt != null)
stmt.close();
if (connection != null)
connection.close();
} catch (SQLException e1) {
BrokerFactory.getLoggingBroker().logError(e1);
}
}
}
}
| true |
313413997c839e8737a027cd89eec80dadde62ba
|
Java
|
demongel/DailyReader
|
/DailyReader/app/src/main/java/com/shakespace/dailyreader/fragment/TwoFragment.java
|
UTF-8
| 1,009 | 2.234375 | 2 |
[] |
no_license
|
package com.shakespace.dailyreader.fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.shakespace.dailyreader.R;
import com.shakespace.dailyreader.base.BaseFragment;
/**
* A simple {@link Fragment} subclass.
*/
public class TwoFragment extends BaseFragment {
public TwoFragment() {
// Required empty public constructor
}
@Override
public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_two, container, false);
}
@Override
protected void initListener(View view) {
}
//---避免叠加
@Override
public void setMenuVisibility(boolean menuVisible) {
super.setMenuVisibility(menuVisible);
if (getView() != null) {
getView().setVisibility(menuVisible ? View.VISIBLE : View.INVISIBLE);
}
}
}
| true |
6034e0230a0a263dcae6818a17f8aa48c85bc2f3
|
Java
|
yunien/Traffic
|
/src/main/java/com/wistron/occ/enums/InfoCode.java
|
UTF-8
| 1,172 | 2.671875 | 3 |
[] |
no_license
|
package com.wistron.occ.enums;
import org.apache.commons.lang3.StringUtils;
public enum InfoCode {
CODE_NULL("null", 0, "NULL"),
CODE_5F0F("5f0f", 4, "燈態步階傳輸週期管理"),
CODE_0f81("0f81", 4, "燈態步階傳輸週期管理");
private String infoCode;
private int params;
private String des;
InfoCode (final String infoCode, final int params, final String des){
this.infoCode = infoCode;
this.params = params;
this.des = des;
}
public String getInfoCode() {
return infoCode;
}
public void setInfoCode(String infoCode) {
this.infoCode = infoCode;
}
public int getParams() {
return params;
}
public void setParams(int params) {
this.params = params;
}
public String getDes() {
return des;
}
public void setDes(String des) {
this.des = des;
}
public static InfoCode lookup(final String infoCode) {
for (InfoCode code : values()) {
if (StringUtils.equals(code.getInfoCode(), infoCode)) {
return code;
}
}
return CODE_NULL;
}
}
| true |
294b8c6d8f91908945124ebe6fe934f9cde32074
|
Java
|
Aleks-Ya/yaal_examples
|
/Java+/Libs+/Cron+/quartz/test/quartz/job/listener/JobListenerSupportTest.java
|
UTF-8
| 2,742 | 2.359375 | 2 |
[] |
no_license
|
package quartz.job.listener;
import org.junit.jupiter.api.Test;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;
import org.quartz.listeners.JobListenerSupport;
import quartz.Factory;
import quartz.UniversalJob;
import util.Tuple2;
import java.util.ArrayList;
import java.util.List;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;
import static org.quartz.impl.matchers.KeyMatcher.keyEquals;
import static quartz.UniversalJob.WAIT_MILLIS;
/**
* Use a JobListenerSupport.
*/
class JobListenerSupportTest {
@Test
void listener() throws SchedulerException {
try (var factory = new Factory()) {
var scheduler = factory.newScheduler();
var jobDetail = newJob(UniversalJob.class)
.withIdentity("jobDetail1", "group1")
.usingJobData(WAIT_MILLIS, 500)
.build();
var trigger = newTrigger()
.withIdentity("trigger1", "group1")
.startNow()
.build();
var jobListener = new MyJobListener();
scheduler.getListenerManager().addJobListener(jobListener, keyEquals(jobDetail.getKey()));
scheduler.scheduleJob(jobDetail, trigger);
await().timeout(30, SECONDS).untilAsserted(() -> {
assertThat(jobListener.jobToBeExecuted).hasSize(1);
assertThat(jobListener.jobExecutionVetoed).isEmpty();
assertThat(jobListener.jobWasExecuted).hasSize(1);
});
}
}
private static class MyJobListener extends JobListenerSupport {
final List<JobExecutionContext> jobToBeExecuted = new ArrayList<>();
final List<JobExecutionContext> jobExecutionVetoed = new ArrayList<>();
final List<Tuple2<JobExecutionContext, JobExecutionException>> jobWasExecuted = new ArrayList<>();
@Override
public String getName() {
return MyJobListener.class.getSimpleName();
}
@Override
public void jobToBeExecuted(JobExecutionContext context) {
jobToBeExecuted.add(context);
}
@Override
public void jobExecutionVetoed(JobExecutionContext context) {
jobExecutionVetoed.add(context);
}
@Override
public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
jobWasExecuted.add(Tuple2.of(context, jobException));
}
}
}
| true |
b161ed89ca7036ac9331a7912cbab169eb085e0c
|
Java
|
john123pal4/californiaexploration
|
/src/bl-dataaccess/src/main/java/com/jpmorgan/am/im/loanops/queries/ContractQueries.java
|
UTF-8
| 188 | 1.601563 | 2 |
[] |
no_license
|
package com.jpmorgan.am.im.loanops.queries;
public interface ContractQueries {
String getContractsBySecurityId = "SELECT c FROM VWContract c WHERE c.facilityId=:facilityId";
}
| true |
dec21a29d040103b686ee85125413e884d104c1b
|
Java
|
lintsGitHub/TeacherCode
|
/test01 (1)/test01/src/main/java/com/nf147/test01/controller/OrderController.java
|
UTF-8
| 828 | 1.828125 | 2 |
[] |
no_license
|
package com.nf147.test01.controller;
import com.nf147.test01.entity.Order;
import com.nf147.test01.validator.CommonValidator;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@Controller
public class OrderController {
// @InitBinder
// public void suibianqigemingzidanyidingyaoyouyiyi(WebDataBinder binder) {
// binder.setValidator(new CommonValidator());
// }
@RequestMapping(value = "/order", method = RequestMethod.POST)
@ResponseBody
public Order order (@Validated @RequestBody Order order, BindingResult result) {
return order;
}
}
| true |
45a39a47fc29ef6cb93fac276d19484dacb6401d
|
Java
|
naweak/Project-Lambda
|
/src/main/java/melonslise/lambda/client/renderer/color/LambdaColors.java
|
UTF-8
| 662 | 2.140625 | 2 |
[] |
no_license
|
package melonslise.lambda.client.renderer.color;
import net.minecraftforge.client.event.ColorHandlerEvent;
public class LambdaColors
{
private LambdaColors() {}
public static void registerColors(ColorHandlerEvent.Item event)
{
/*
IItemColor color;
color = new IItemColor()
{
@Override
public int colorMultiplier(ItemStack stack, int index)
{
return ((ItemSpawnerEgg) stack.getItem()).getColor(stack, index);
}
};
event.getItemColors().registerItemColorHandler(color, LambdaItems.spawner_headcrab, LambdaItems.spawner_zombie, LambdaItems.spawner_vortigaunt, LambdaItems.spawner_houndeye, LambdaItems.spawner_barnacle);
*/
}
}
| true |
3d0b2f53215c3486b3a07407ac9ae22ed39422e8
|
Java
|
boltony/MSG
|
/src/msg/member/MailController.java
|
UTF-8
| 6,533 | 2.140625 | 2 |
[] |
no_license
|
package msg.member;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;
import java.util.Random;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("*.mail")
public class MailController extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String requestURI = request.getRequestURI();
String ctxPath = request.getContextPath();
String cmd = requestURI.substring(ctxPath.length());
if(cmd.equals("/findPW.mail")) {
// 한글 깨지지 않도록!
request.setCharacterEncoding("utf8");
response.setCharacterEncoding("utf8");
response.setContentType("text/html; charset=UTF-8");
try {
String pw_find_id = request.getParameter("pw_find_id");
String pw_find_email = request.getParameter("pw_find_email");
String pw_find_answer = request.getParameter("pw_find_answer");
String pw_find_hint = request.getParameter("pw_find_hint");
// 비번찾기 폼에 입력한 이메일 값이 DB에 있으면 이메일로 임시비번 보내기 함! 없으면 다시 main으로!
boolean result = MemberDAO.getInstance().selectByEmail(pw_find_email);
System.out.println("DB에 존재하는 이메일인지? : "+result);
if (result == true) {
String host = "smtp.naver.com";
String user = "msg_account_jy";
String password = "msgmsg123!";
String to_email = pw_find_email;
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", 587);
props.put("mail.smtp.auth", "true");
// props.put("mail.smtp.ssl.enable","true"); 이거 넣으면 왜 안됨?
// 임시 비밀번호 생성
StringBuffer temp = new StringBuffer();
Random rnd = new Random();
for (int i = 0; i < 10; i++) {
int rIndex = rnd.nextInt(3);
switch (rIndex) {
case 0:
// a-z
temp.append((char) ((int) (rnd.nextInt(26)) + 97));
break;
case 1:
// A-Z
temp.append((char) ((int) (rnd.nextInt(26)) + 65));
break;
case 2:
// 0-9
temp.append((rnd.nextInt(10)));
break;
}
}
String AuthenticationKey = temp.toString();
System.out.println("임시비밀번호: "+AuthenticationKey);
// AuthenticationKey: 임시비밀번호!
System.out.println(AuthenticationKey + " : " + pw_find_id + " : " + pw_find_email + " : " + pw_find_hint + " : " + pw_find_answer);
int result2 = MemberDAO.getInstance().modifyPW(AuthenticationKey, pw_find_id, pw_find_email,pw_find_hint,pw_find_answer);
System.out.println("비번 수정여부 : " + result2);
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(user, "MSG"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to_email));
msg.setSubject("안녕하세요. MSG 입니다. 회원님의 임시 비밀번호를 발급해드립니다.");
msg.setText(pw_find_id + " 회원님의 임시비밀번호는 [" + AuthenticationKey + "] 입니다.");
Transport.send(msg);
System.out.println("이메일 전송함...");
HttpSession saveKey = request.getSession();
saveKey.setAttribute("AuthenticationKey", AuthenticationKey);
request.setAttribute("pw_find_id", pw_find_id);
response.sendRedirect("main.jsp");
}
} catch (Exception e) {
e.printStackTrace();
response.sendRedirect("error.jsp");
}
}else if(cmd.equals("/emailConfirm.mail")) {
try {
String CheckEmail = request.getParameter("email");
String host = "smtp.naver.com";
String user = "msg_account_jy";
String password = "msgmsg123!";
String to_email = CheckEmail;
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", 587);
props.put("mail.smtp.auth", "true");
// props.put("mail.smtp.ssl.enable","true"); 이거 넣으면 왜 안됨?
// 임시 비밀번호 생성
StringBuffer temp = new StringBuffer();
Random rnd = new Random();
for (int i = 0; i < 10; i++) {
int rIndex = rnd.nextInt(3);
switch (rIndex) {
case 0:
// a-z
temp.append((char) ((int) (rnd.nextInt(26)) + 97));
break;
case 1:
// A-Z
temp.append((char) ((int) (rnd.nextInt(26)) + 65));
break;
case 2:
// 0-9
temp.append((rnd.nextInt(10)));
break;
}
}
String AuthenticationKey = temp.toString();
System.out.println("이메일 인증번호: "+AuthenticationKey);
// AuthenticationKey: 메일 인증번호!
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(user, "MSG"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to_email));
msg.setSubject("안녕하세요. MSG 입니다. 회원가입 이메일 인증번호를 보내드립니다.");
msg.setText("이메일 인증번호는 [" + AuthenticationKey + "] 입니다.");
Transport.send(msg);
System.out.println("이메일 전송함...");
HttpSession saveKey = request.getSession();
saveKey.setAttribute("AuthenticationKey", AuthenticationKey);
request.setAttribute("email_key", AuthenticationKey);
request.getRequestDispatcher("member/emailCheck.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
response.sendRedirect("member/error.jsp");
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
| true |
f51ce733b2183a1d4351b69ae0fb242b6efbfe70
|
Java
|
sora12345/SpringTest
|
/ksr1/src/main/java/kr/co/ksr1/board/service/Impl/BoardDocServiceImpl.java
|
UTF-8
| 7,200 | 1.921875 | 2 |
[] |
no_license
|
package kr.co.ksr1.board.service.Impl;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import kr.co.ksr1.board.dao.IBoardCommentDAO;
import kr.co.ksr1.board.dao.IBoardDocDAO;
import kr.co.ksr1.board.dao.IBoardFileDAO;
import kr.co.ksr1.board.dao.IBoardLikeDAO;
import kr.co.ksr1.board.dao.IBoardNoticeDAO;
import kr.co.ksr1.board.dao.Impl.BoardDocDAOImpl;
import kr.co.ksr1.board.dao.Impl.BoardNoticeDAOImpl;
import kr.co.ksr1.board.dto.BoardDocDTO;
import kr.co.ksr1.board.dto.BoardFileDTO;
import kr.co.ksr1.board.dto.BoardSearchDTO;
import kr.co.ksr1.board.service.IBoardDocService;
import kr.co.ksr1.board.service.IBoardFileService;
import kr.co.ksr1.board.service.IBoardLikeService;
import kr.co.ksr1.commom.dao.BaseDaoSupport;
import kr.co.ksr1.commom.file.FileService;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class BoardDocServiceImpl implements IBoardDocService {
@Autowired private IBoardDocDAO boardDocDAOImpl = null;
@Autowired private IBoardFileDAO boardFileDAOImpl = null;
@Autowired private IBoardCommentDAO boardCommentDAOImpl = null;
@Autowired private IBoardFileService boardFileServiceImpl = null;
@Autowired private IBoardLikeDAO boardLikeDAOImpl = null;
@Autowired private FileService fileService = null;
@Autowired private IBoardNoticeDAO boardNoticeDAOImpl = null;
@Override
@Transactional
public void write(BoardDocDTO boardDocDTO, HttpSession session) {
// 1. 게시물 insert
boardDocDAOImpl.insertData(boardDocDTO);
// 2. 게시물 파일 insert
List<MultipartFile> fileList = boardDocDTO.getFiles();
BoardFileDTO boardFileDTO = null;
if (fileList != null) {
for (MultipartFile file : boardDocDTO.getFiles()) {
log.debug("name1================>" + file.getOriginalFilename());
log.debug("name2=================>" + file.getSize());
// 2. 첨부파일 물리적인 디스크에 저장
boardFileDTO = fileService.uploadSingleFile(file, session);
// 3. 첨부파일 디비에 insert
boardFileDTO.setDocId(boardDocDTO.getDocId());
boardFileServiceImpl.write(boardFileDTO);
}
}
// 3. 공지사항 게시글 체크 및 insert
if(boardDocDTO.getMapId()==5) {
boardNoticeDAOImpl.insertData(boardDocDTO);
}
}
@Override
@Transactional
public BoardDocDTO view(BoardDocDTO _boardDocDTO) {
// 1. 조회수 증가
this.editByCntRead(_boardDocDTO.getDocId());
// 2. 조회
BoardDocDTO boardDocDTO = boardDocDAOImpl.selectOne(_boardDocDTO);
// 3. 첨부파일 가져오기
List<BoardFileDTO> fileList = boardFileServiceImpl.list(_boardDocDTO.getDocId());
boardDocDTO.setFileList(fileList);
return boardDocDTO;
}
@Override
@Transactional
public void edit(BoardDocDTO boardDocDTO, HttpSession session) {
// 1. 첨부파일 등록
BoardFileDTO fileDTO = null;
log.debug("getDocId()=====================>" + boardDocDTO.getFiles());
if (boardDocDTO.getFiles() != null) {
for (MultipartFile file : boardDocDTO.getFiles()) {
log.debug("name1================>" + file.getOriginalFilename());
log.debug("name2=================>" + file.getSize());
// 2. 첨부파일 물리적인 디스크에 저장
fileDTO = fileService.uploadSingleFile(file, session);
// 3. 첨부파일 디비에 insert
fileDTO.setDocId(boardDocDTO.getDocId());
log.debug("fileDTO=====================>" + fileDTO);
log.debug("fileDTO=====================>" + fileDTO);
boardFileServiceImpl.write(fileDTO);
}
}
if (boardDocDTO.getDelFiles() != null) {
// 2.첨부파일 삭제
for (Integer sno : boardDocDTO.getDelFiles()) {
boardFileServiceImpl.remove(sno);
log.debug("==========>" + sno);
}
}
// 3. 수정
boardDocDAOImpl.updateData(boardDocDTO);
// 3. 공지사항 게시글 체크 및 edit
if(boardDocDTO.getMapId()==5) {
boardNoticeDAOImpl.updateData(boardDocDTO.getDocId());
}
}
@Override
public void remove(Integer docId) {
boardFileDAOImpl.deleteByDocId(docId);
boardCommentDAOImpl.deleteByDocId(docId);
boardLikeDAOImpl.deleteByDocId(docId);
boardDocDAOImpl.deleteData(docId);
}
@Override
public List<BoardDocDTO> list(BoardSearchDTO boardSearchDTO) {
// 1. 총 게시물 갯수
boardSearchDTO.setTotal(boardDocDAOImpl.selectCount(boardSearchDTO));
// 2. 목록
List<BoardDocDTO> list = boardDocDAOImpl.selectList(boardSearchDTO);
for (BoardDocDTO boardDocDTO : list) {
if (boardDocDTO.getCntFile() > 0) {
List<BoardFileDTO> fileList = boardFileServiceImpl.list(boardDocDTO.getDocId());
boardDocDTO.setFileList(fileList);
}
}
return list;
}
@Override
public void editByCntRead(Integer docId) {
boardDocDAOImpl.updateByCntRead(docId);
}
@Override
public List<BoardDocDTO> listByUserId(BoardSearchDTO boardSearchDTO) {
boardSearchDTO.setTotal(boardDocDAOImpl.selectCountByUserId(boardSearchDTO));
// 2. 목록
List<BoardDocDTO> list = boardDocDAOImpl.selectListByUserId(boardSearchDTO);
for (BoardDocDTO boardDocDTO : list) {
if (boardDocDTO.getCntFile() > 0) {
List<BoardFileDTO> fileList = boardFileServiceImpl.list(boardDocDTO.getDocId());
boardDocDTO.setFileList(fileList);
}
}
return list;
}
@Override
public List<BoardDocDTO> listMyUserId(Integer userId) {
// 2. 목록
List<BoardDocDTO> list = boardDocDAOImpl.selectListMyUserId(userId);
for (BoardDocDTO boardDocDTO : list) {
if (boardDocDTO.getCntFile() > 0) {
List<BoardFileDTO> fileList = boardFileServiceImpl.list(boardDocDTO.getDocId());
boardDocDTO.setFileList(fileList);
}
}
return list;
}
@Override
public List<BoardDocDTO> listTotal(BoardSearchDTO boardSearchDTO) {
boardSearchDTO.setTotal(boardDocDAOImpl.selectCountTotal(boardSearchDTO));
// 2. 목록
List<BoardDocDTO> list = boardDocDAOImpl.selectListTotal(boardSearchDTO);
for (BoardDocDTO boardDocDTO : list) {
if (boardDocDTO.getCntFile() > 0) {
List<BoardFileDTO> fileList = boardFileServiceImpl.list(boardDocDTO.getDocId());
boardDocDTO.setFileList(fileList);
}
}
return list;
}
@Override
public List<BoardDocDTO> listMyLikeY(BoardSearchDTO boardSearchDTO) {
boardSearchDTO.setLikeYn("Y");
List<BoardDocDTO> list = boardDocDAOImpl.selectListMyLike(boardSearchDTO);
for (BoardDocDTO boardDocDTO : list) {
if (boardDocDTO.getCntFile() > 0) {
List<BoardFileDTO> fileList = boardFileServiceImpl.list(boardDocDTO.getDocId());
boardDocDTO.setFileList(fileList);
}
}
return list;
}
@Override
public List<BoardDocDTO> listMyLikeN(BoardSearchDTO boardSearchDTO) {
boardSearchDTO.setLikeYn("N");
List<BoardDocDTO> list = boardDocDAOImpl.selectListMyLike(boardSearchDTO);
for (BoardDocDTO boardDocDTO : list) {
if (boardDocDTO.getCntFile() > 0) {
List<BoardFileDTO> fileList = boardFileServiceImpl.list(boardDocDTO.getDocId());
boardDocDTO.setFileList(fileList);
}
}
return list;
}
}
| true |
d197812555a16286989d6f1f519df65436c1e66b
|
Java
|
Pascal66/driemworks
|
/driemworks-ar/src/main/java/com/driemworks/ar/utils/HandDetectionUtils.java
|
UTF-8
| 636 | 2.421875 | 2 |
[
"MIT"
] |
permissive
|
package com.driemworks.ar.utils;
import android.util.Log;
import org.opencv.core.Point;
import java.util.List;
/**
* Created by Tony on 7/3/2017.
*/
public class HandDetectionUtils {
/**
*
* @param points
* @return
*/
public static Point getGunTip(List<Point> points) {
// sort by minimum y value
points = PointSortUtils.sortByMinY(points);
// get the first 5 entries in the list
List<Point> minYPoints = points.subList(0, 4);
// sort by minimum x value, return the first point of that list
return PointSortUtils.sortByMinX(minYPoints).get(0);
}
}
| true |
3dc029c3dbc30d0581b56346e62edf987c164e3d
|
Java
|
WJtoy/rptMicroservice
|
/src/main/java/com/kkl/kklplus/provider/rpt/service/CustomerChargeSummaryRptNewService.java
|
UTF-8
| 39,792 | 1.882813 | 2 |
[] |
no_license
|
package com.kkl.kklplus.provider.rpt.service;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.kkl.kklplus.entity.rpt.RPTCancelledOrderEntity;
import com.kkl.kklplus.entity.rpt.RPTCompletedOrderEntity;
import com.kkl.kklplus.entity.rpt.RPTCustomerChargeSummaryMonthlyEntity;
import com.kkl.kklplus.entity.rpt.RPTCustomerWriteOffEntity;
import com.kkl.kklplus.entity.rpt.common.RPTMiddleTableEnum;
import com.kkl.kklplus.entity.rpt.common.RPTRebuildOperationTypeEnum;
import com.kkl.kklplus.entity.rpt.search.RPTCustomerChargeSearch;
import com.kkl.kklplus.entity.rpt.web.RPTCustomer;
import com.kkl.kklplus.provider.rpt.entity.LongThreeTuple;
import com.kkl.kklplus.provider.rpt.entity.LongTwoTuple;
import com.kkl.kklplus.provider.rpt.entity.TwoTuple;
import com.kkl.kklplus.provider.rpt.mapper.CustomerChargeSummaryRptMapper;
import com.kkl.kklplus.provider.rpt.mapper.CustomerChargeSummaryRptNewMapper;
import com.kkl.kklplus.provider.rpt.ms.md.service.MSCustomerService;
import com.kkl.kklplus.provider.rpt.utils.*;
import com.kkl.kklplus.provider.rpt.utils.excel.ExportExcel;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* 客户对账单 - 工单数量与消费金额汇总
*/
@Service
@Slf4j
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public class CustomerChargeSummaryRptNewService extends RptBaseService {
@Resource
private CustomerChargeSummaryRptNewMapper customerChargeSummaryRptNewMapper;
@Autowired
private MSCustomerService msCustomerService;
@Autowired
private CompletedOrderRptService completedOrderRptService;
@Autowired
private CancelledOrderRptService cancelledOrderRptService;
@Autowired
private CustomerWriteOffRptService customerWriteOffRptService;
//endregion 公开
public RPTCustomerChargeSummaryMonthlyEntity getCustomerChargeSummaryNew(RPTCustomerChargeSearch search) {
RPTCustomerChargeSummaryMonthlyEntity result = null;
if (search != null && search.getCustomerId() != null && search.getCustomerId() > 0
&& search.getSelectedYear() != null && search.getSelectedYear() > 0
&& search.getSelectedMonth() != null && search.getSelectedMonth() > 0) {
int yearMonth = generateYearMonth(search.getSelectedYear(), search.getSelectedMonth());
int currentYearMonth = generateYearMonth(new Date());
// if (yearMonth == currentYearMonth) {
// result = getCustomerChargeSummaryMonthlyByCurrentMonth(search.getCustomerId(), search.getSelectedYear(), search.getSelectedMonth());
// } else
if (yearMonth <= currentYearMonth) {
result = getCustomerChargeSummaryMonthly(search.getCustomerId(), yearMonth);
} else {
result = new RPTCustomerChargeSummaryMonthlyEntity();
}
}
return result;
}
public void updateCustomerChargeSummaryToRptDB(int selectedYear, int selectedMonth) {
updateCustomerOrderQtyMonthlysToRptDB(selectedYear, selectedMonth);
updateCustomerFinanceMonthlysToRptDB(selectedYear, selectedMonth);
}
//region 从Web数据库获取客户的工单数量与消费金额数据
/**
* 查询所有客户的工单数量
*/
public List<RPTCustomerChargeSummaryMonthlyEntity> getCustomerOrderQtyMonthlyListFromWebDBNew(int selectedYear, int selectedMonth) {
List<RPTCustomerChargeSummaryMonthlyEntity> result = Lists.newArrayList();
Date startOfMonth = DateUtils.getStartOfDay(DateUtils.getDate(selectedYear, selectedMonth, 1));
int yearMonth = generateYearMonth(startOfMonth);
int currentYearMonth = generateYearMonth(new Date());
Date endDate;
if (yearMonth == currentYearMonth) {
endDate = DateUtils.getStartOfDay(new Date());
} else {
endDate = DateUtils.addMonth(startOfMonth, 1);
}
String quarter = QuarterUtils.getSeasonQuarter(startOfMonth);
List<RPTCustomerChargeSummaryMonthlyEntity> newQtyList = customerChargeSummaryRptNewMapper.getNewOrderQtyList(quarter, startOfMonth, endDate);
List<RPTCustomerChargeSummaryMonthlyEntity> completedQtyList = customerChargeSummaryRptNewMapper.getCompletedOrderQtyList(quarter, startOfMonth, endDate);
List<RPTCustomerChargeSummaryMonthlyEntity> returnedQtyList = customerChargeSummaryRptNewMapper.getReturnedOrderQtyList(startOfMonth, endDate);
List<RPTCustomerChargeSummaryMonthlyEntity> cancelledQtyList = customerChargeSummaryRptNewMapper.getCancelledOrderQtyList(startOfMonth, endDate);
List<RPTCustomerChargeSummaryMonthlyEntity> lastMonthUncompletedQtyList = customerChargeSummaryRptNewMapper.getUnCompletedOrderQtyList(startOfMonth);
List<RPTCustomerChargeSummaryMonthlyEntity> uncompletedQtyList = customerChargeSummaryRptNewMapper.getUnCompletedOrderQtyList(endDate);
Set<Long> customerIds = Sets.newHashSet();
Set<String> keys = Sets.newHashSet();
Map<String, Integer> newQtyMap = Maps.newHashMap();
for (RPTCustomerChargeSummaryMonthlyEntity item : newQtyList) {
String key = StringUtils.join(item.getCustomerId(), "%", item.getProductCategoryId());
keys.add(key);
customerIds.add(item.getCustomerId());
newQtyMap.put(key, item.getNewQty());
}
Map<String, Integer> completedQtyMap = Maps.newHashMap();
for (RPTCustomerChargeSummaryMonthlyEntity item : completedQtyList) {
String key = StringUtils.join(item.getCustomerId(), "%", item.getProductCategoryId());
keys.add(key);
customerIds.add(item.getCustomerId());
completedQtyMap.put(key, item.getCompletedQty());
}
Map<String, Integer> returnedQtyMap = Maps.newHashMap();
for (RPTCustomerChargeSummaryMonthlyEntity item : returnedQtyList) {
String key = StringUtils.join(item.getCustomerId(), "%", item.getProductCategoryId());
keys.add(key);
customerIds.add(item.getCustomerId());
returnedQtyMap.put(key, item.getReturnedQty());
}
Map<String, Integer> cancelledQtyMap = Maps.newHashMap();
for (RPTCustomerChargeSummaryMonthlyEntity item : cancelledQtyList) {
String key = StringUtils.join(item.getCustomerId(), "%", item.getProductCategoryId());
keys.add(key);
customerIds.add(item.getCustomerId());
cancelledQtyMap.put(key, item.getCancelledQty());
}
Map<String, Integer> lastMonthUncompletedQtyMap = Maps.newHashMap();
for (RPTCustomerChargeSummaryMonthlyEntity item : lastMonthUncompletedQtyList) {
String key = StringUtils.join(item.getCustomerId(), "%", item.getProductCategoryId());
keys.add(key);
customerIds.add(item.getCustomerId());
lastMonthUncompletedQtyMap.put(key, item.getUncompletedQty());
}
Map<String, Integer> uncompletedQtyMap = Maps.newHashMap();
for (RPTCustomerChargeSummaryMonthlyEntity item : uncompletedQtyList) {
String key = StringUtils.join(item.getCustomerId(), "%", item.getProductCategoryId());
uncompletedQtyMap.put(key, item.getUncompletedQty());
customerIds.add(item.getCustomerId());
keys.add(key);
}
RPTCustomerChargeSummaryMonthlyEntity entity;
int yearmonth = generateYearMonth(startOfMonth);
for (String key : keys) {
entity = new RPTCustomerChargeSummaryMonthlyEntity();
String[] arr = key.split("%");
entity.setCustomerId(Long.valueOf(arr[0]));
entity.setProductCategoryId(Long.valueOf(arr[1]));
entity.setYearmonth(yearmonth);
entity.setNewQty(NumberUtils.toInteger(newQtyMap.get(key)));
entity.setCompletedQty(NumberUtils.toInteger(completedQtyMap.get(key)));
entity.setReturnedQty(NumberUtils.toInteger(returnedQtyMap.get(key)));
entity.setCancelledQty(NumberUtils.toInteger(cancelledQtyMap.get(key)));
entity.setLastMonthUncompletedQty(NumberUtils.toInteger(lastMonthUncompletedQtyMap.get(key)));
entity.setUncompletedQty(NumberUtils.toInteger(uncompletedQtyMap.get(key)));
result.add(entity);
}
Map<Long, List<RPTCustomerChargeSummaryMonthlyEntity>> orderDailyMap = result.stream().collect(Collectors.groupingBy(RPTCustomerChargeSummaryMonthlyEntity::getCustomerId));
for(long customerId : customerIds){
List<RPTCustomerChargeSummaryMonthlyEntity> list = orderDailyMap.get(customerId);
RPTCustomerChargeSummaryMonthlyEntity customerEntity = new RPTCustomerChargeSummaryMonthlyEntity();
int lastMonthUncompletedQty = 0;
int newQty = 0;
int completedQty = 0;
int returnQty = 0;
int cancelQty = 0;
int uncompletedQty = 0;
for(RPTCustomerChargeSummaryMonthlyEntity item : list){
newQty = newQty + item.getNewQty();
completedQty = completedQty + item.getCompletedQty();
returnQty = returnQty + item.getReturnedQty();
cancelQty = cancelQty + item.getCancelledQty();
uncompletedQty = uncompletedQty + item.getUncompletedQty();
lastMonthUncompletedQty = lastMonthUncompletedQty + item.getLastMonthUncompletedQty();
}
customerEntity.setNewQty(newQty);
customerEntity.setCompletedQty(completedQty);
customerEntity.setReturnedQty(returnQty);
customerEntity.setCancelledQty(cancelQty);
customerEntity.setUncompletedQty(uncompletedQty);
customerEntity.setLastMonthUncompletedQty(lastMonthUncompletedQty);
customerEntity.setCustomerId(customerId);
customerEntity.setProductCategoryId(0L);
customerEntity.setYearmonth(yearmonth);
result.add(customerEntity);
}
return result;
}
/**
* 查询所有客户的消费金额
*/
private List<RPTCustomerChargeSummaryMonthlyEntity> getCustomerFinanceMonthlyListFromWebDBNew(int selectedYear, int selectedMonth) {
List<RPTCustomerChargeSummaryMonthlyEntity> result = Lists.newArrayList();
Date startOfMonth = DateUtils.getStartOfDay(DateUtils.getDate(selectedYear, selectedMonth, 1));
int yearMonth = generateYearMonth(startOfMonth);
int currentYearMonth = generateYearMonth(new Date());
Date endDate;
if (yearMonth == currentYearMonth) {
endDate = DateUtils.getStartOfDay(new Date());
} else {
endDate = DateUtils.addMonth(startOfMonth, 1);
}
String quarter = QuarterUtils.getSeasonQuarter(startOfMonth);
List<RPTCustomerChargeSummaryMonthlyEntity> rechargeAmountList = customerChargeSummaryRptNewMapper.getRechargeAmountList(quarter, startOfMonth, endDate);
List<RPTCustomerChargeSummaryMonthlyEntity> completedOrderChargeList = customerChargeSummaryRptNewMapper.getCompletedOrderAndTimelinessAndUrgentChargeList(quarter, startOfMonth, endDate);
List<RPTCustomerChargeSummaryMonthlyEntity> writeOffChargeList = customerChargeSummaryRptNewMapper.getWriteOffChargeList(quarter, startOfMonth, endDate);
List<RPTCustomerChargeSummaryMonthlyEntity> lastMonthBalanceList = customerChargeSummaryRptNewMapper.getBalanceList(startOfMonth);
List<RPTCustomerChargeSummaryMonthlyEntity> balanceList = customerChargeSummaryRptNewMapper.getBalanceList(endDate);
List<RPTCustomerChargeSummaryMonthlyEntity> blockAmountList = customerChargeSummaryRptNewMapper.getBlockAmountList(endDate);
Set<Long> customerIds = Sets.newHashSet();
Set<String> keys = Sets.newHashSet();
Map<Long, Double> rechargeAmountMap = Maps.newHashMap();
for (RPTCustomerChargeSummaryMonthlyEntity item : rechargeAmountList) {
customerIds.add(item.getCustomerId());
rechargeAmountMap.put(item.getCustomerId(), item.getRechargeAmount());
}
Map<String, RPTCustomerChargeSummaryMonthlyEntity> completedOrderAndTimelinessAndUrgentChargeMap = Maps.newHashMap();
for (RPTCustomerChargeSummaryMonthlyEntity item : completedOrderChargeList) {
customerIds.add(item.getCustomerId());
String key = StringUtils.join(item.getCustomerId(), "%", item.getProductCategoryId());
keys.add(key);
completedOrderAndTimelinessAndUrgentChargeMap.put(key, item);
}
Map<String, RPTCustomerChargeSummaryMonthlyEntity> writeOffChargeMap = Maps.newHashMap();
for (RPTCustomerChargeSummaryMonthlyEntity item : writeOffChargeList) {
customerIds.add(item.getCustomerId());
String key = StringUtils.join(item.getCustomerId(), "%", item.getProductCategoryId());
keys.add(key);
writeOffChargeMap.put(key, item);
}
Map<Long, Double> lastMonthBalanceMap = Maps.newHashMap();
for (RPTCustomerChargeSummaryMonthlyEntity item : lastMonthBalanceList) {
customerIds.add(item.getCustomerId());
lastMonthBalanceMap.put(item.getCustomerId(), item.getBalance());
}
Map<Long, Double> balanceMap = Maps.newHashMap();
for (RPTCustomerChargeSummaryMonthlyEntity item : balanceList) {
balanceMap.put(item.getCustomerId(), item.getBalance());
customerIds.add(item.getCustomerId());
}
Map<Long, Double> blockAmountMap = Maps.newHashMap();
for (RPTCustomerChargeSummaryMonthlyEntity item : blockAmountList) {
customerIds.add(item.getCustomerId());
blockAmountMap.put(item.getCustomerId(), item.getBlockAmount());
}
RPTCustomerChargeSummaryMonthlyEntity entity;
RPTCustomerChargeSummaryMonthlyEntity completedOrderCharge;
RPTCustomerChargeSummaryMonthlyEntity writeOffEntity;
double completeds;
double writes;
int yearmonth = generateYearMonth(startOfMonth);
for (String key : keys) {
completeds = 0.00;
writes = 0.00;
entity = new RPTCustomerChargeSummaryMonthlyEntity();
String[] arr = key.split("%");
entity.setCustomerId(Long.valueOf(arr[0]));
entity.setProductCategoryId(Long.valueOf(arr[1]));
entity.setYearmonth(yearmonth);
completedOrderCharge = completedOrderAndTimelinessAndUrgentChargeMap.get(key);
if (completedOrderCharge != null) {
entity.setCompletedOrderCharge(NumberUtils.toDouble(completedOrderCharge.getCompletedOrderCharge()));
entity.setTimelinessCharge(NumberUtils.toDouble(completedOrderCharge.getTimelinessCharge()));
entity.setUrgentCharge(NumberUtils.toDouble(completedOrderCharge.getUrgentCharge()));
completeds = NumberUtils.toDouble(completedOrderCharge.getPraiseFee());
}
writeOffEntity = writeOffChargeMap.get(key);
if (writeOffEntity != null) {
entity.setWriteOffCharge(NumberUtils.toDouble(writeOffEntity.getWriteOffCharge()));
writes = NumberUtils.toDouble(writeOffEntity.getPraiseFee());
}
entity.setPraiseFee(writes + completeds);
result.add(entity);
}
Map<Long, List<RPTCustomerChargeSummaryMonthlyEntity>> orderMap = result.stream().collect(Collectors.groupingBy(RPTCustomerChargeSummaryMonthlyEntity::getCustomerId));
for(Long customerId :customerIds){
List<RPTCustomerChargeSummaryMonthlyEntity> list = orderMap.get(customerId);
RPTCustomerChargeSummaryMonthlyEntity customerEntity = new RPTCustomerChargeSummaryMonthlyEntity();
double completedCharge = 0.00;
double timelinessCharge = 0.00;
double urgentCharge = 0.00;
double writeOffCharge = 0.00;
double praiseFee = 0.00;
if(list !=null){
for(RPTCustomerChargeSummaryMonthlyEntity item : list){
completedCharge = completedCharge + item.getCompletedOrderCharge();
timelinessCharge = timelinessCharge + item.getTimelinessCharge();
urgentCharge = urgentCharge + item.getUrgentCharge();
writeOffCharge = writeOffCharge + item.getWriteOffCharge();
praiseFee = praiseFee + item.getPraiseFee();
}
}
customerEntity.setRechargeAmount(NumberUtils.toDouble(rechargeAmountMap.get(customerId)));
customerEntity.setLastMonthBalance(NumberUtils.toDouble(lastMonthBalanceMap.get(customerId)));
customerEntity.setBalance(NumberUtils.toDouble(balanceMap.get(customerId)));
customerEntity.setBlockAmount(NumberUtils.toDouble(blockAmountMap.get(customerId)));
customerEntity.setCompletedOrderCharge(completedCharge);
customerEntity.setTimelinessCharge(timelinessCharge);
customerEntity.setUrgentCharge(urgentCharge);
customerEntity.setWriteOffCharge(writeOffCharge);
customerEntity.setPraiseFee(praiseFee);
customerEntity.setCustomerId(customerId);
customerEntity.setProductCategoryId(0L);
customerEntity.setYearmonth(yearmonth);
result.add(customerEntity);
}
return result;
}
private RPTCustomerChargeSummaryMonthlyEntity getCustomerChargeSummaryMonthly(long customerId, int yearmonth) {
int systemId = RptCommonUtils.getSystemId();
RPTCustomerChargeSummaryMonthlyEntity orderQtyMonthly = customerChargeSummaryRptNewMapper.getCustomerOrderQtyMonthly(systemId, customerId, yearmonth);
RPTCustomerChargeSummaryMonthlyEntity financeMonthly = customerChargeSummaryRptNewMapper.getCustomerFinanceMonthly(systemId, customerId, yearmonth);
RPTCustomerChargeSummaryMonthlyEntity result = new RPTCustomerChargeSummaryMonthlyEntity();
result.setCustomerId(customerId);
result.setYearmonth(yearmonth);
if (orderQtyMonthly != null) {
result.setLastMonthUncompletedQty(orderQtyMonthly.getLastMonthUncompletedQty());
result.setNewQty(orderQtyMonthly.getNewQty());
result.setCompletedQty(orderQtyMonthly.getCompletedQty());
result.setReturnedQty(orderQtyMonthly.getReturnedQty());
result.setCancelledQty(orderQtyMonthly.getCancelledQty());
result.setUncompletedQty(orderQtyMonthly.getUncompletedQty());
}
if (financeMonthly != null) {
result.setLastMonthBalance(financeMonthly.getLastMonthBalance());
result.setRechargeAmount(financeMonthly.getRechargeAmount());
result.setCompletedOrderCharge(financeMonthly.getCompletedOrderCharge());
result.setWriteOffCharge(financeMonthly.getWriteOffCharge());
result.setTimelinessCharge(financeMonthly.getTimelinessCharge());
result.setUrgentCharge(financeMonthly.getUrgentCharge());
result.setPraiseFee(financeMonthly.getPraiseFee());
result.setBalance(financeMonthly.getBalance());
result.setBlockAmount(financeMonthly.getBlockAmount());
}
return result;
}
//endregion 从Web数据库获取客户的工单数量与消费金额数据
//region 操作中间表
private void saveCustomerOrderQtyMonthlysToRptDB(int selectedYear, int selectedMonth) {
List<RPTCustomerChargeSummaryMonthlyEntity> list = getCustomerOrderQtyMonthlyListFromWebDBNew(selectedYear, selectedMonth);
if (!list.isEmpty()) {
int yearmonth = generateYearMonth(selectedYear, selectedMonth);
int systemId = RptCommonUtils.getSystemId();
for (RPTCustomerChargeSummaryMonthlyEntity item : list) {
item.setSystemId(systemId);
item.setYearmonth(yearmonth);
item.setCreateDt(System.currentTimeMillis());
item.setUpdateDt(System.currentTimeMillis());
customerChargeSummaryRptNewMapper.insertCustomerOrderQtyMonthly(item);
}
}
}
private void saveCustomerFinanceMonthlysToRptDB(int selectedYear, int selectedMonth) {
List<RPTCustomerChargeSummaryMonthlyEntity> list = getCustomerFinanceMonthlyListFromWebDBNew(selectedYear, selectedMonth);
if (!list.isEmpty()) {
int yearmonth = generateYearMonth(selectedYear, selectedMonth);
int systemId = RptCommonUtils.getSystemId();
for (RPTCustomerChargeSummaryMonthlyEntity item : list) {
item.setSystemId(systemId);
item.setYearmonth(yearmonth);
item.setCreateDt(System.currentTimeMillis());
item.setUpdateDt(System.currentTimeMillis());
customerChargeSummaryRptNewMapper.insertCustomerFinanceMonthly(item);
}
}
}
private Map<String, Long> getCustomerOrderQtyMonthlyIdMap(int systemId, int yearmonth) {
List<LongThreeTuple> tuples = customerChargeSummaryRptNewMapper.getCustomerOrderQtyMonthlyIds(systemId, yearmonth);
Map<String, Long> tuplesMap = Maps.newHashMap();
if (tuples != null && !tuples.isEmpty()) {
for(LongThreeTuple item : tuples ){
String key = StringUtils.join(item.getBElement(), "%", item.getCElement());
tuplesMap.put(key,item.getAElement());
}
return tuplesMap;
} else {
return tuplesMap;
}
}
private Map<String, Long> getCustomerFinanceMonthlyIdMap(int systemId, int yearmonth) {
List<LongThreeTuple> tuples = customerChargeSummaryRptNewMapper.getCustomerFinanceMonthlyIds(systemId, yearmonth);
Map<String, Long> tuplesMap = Maps.newHashMap();
if(tuples != null && !tuples.isEmpty()) {
for(LongThreeTuple item : tuples ){
String key = StringUtils.join(item.getBElement(), "%", item.getCElement());
tuplesMap.put(key,item.getAElement());
}
return tuplesMap;
} else {
return tuplesMap;
}
}
private void updateCustomerOrderQtyMonthlysToRptDB(int selectedYear, int selectedMonth) {
List<RPTCustomerChargeSummaryMonthlyEntity> list = getCustomerOrderQtyMonthlyListFromWebDBNew(selectedYear, selectedMonth);
if (!list.isEmpty()) {
int yearmonth = generateYearMonth(selectedYear, selectedMonth);
int systemId = RptCommonUtils.getSystemId();
Map<String, Long> idMap = getCustomerOrderQtyMonthlyIdMap(systemId, yearmonth);
Long primaryKeyId;
String key;
for (RPTCustomerChargeSummaryMonthlyEntity item : list) {
key = StringUtils.join(item.getCustomerId(), "%", item.getProductCategoryId());
primaryKeyId = idMap.get(key);
item.setCreateDt(System.currentTimeMillis());
item.setUpdateDt(item.getCreateDt());
if (primaryKeyId != null && primaryKeyId != 0) {
item.setId(primaryKeyId);
customerChargeSummaryRptNewMapper.updateCustomerOrderQtyMonthly(item);
} else {
item.setSystemId(systemId);
item.setYearmonth(yearmonth);
customerChargeSummaryRptNewMapper.insertCustomerOrderQtyMonthly(item);
}
}
}
}
private void updateCustomerFinanceMonthlysToRptDB(int selectedYear, int selectedMonth) {
List<RPTCustomerChargeSummaryMonthlyEntity> list = getCustomerFinanceMonthlyListFromWebDBNew(selectedYear, selectedMonth);
if (!list.isEmpty()) {
int yearmonth = generateYearMonth(selectedYear, selectedMonth);
int systemId = RptCommonUtils.getSystemId();
Map<String, Long> idMap = getCustomerFinanceMonthlyIdMap(systemId, yearmonth);
Long primaryKeyId;
String key;
for (RPTCustomerChargeSummaryMonthlyEntity item : list) {
key = StringUtils.join(item.getCustomerId(), "%", item.getProductCategoryId());
primaryKeyId = idMap.get(key);
item.setCreateDt(System.currentTimeMillis());
item.setUpdateDt(item.getCreateDt());
if (primaryKeyId != null && primaryKeyId != 0) {
item.setId(primaryKeyId);
customerChargeSummaryRptNewMapper.updateCustomerFinanceMonthly(item);
} else {
item.setSystemId(systemId);
item.setYearmonth(yearmonth);
customerChargeSummaryRptNewMapper.insertCustomerFinanceMonthly(item);
}
}
}
}
private void deleteCustomerOrderQtyMonthlysFromRptDB(int selectedYear, int selectedMonth) {
customerChargeSummaryRptNewMapper.deleteCustomerOrderQtyMonthly(RptCommonUtils.getSystemId(), generateYearMonth(selectedYear, selectedMonth));
}
private void deleteCustomerFinanceMonthlysFromRptDB(int selectedYear, int selectedMonth) {
customerChargeSummaryRptNewMapper.deleteCustomerFinanceMonthly(RptCommonUtils.getSystemId(), generateYearMonth(selectedYear, selectedMonth));
}
//endregion
//region 辅助方法
private int generateYearMonth(Date date) {
int selectedYear = DateUtils.getYear(date);
int selectedMonth = DateUtils.getMonth(date);
return generateYearMonth(selectedYear, selectedMonth);
}
private int generateYearMonth(int selectedYear, int selectedMonth) {
return StringUtils.toInteger(String.format("%04d%02d", selectedYear, selectedMonth));
}
//endregion 辅助方法
/**
* 重建中间表
*/
public boolean rebuildMiddleTableData(RPTMiddleTableEnum table, RPTRebuildOperationTypeEnum operationType, Integer selectedYear, Integer selectedMonth) {
boolean result = false;
if (table != null && operationType != null && selectedYear != null && selectedYear > 0
&& selectedMonth != null && selectedMonth > 0) {
try {
if (table == RPTMiddleTableEnum.RPT_CUSTOMER_ORDER_QTY_MONTHLY) {
switch (operationType) {
case INSERT:
saveCustomerOrderQtyMonthlysToRptDB(selectedYear, selectedMonth);
break;
case INSERT_MISSED_DATA:
updateCustomerOrderQtyMonthlysToRptDB(selectedYear, selectedMonth);
break;
case UPDATE:
deleteCustomerOrderQtyMonthlysFromRptDB(selectedYear, selectedMonth);
saveCustomerOrderQtyMonthlysToRptDB(selectedYear, selectedMonth);
break;
case DELETE:
deleteCustomerOrderQtyMonthlysFromRptDB(selectedYear, selectedMonth);
break;
}
result = true;
} else if (table == RPTMiddleTableEnum.RPT_CUSTOMER_FINANCE_MONTHLY) {
switch (operationType) {
case INSERT:
saveCustomerFinanceMonthlysToRptDB(selectedYear, selectedMonth);
break;
case INSERT_MISSED_DATA:
updateCustomerFinanceMonthlysToRptDB(selectedYear, selectedMonth);
break;
case UPDATE:
deleteCustomerFinanceMonthlysFromRptDB(selectedYear, selectedMonth);
saveCustomerFinanceMonthlysToRptDB(selectedYear, selectedMonth);
break;
case DELETE:
deleteCustomerFinanceMonthlysFromRptDB(selectedYear, selectedMonth);
break;
}
result = true;
}
} catch (Exception e) {
log.error("CustomerChargeSummaryRptService.rebuildMiddleTableData:{}", Exceptions.getStackTraceAsString(e));
}
}
return result;
}
/**
* 导出 客户对账单
*
* @return
*/
public SXSSFWorkbook exportCustomerChargeRptNew(String searchConditionJson, String reportTitle) {
RPTCustomerChargeSearch searchCondition = redisGsonService.fromJson(searchConditionJson, RPTCustomerChargeSearch.class);
RPTCustomerChargeSummaryMonthlyEntity item = getCustomerChargeSummaryNew(searchCondition);
SXSSFWorkbook xBook = null;
try {
long customerId = item.getCustomerId();
RPTCustomer customer = msCustomerService.get(customerId);
item.setCustomer(customer == null ? new RPTCustomer() : customer);
ExportExcel exportExcel = new ExportExcel();
xBook = new SXSSFWorkbook(500);
Sheet xSheet = xBook.createSheet("消费汇总");
xSheet.setDefaultColumnWidth(EXECL_CELL_WIDTH_20);
Map<String, CellStyle> xStyle = exportExcel.createStyles(xBook);
int rowIndex = 0;
Row titleRow = xSheet.createRow(rowIndex++);
titleRow.setHeightInPoints(EXECL_CELL_HEIGHT_TITLE);
ExportExcel.createCell(titleRow, 0, xStyle, ExportExcel.CELL_STYLE_NAME_TITLE, item.getCustomer().getName() + "对账单");
xSheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(), 0, 8));
Row firstRow = xSheet.createRow(rowIndex++);
firstRow.setHeightInPoints(EXECL_CELL_HEIGHT_DATA);
ExportExcel.createCell(firstRow, 0, xStyle, ExportExcel.CELL_STYLE_NAME_DATA, "提供服务公司:广东快可立服务有限公司");
xSheet.addMergedRegion(new CellRangeAddress(firstRow.getRowNum(), firstRow.getRowNum(), 0, 7));
CellRangeAddress region = new CellRangeAddress(firstRow.getRowNum(), firstRow.getRowNum(), 0, 7);
ExportExcel.setRegionBorder(region, xSheet, xBook);
ExportExcel.createCell(firstRow, 8, xStyle, ExportExcel.CELL_STYLE_NAME_DATA, "所属账期:" + searchCondition.getSelectedYear() + "年" + searchCondition.getSelectedMonth() + "月");
Row firsHeaderRow = xSheet.createRow(rowIndex++);
firsHeaderRow.setHeightInPoints(EXECL_CELL_HEIGHT_HEADER);
ExportExcel.createCell(firsHeaderRow, 0, xStyle, ExportExcel.CELL_STYLE_NAME_HEADER, "上月未完成单");
ExportExcel.createCell(firsHeaderRow, 1, xStyle, ExportExcel.CELL_STYLE_NAME_HEADER, "本月下单");
ExportExcel.createCell(firsHeaderRow, 2, xStyle, ExportExcel.CELL_STYLE_NAME_HEADER, "本月完工单");
ExportExcel.createCell(firsHeaderRow, 3, xStyle, ExportExcel.CELL_STYLE_NAME_HEADER, "本月退单");
ExportExcel.createCell(firsHeaderRow, 4, xStyle, ExportExcel.CELL_STYLE_NAME_HEADER, "本月取消单");
ExportExcel.createCell(firsHeaderRow, 5, xStyle, ExportExcel.CELL_STYLE_NAME_HEADER, "本月未完成单");
ExportExcel.createCell(firsHeaderRow, 6, xStyle, ExportExcel.CELL_STYLE_NAME_HEADER, "");
ExportExcel.createCell(firsHeaderRow, 7, xStyle, ExportExcel.CELL_STYLE_NAME_HEADER, "");
ExportExcel.createCell(firsHeaderRow, 8, xStyle, ExportExcel.CELL_STYLE_NAME_HEADER, "");
Row firstDataRow = xSheet.createRow(rowIndex++);
firstDataRow.setHeightInPoints(EXECL_CELL_HEIGHT_HEADER);
ExportExcel.createCell(firstDataRow, 0, xStyle, ExportExcel.CELL_STYLE_NAME_DATA, item.getLastMonthUncompletedQty());
ExportExcel.createCell(firstDataRow, 1, xStyle, ExportExcel.CELL_STYLE_NAME_DATA, item.getNewQty());
ExportExcel.createCell(firstDataRow, 2, xStyle, ExportExcel.CELL_STYLE_NAME_DATA, item.getCompletedQty());
ExportExcel.createCell(firstDataRow, 3, xStyle, ExportExcel.CELL_STYLE_NAME_DATA, item.getReturnedQty());
ExportExcel.createCell(firstDataRow, 4, xStyle, ExportExcel.CELL_STYLE_NAME_DATA, item.getCancelledQty());
ExportExcel.createCell(firstDataRow, 5, xStyle, ExportExcel.CELL_STYLE_NAME_DATA, item.getUncompletedQty());
ExportExcel.createCell(firstDataRow, 6, xStyle, ExportExcel.CELL_STYLE_NAME_DATA, "");
ExportExcel.createCell(firstDataRow, 7, xStyle, ExportExcel.CELL_STYLE_NAME_DATA, "");
ExportExcel.createCell(firstDataRow, 8, xStyle, ExportExcel.CELL_STYLE_NAME_DATA, "");
Row secondHeaderRow = xSheet.createRow(rowIndex++);
secondHeaderRow.setHeightInPoints(EXECL_CELL_HEIGHT_HEADER);
ExportExcel.createCell(secondHeaderRow, 0, xStyle, ExportExcel.CELL_STYLE_NAME_HEADER, "上月消费余额");
ExportExcel.createCell(secondHeaderRow, 1, xStyle, ExportExcel.CELL_STYLE_NAME_HEADER, "本月充值");
ExportExcel.createCell(secondHeaderRow, 2, xStyle, ExportExcel.CELL_STYLE_NAME_HEADER, "本月完工单金额");
ExportExcel.createCell(secondHeaderRow, 3, xStyle, ExportExcel.CELL_STYLE_NAME_HEADER, "对帐差异单(本期退补款)");
ExportExcel.createCell(secondHeaderRow, 4, xStyle, ExportExcel.CELL_STYLE_NAME_HEADER, "本月时效费");
ExportExcel.createCell(secondHeaderRow, 5, xStyle, ExportExcel.CELL_STYLE_NAME_HEADER, "本月加急费");
ExportExcel.createCell(secondHeaderRow, 6, xStyle, ExportExcel.CELL_STYLE_NAME_HEADER, "本月好评费");
ExportExcel.createCell(secondHeaderRow, 7, xStyle, ExportExcel.CELL_STYLE_NAME_HEADER, "本月消费余额");
ExportExcel.createCell(secondHeaderRow, 8, xStyle, ExportExcel.CELL_STYLE_NAME_HEADER, "未完工冻结金额");
Row secondDataRow = xSheet.createRow(rowIndex++);
secondDataRow.setHeightInPoints(EXECL_CELL_HEIGHT_HEADER);
ExportExcel.createCell(secondDataRow, 0, xStyle, ExportExcel.CELL_STYLE_NAME_DATA, item.getLastMonthBalance());
ExportExcel.createCell(secondDataRow, 1, xStyle, ExportExcel.CELL_STYLE_NAME_DATA, item.getRechargeAmount());
ExportExcel.createCell(secondDataRow, 2, xStyle, ExportExcel.CELL_STYLE_NAME_DATA, item.getCompletedOrderCharge());
ExportExcel.createCell(secondDataRow, 3, xStyle, ExportExcel.CELL_STYLE_NAME_DATA, item.getWriteOffCharge());
ExportExcel.createCell(secondDataRow, 4, xStyle, ExportExcel.CELL_STYLE_NAME_DATA, item.getTimelinessCharge());
ExportExcel.createCell(secondDataRow, 5, xStyle, ExportExcel.CELL_STYLE_NAME_DATA, item.getUrgentCharge());
ExportExcel.createCell(secondDataRow, 6, xStyle, ExportExcel.CELL_STYLE_NAME_DATA, item.getPraiseFee());
ExportExcel.createCell(secondDataRow, 7, xStyle, ExportExcel.CELL_STYLE_NAME_DATA, item.getBalance());
ExportExcel.createCell(secondDataRow, 8, xStyle, ExportExcel.CELL_STYLE_NAME_DATA, item.getBlockAmount());
StringBuilder stringBuilder = new StringBuilder();
Date queryDate = DateUtils.getDate(searchCondition.getSelectedYear(), searchCondition.getSelectedMonth(), 1);
String dayString = DateUtils.formatDate(DateUtils.getLastDayOfMonth(queryDate), "yyyy-MM-dd");
stringBuilder.append("截止到" + dayString + "," + item.getCustomer().getName());
stringBuilder.append(item.getBalance() > 0 ? "在广东快可立家电服务有限公司余额为" : "欠广东快可立家电服务有限公司服务款");
double money = Math.abs(item.getBalance());
String s = String.valueOf(money);
CurrencyUtil nf = new CurrencyUtil(s);
String bigMoney = nf.Convert();
stringBuilder.append(String.format("%.2f", money) + "元 ");
stringBuilder.append("(大写:");
stringBuilder.append(bigMoney);
stringBuilder.append(")");
// 截止到2015年3月31号易品购商贸公司欠广东快可立家电服务有限公司服务款18445元(大写:壹万捌仟肆佰肆拾伍元正)
rowIndex = rowIndex + 2;
Row remarkRow = xSheet.createRow(rowIndex++);
ExportExcel.createCell(remarkRow, 0, xStyle, ExportExcel.CELL_STYLE_NAME_DATA, stringBuilder.toString());
xSheet.addMergedRegion(new CellRangeAddress(remarkRow.getRowNum(), remarkRow.getRowNum(), 0, 7));
Row last1Row = xSheet.createRow(rowIndex++);
ExportExcel.createCell(last1Row, 7, xStyle, ExportExcel.CELL_STYLE_NAME_DATA, "确认(单位盖章):");
Row last2Row = xSheet.createRow(rowIndex++);
ExportExcel.createCell(last2Row, 7, xStyle, ExportExcel.CELL_STYLE_NAME_DATA, "日期:");
List<RPTCompletedOrderEntity> customerCompletedOrdersRptData = completedOrderRptService.getCompletedOrderList(searchCondition);
List<RPTCancelledOrderEntity> returnedOrderDetail = cancelledOrderRptService.getCancelledOrder(searchCondition);
List<RPTCustomerWriteOffEntity> WriteOffData = customerWriteOffRptService.getCustomerWriteOffList(searchCondition);
//添加完工单Sheet
if (customerCompletedOrdersRptData.size() < 2000) {
completedOrderRptService.addCustomerChargeCompleteRptSheet(xBook, xStyle, customerCompletedOrdersRptData);
} else {
completedOrderRptService.addCustomerChargeCompleteRptSheetMore2000(xBook, xStyle, customerCompletedOrdersRptData);
}
//添加退单/取消单Sheet
if (returnedOrderDetail.size() < 2000) {
cancelledOrderRptService.addCustomerChargeReturnCancelRptSheet(xBook, xStyle, returnedOrderDetail);
} else {
cancelledOrderRptService.addCustomerChargeReturnCancelRptSheetMore2000(xBook, xStyle, returnedOrderDetail);
}
//添加退补单Sheet
if (WriteOffData.size() < 2000) {
customerWriteOffRptService.addCustomerWriteOffRptSheet(xBook, xStyle, WriteOffData);
} else {
customerWriteOffRptService.addCustomerWriteOffRptSheetMore2000(xBook, xStyle, WriteOffData);
}
} catch (Exception e) {
log.error("【CustomerChargeSummaryRptNewService.exportCustomerChargeRptNew】客户对账单写入excel失败, errorMsg: {}", Exceptions.getStackTraceAsString(e));
return null;
}
return xBook;
}
}
| true |
8993332c5fac111109c937c9ba16e6552ae73119
|
Java
|
LYTWork/Practical-Training
|
/医院药品管理系统/total - 副本/src/main/java/com/java1234/service/impl/SaleListDrugsServiceImpl.java
|
UTF-8
| 2,554 | 2.078125 | 2 |
[] |
no_license
|
package com.java1234.service.impl;
import java.util.List;
import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import com.java1234.entity.PurchaseListDrugs;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import com.java1234.entity.SaleListDrugs;
import com.java1234.repository.SaleListDrugsRepository;
import com.java1234.service.SaleListDrugsService;
import com.java1234.util.StringUtil;
/*
* 销售单药品Service实现类
* @author java1234_AT
*
*/
@Service("saleListDrugsService")
public class SaleListDrugsServiceImpl implements SaleListDrugsService{
@Resource
private SaleListDrugsRepository saleListDrugsRepository;
@Override
public List<SaleListDrugs> listBySaleListId(Integer saleListId) {
return saleListDrugsRepository.listBySaleListId(saleListId);
}
@Override
public Integer getTotalByDrugsId(Integer drugsId) {
return saleListDrugsRepository.getTotalByDrugsId(drugsId)==null?0:saleListDrugsRepository.getTotalByDrugsId(drugsId);
}
@Override
public List<SaleListDrugs> list(SaleListDrugs saleListDrugs) {
return saleListDrugsRepository.findAll(new Specification<SaleListDrugs>() {
@Override
public Predicate toPredicate(Root<SaleListDrugs> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Predicate predicate=cb.conjunction();
if(saleListDrugs!=null){
if(saleListDrugs.getType()!=null && saleListDrugs.getType().getId()!=null && saleListDrugs.getType().getId()!=1){
predicate.getExpressions().add(cb.equal(root.get("type").get("id"), saleListDrugs.getType().getId()));
}
if(StringUtil.isNotEmpty(saleListDrugs.getCodeOrName())){
predicate.getExpressions().add(cb.or(cb.like(root.get("code"),"%"+saleListDrugs.getCodeOrName()+"%"), cb.like(root.get("name"),"%"+saleListDrugs.getCodeOrName()+"%")));
}
if(saleListDrugs.getSaleList()!=null && StringUtil.isNotEmpty(saleListDrugs.getSaleList().getSaleNumber())){
predicate.getExpressions().add(cb.like(root.get("saleList").get("saleNumber"), "%"+saleListDrugs.getSaleList().getSaleNumber()+"%"));
}
}
return predicate;
}
});
}
}
| true |
177979445d84577fbaf6233b2f6fe7d65c677168
|
Java
|
alexanderguk/Mad_Game
|
/src/core/gamestates/MenuState.java
|
UTF-8
| 1,863 | 2.375 | 2 |
[] |
no_license
|
package core.gamestates;
import core.model.Menu;
import core.resourcemanager.ResourceManager;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
import core.controller.MenuController;
import core.view.MenuView;
/*
* Execute start menu
* */
public class MenuState extends BasicGameState {
private static MenuState instance;
private final GameState STATE_ID = GameState.MENU;
private MenuController menuController;
private MenuView menuView;
private MenuState() {
}
public static MenuState getInstance() {
if (instance == null) {
instance = new MenuState();
}
return instance;
}
@Override
public int getID() {
return STATE_ID.getValue();
}
@Override
public void init(GameContainer gc, StateBasedGame game) throws SlickException {
}
@Override
public void render(GameContainer gc, StateBasedGame game, Graphics graphics) throws SlickException {
menuView.render(gc);
}
@Override
public void update(GameContainer gc, StateBasedGame game, int delta) throws SlickException {
menuController.update(gc, game);
}
@Override
public void enter(GameContainer gc, StateBasedGame game) throws SlickException {
ResourceManager.getInstance().load(STATE_ID);
menuController = MenuController.getInstance();
menuView = new MenuView(Menu.getInstance());
}
@Override
public void leave(GameContainer gc, StateBasedGame game) throws SlickException {
ResourceManager.getInstance().unload();
gc.getInput().clearKeyPressedRecord();
menuController = null;
menuView = null;
System.gc();
}
}
| true |
1a845b91ed1a61f3b1ad062a2dcd5ca58f2c6c2d
|
Java
|
mucahitzirek/spring-boot-subjects
|
/spring-boot-sujects/01-springbasics/src/main/java/com/godoro/springbasics/post/EditingController.java
|
UTF-8
| 859 | 2.5625 | 3 |
[] |
no_license
|
package com.godoro.springbasics.post;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class EditingController {
// http://localhost:8080/editing/employee
@GetMapping("/editing/employee")
public String getEmployee(Model model) {
Employee employee = new Employee(0, "", 0.0);
model.addAttribute("employee", employee);
return "post/EmployeeEditor";
}
@PostMapping("/editing/employee")
public String postEmployee(Model model, Employee employee) {
System.out.println("Saklaniyor " + employee.getEmployeeId() + " " + employee.getEmployeeName() + " "
+ employee.getMounthSalary());
model.addAttribute("employee", employee);
return "post/EmployeeEditor";
}
}
| true |
2704f8fbf767d72c2ad17dc1eb96a759ae8208e9
|
Java
|
tdomzal/junit-docker-rule
|
/src/main/java/pl/domzal/junit/docker/rule/wait/LogSequenceChecker.java
|
UTF-8
| 1,457 | 2.609375 | 3 |
[
"Apache-2.0"
] |
permissive
|
package pl.domzal.junit.docker.rule.wait;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* {@link StartConditionCheck} met when incoming log lines contains specified
* message sequence..
*/
public class LogSequenceChecker implements LineListener, StartConditionCheck {
private static Logger log = LoggerFactory.getLogger(LogSequenceChecker.class);
private final List<String> logSequence;
private AtomicInteger currentIndex = new AtomicInteger();
public LogSequenceChecker(List<String> logSequence) {
this.logSequence = logSequence;
}
@Override
public boolean check() {
return currentIndex.get() >= logSequence.size();
}
@Override
public String describe() {
return String.format("log sequence %s", logSequence);
}
@Override
public void after() { }
@Override
public void nextLine(String line) {
if (!check()) {
int currentLineIndex = currentIndex.get();
String waitForLine = logSequence.get(currentLineIndex);
if (line.contains(waitForLine)) {
log.info("pattern {}:'{}' found in '{}'", currentLineIndex, waitForLine, line);
currentIndex.incrementAndGet();
} else {
log.trace("pattern {}:'{}' not found", currentLineIndex, waitForLine);
}
}
}
}
| true |
cd505603934d5f21aa8bc6c8e12a2fe7a5c601dd
|
Java
|
s011208/BlogSamples
|
/app/src/main/java/yhh/blog/samples/butterknife/ButterKnifeMainActivity.java
|
UTF-8
| 1,843 | 2.046875 | 2 |
[] |
no_license
|
package yhh.blog.samples.butterknife;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import butterknife.BindArray;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnItemClick;
import yhh.blog.samples.R;
import yhh.blog.samples.butterknife.samples.BindActivityViewActivity;
import yhh.blog.samples.butterknife.samples.BindFragmentActivity;
import yhh.blog.samples.butterknife.samples.BindXMLResourceActivity;
public class ButterKnifeMainActivity extends AppCompatActivity {
@BindView(R.id.sample_list)
ListView mButterKnifeSampleList;
@BindString(R.string.butter_knife_main_activity_bind_activity_view)
String mBindActivityView;
@BindArray(R.array.butter_knife_main_activity_samples)
String[] mSamples;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_butter_knife_main);
ButterKnife.bind(this);
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, mSamples);
mButterKnifeSampleList.setAdapter(arrayAdapter);
}
@OnItemClick(R.id.sample_list)
void onItemClick(int position) {
switch (position) {
case 0:
startActivity(new Intent(this, BindActivityViewActivity.class));
break;
case 1:
startActivity(new Intent(this, BindXMLResourceActivity.class));
break;
case 2:
startActivity(new Intent(this, BindFragmentActivity.class));
break;
}
}
}
| true |
1a28b17e5b3ef186dc437ce43c240f71ba3f335b
|
Java
|
felipeparaujo/FlexibleTimeManager
|
/app/src/main/java/xyz/felipearaujo/flexibletimemanager/usecase/GetLocation.java
|
UTF-8
| 825 | 2.21875 | 2 |
[] |
no_license
|
package xyz.felipearaujo.flexibletimemanager.usecase;
import javax.inject.Inject;
import rx.Observable;
import xyz.felipearaujo.flexibletimemanager.datasource.DataSource;
import xyz.felipearaujo.flexibletimemanager.injection.BackgroundThread;
import xyz.felipearaujo.flexibletimemanager.injection.ForegroundThread;
public final class GetLocation extends UseCase {
private String id;
private DataSource mDataSource;
public GetLocation(String id,
DataSource dataSource,
BackgroundThread bgThread,
ForegroundThread fgThread) {
super(bgThread, fgThread);
this.id = id;
this.mDataSource = dataSource;
}
@Override
protected Observable buildUseCase() {
return mDataSource.getLocation(this.id);
}
}
| true |
759d8969289207fd4889e7fbe9464af200ecb2f5
|
Java
|
mkej/mongows1
|
/src/main/java/com/avsystem/mongows/dao/impl/FakeDao.java
|
UTF-8
| 755 | 2.484375 | 2 |
[] |
no_license
|
package com.avsystem.mongows.dao.impl;
import com.avsystem.mongows.dao.Dao;
import com.avsystem.mongows.data.DataObject;
import java.util.HashMap;
/**
* Created by MKej
*/
public class FakeDao<T extends DataObject> implements Dao<T> {
public static final int MAX_SIZE = 10000;
private final HashMap<String, T> objects = new HashMap<>();
@Override
public void removeAll() {
objects.clear();
}
@Override
public void save(T object) {
if (objects.size() >= MAX_SIZE) {
objects.remove(object.getId()); // to trigger hash counting
return;
}
objects.put(object.getId(), object);
}
@Override
public T load(String id) {
return objects.get(id);
}
}
| true |
603f229aca238c60a224b6dd5fadcbe191c1227a
|
Java
|
AgapovaDaria/OOPpractice
|
/src/test/java/ru/ssau/tk/forev/OOPpractice/Points/PointsTest.java
|
UTF-8
| 2,479 | 2.75 | 3 |
[] |
no_license
|
package ru.ssau.tk.forev.OOPpractice.Points;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
public class PointsTest {
private static double accuracy = 0.00005;
@Test
public void testSum() {
assertTrue(Points.equalsApproximately(Points.sum(new Point(8, 1, 0), new Point(15, 3, 2)), new Point(23, 4, 2)));
assertTrue(Points.equalsApproximately(Points.sum(new Point(10.3, 25, 16), new Point(3, 5, 4)), new Point(13.3, 30, 20)));
}
@Test
public void testSubtract() {
assertTrue(Points.equalsApproximately(Points.subtract(new Point(5, 6, 8), new Point(8, 3, 2)), new Point(-3, 3, 6)));
assertTrue(Points.equalsApproximately(Points.subtract(new Point(18.6, 50.2, 106.4), new Point(10.6, 50.1, 106.4)), new Point(8, 0.1, 0)));
}
@Test
public void testMultiply() {
assertTrue(Points.equalsApproximately(Points.multiply(new Point(6, 8, 1), new Point(2, 9, 3)), new Point(12, 72, 3)));
assertTrue(Points.equalsApproximately(Points.multiply(new Point(2.1, -3.6, 10.3), new Point(2, 9.1, 3)), new Point(4.2, -32.76, 30.9)));
}
@Test
public void testDivide() {
assertTrue(Points.equalsApproximately(Points.divide(new Point(-1.5, 6, 10), new Point(3, 3, 5)), new Point(-0.5, 2, 2)));
assertTrue(Points.equalsApproximately(Points.divide(new Point(-18, 45, 5), new Point(9, 2.5, 8)), new Point(-2, 18, 0.625)));
}
@Test
public void testEnlarge() {
assertTrue(Points.equalsApproximately(Points.enlarge(new Point(16, 0, 1.5), 1.8), new Point(28.8, 0, 2.7)));
}
@Test
public void testLength() {
assertEquals(Points.length(new Point(1, 2, 3)), Math.sqrt(14), accuracy);
}
@Test
public void testOpposite() {
assertTrue(Points.equalsApproximately(Points.opposite(new Point(8, -10, -5)), new Point(-8, 10, 5)));
}
@Test
public void testInverse() {
assertTrue(Points.equalsApproximately(Points.inverse(new Point(5, 1, -2)), new Point(0.2, 1, -0.5)));
}
@Test
public void testScalarProduct() {
assertEquals(Points.scalarProduct(new Point(5, 8, 1), new Point(4.56, -1.86, 8.16)), 16.08);
}
@Test
public void testVectorProduct() {
assertTrue(Points.equalsApproximately(Points.vectorProduct(new Point(8, 4.5, 3.2), new Point(1, 3.85, 3.67)), new Point(4.195, -26.16, 26.3)));
}
}
| true |
93310843f2479c5cbe51eb47b550f61433cd9ae5
|
Java
|
mglunafh/Programming-II-semester
|
/2012.03.23_VI/GuiCalculator/src/guicalculator/Calc.java
|
UTF-8
| 21,653 | 3.15625 | 3 |
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package guicalculator;
import java.awt.Button;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JOptionPane;
/**
*
* @author Fedor Uvarychev
*/
public class Calc extends javax.swing.JFrame {
private String currentLabel = ""; // то, что выводится в лейбл.
private int operand = 0; // операнд
private String previousOperation = ""; // знак операции
private boolean opWasPressedBefore = false; //
/**
* Creates new form Calc
*/
public Calc() {
initComponents();
setResizable(false);
sign.setText("");
NumListener numListener = new NumListener();
numButton0.addActionListener(numListener);
numButton1.addActionListener(numListener);
numButton2.addActionListener(numListener);
numButton3.addActionListener(numListener);
numButton4.addActionListener(numListener);
numButton5.addActionListener(numListener);
numButton6.addActionListener(numListener);
numButton7.addActionListener(numListener);
numButton8.addActionListener(numListener);
numButton9.addActionListener(numListener);
CleanListener cleanListener = new CleanListener();
clearButton.addActionListener(cleanListener);
OpListener opListener = new OpListener();
addButton.addActionListener(opListener);
subButton.addActionListener(opListener);
mulButton.addActionListener(opListener);
divButton.addActionListener(opListener);
EqualsListener equalsListener = new EqualsListener();
equalsButton.addActionListener(equalsListener);
SignListener signListener = new SignListener();
addButton.addActionListener(signListener);
subButton.addActionListener(signListener);
mulButton.addActionListener(signListener);
divButton.addActionListener(signListener);
}
// Работает нормально.
private class NumListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
Button button = (Button) e.getSource();
if (opWasPressedBefore) {
opWasPressedBefore = false;
label.setText("0");
currentLabel = "0";
}
if ("0".equals(currentLabel)) {
currentLabel = button.getLabel();
} else {
currentLabel += button.getLabel();
}
label.setText(currentLabel);
}
}
// Тоже работает нормально.
private class CleanListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
currentLabel = "0";
label.setText(currentLabel);
operand = 0;
opWasPressedBefore = false;
previousOperation = "";
sign.setText("");
}
}
// Берёт знак, запихивает его.
private class SignListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
Button opButton = (Button) e.getSource();
sign.setText(opButton.getLabel());
}
}
// Работа с кнопочкой "равно".
private class EqualsListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
Integer currentNum = new Integer(currentLabel);
calculate(currentNum);
currentLabel = "" + operand;
label.setText(currentLabel);
previousOperation = "";
opWasPressedBefore = true;
}
}
// Bags shall fall!
private class OpListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
Button opButton = (Button) e.getSource();
Integer currentNum = new Integer(currentLabel);
calculate(currentNum);
currentLabel = "" + operand;
label.setText(currentLabel);
previousOperation = opButton.getLabel();
opWasPressedBefore = true;
}
}
private void calculate(int currentNumber) {
switch (previousOperation) {
case "+":
operand += currentNumber;
break;
case "-":
operand -= currentNumber;
break;
case "*":
operand *= currentNumber;
break;
case "/":
if (0 == currentNumber) {
JOptionPane.showMessageDialog(rootPane, "Division by zero lol");
break;
} else {
operand /= currentNumber;
}
break;
case "":
operand = currentNumber;
break;
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jInternalFrame1 = new javax.swing.JInternalFrame();
debugLabel = new java.awt.Label();
numButton1 = new java.awt.Button();
numButton2 = new java.awt.Button();
numButton3 = new java.awt.Button();
numButton4 = new java.awt.Button();
numButton5 = new java.awt.Button();
numButton6 = new java.awt.Button();
numButton7 = new java.awt.Button();
numButton8 = new java.awt.Button();
numButton9 = new java.awt.Button();
numButton0 = new java.awt.Button();
addButton = new java.awt.Button();
label = new java.awt.Label();
subButton = new java.awt.Button();
mulButton = new java.awt.Button();
divButton = new java.awt.Button();
equalsButton = new java.awt.Button();
clearButton = new java.awt.Button();
sign = new java.awt.Label();
jInternalFrame1.setVisible(true);
debugLabel.setText("label1");
javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane());
jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout);
jInternalFrame1Layout.setHorizontalGroup(
jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jInternalFrame1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(debugLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jInternalFrame1Layout.setVerticalGroup(
jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jInternalFrame1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(debugLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
numButton1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
numButton1.setLabel("1");
numButton1.setName("");
numButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
numButton1ActionPerformed(evt);
}
});
numButton2.setLabel("2");
numButton3.setLabel("3");
numButton4.setLabel("4");
numButton5.setLabel("5");
numButton6.setLabel("6");
numButton7.setLabel("7");
numButton8.setLabel("8");
numButton9.setLabel("9");
numButton0.setLabel("0");
addButton.setActionCommand("addButton");
addButton.setLabel("+");
label.setName("");
label.setText("0");
subButton.setLabel("-");
mulButton.setLabel("*");
divButton.setLabel("/");
equalsButton.setLabel("=");
clearButton.setLabel("C");
sign.setText("label1");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(label, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(sign, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(165, 165, 165))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(mulButton, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 16, Short.MAX_VALUE)
.addComponent(divButton, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(addButton, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(subButton, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(numButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(numButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(2, 2, 2)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(numButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(numButton5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(numButton8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(numButton0, javax.swing.GroupLayout.DEFAULT_SIZE, 66, Short.MAX_VALUE)))
.addComponent(numButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(1, 1, 1)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(numButton3, javax.swing.GroupLayout.DEFAULT_SIZE, 62, Short.MAX_VALUE)
.addComponent(numButton6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(numButton9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addGap(59, 59, 59)
.addComponent(clearButton, javax.swing.GroupLayout.DEFAULT_SIZE, 97, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(equalsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(35, 35, 35))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(21, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(label, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(sign, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(19, 19, 19)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(numButton3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(numButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(numButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(clearButton, 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()
.addComponent(numButton4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(numButton7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(numButton5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(numButton6, 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)
.addComponent(numButton9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(numButton8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(numButton0, 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(36, 36, 36)
.addComponent(addButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(12, 12, 12))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(equalsButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(8, 8, 8)
.addComponent(subButton, 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.TRAILING)
.addComponent(mulButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(divButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
label.getAccessibleContext().setAccessibleName("label");
pack();
}// </editor-fold>//GEN-END:initComponents
private void numButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_numButton1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_numButton1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Calc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Calc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Calc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Calc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Calc().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private java.awt.Button addButton;
private java.awt.Button clearButton;
private java.awt.Label debugLabel;
private java.awt.Button divButton;
private java.awt.Button equalsButton;
private javax.swing.JInternalFrame jInternalFrame1;
private java.awt.Label label;
private java.awt.Button mulButton;
private java.awt.Button numButton0;
private java.awt.Button numButton1;
private java.awt.Button numButton2;
private java.awt.Button numButton3;
private java.awt.Button numButton4;
private java.awt.Button numButton5;
private java.awt.Button numButton6;
private java.awt.Button numButton7;
private java.awt.Button numButton8;
private java.awt.Button numButton9;
private java.awt.Label sign;
private java.awt.Button subButton;
// End of variables declaration//GEN-END:variables
}
| true |
a0f66d7b3ebf27236b85efcd707f0603c952ffbd
|
Java
|
anirudh985/ScavengersWorld
|
/app/src/main/java/com/example/aj/scavengersworld/Activities/HuntsFeed/MyPopularHuntsRecyclerViewAdapter.java
|
UTF-8
| 3,875 | 2.3125 | 2 |
[] |
no_license
|
package com.example.aj.scavengersworld.Activities.HuntsFeed;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import com.example.aj.scavengersworld.DatabaseModels.SearchableHunt;
import com.example.aj.scavengersworld.R;
import static com.example.aj.scavengersworld.Constants.POPULARITY_THRESHOLD;
import java.util.List;
public class MyPopularHuntsRecyclerViewAdapter extends RecyclerView.Adapter<MyPopularHuntsRecyclerViewAdapter.ViewHolder> {
private final List<SearchableHunt> mValues;
private final PopularHuntsFeedFragment.OnListFragmentInteractionListener mListener;
private final ColorGenerator mGenerator = ColorGenerator.MATERIAL;
public MyPopularHuntsRecyclerViewAdapter(List<SearchableHunt> items, PopularHuntsFeedFragment.OnListFragmentInteractionListener listener) {
mValues = items;
mListener = listener;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_popularhuntsfeed, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
//TODO: need to change this later
final SearchableHunt popularHunt = mValues.get(position);
// holder.mProgressView.setText(progressMessage + String.valueOf(hunt.getProgress()));
holder.mContentView.setText(popularHunt.getHuntName());
// holder.mCreatedUserView.setText(hunt.getCreatedByUserId());
holder.mRatingBar.setRating(getRating(popularHunt));
String letter = String.valueOf(popularHunt.getHuntName().charAt(0));
TextDrawable drawable = TextDrawable.builder()
.buildRound(letter, mGenerator.getRandomColor());
holder.mImageLetter.setImageDrawable(drawable);
holder.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
// mListener.onListFragmentInteraction(holder.);
mListener.onListPopularHuntsFragmentInteraction(popularHunt);
}
}
});
}
@Override
public int getItemCount() {
return mValues.size();
}
private float getRating(SearchableHunt popularHunt){
return popularHunt.getNumberOfPlayers()/POPULARITY_THRESHOLD >= 1 ? 5.0f : (popularHunt.getNumberOfPlayers()/POPULARITY_THRESHOLD)*5.0f;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mContentView;
public final ImageView mImageLetter;
// public final TextView mCreatedUserView;
public final RatingBar mRatingBar;
public ViewHolder(View view) {
super(view);
mView = view;
mContentView = (TextView) view.findViewById(R.id.popularHuntsName);
mImageLetter = (ImageView) view.findViewById(R.id.popularHuntsImageLetter);
// mCreatedUserView = (TextView) view.findViewById(R.id.popularHuntsCreatedUser);
mRatingBar = (RatingBar) view.findViewById(R.id.popularityRatingBar);
}
@Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
| true |
084517a8baccdf4946b6c9fcbf4071f7fe16cb87
|
Java
|
apache/hadoop
|
/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/HATestUtil.java
|
UTF-8
| 1,630 | 1.726563 | 2 |
[
"CC-PDDC",
"CC0-1.0",
"CC-BY-3.0",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"CDDL-1.0",
"GCC-exception-3.1",
"MIT",
"EPL-1.0",
"Classpath-exception-2.0",
"BSD-3-Clause",
"GPL-2.0-only",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-jdom",
"CDDL-1.1",
"BSD-2-Clause",
"LicenseRef-scancode-unknown"
] |
permissive
|
/**
* 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.
*/
package org.apache.hadoop.yarn.server.resourcemanager;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.net.ServerSocketUtil;
import org.apache.hadoop.yarn.conf.HAUtil;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import java.io.IOException;
public class HATestUtil {
public static void setRpcAddressForRM(String rmId, int base,
Configuration conf) throws IOException {
for (String confKey : YarnConfiguration.getServiceAddressConfKeys(conf)) {
setConfForRM(rmId, confKey, "0.0.0.0:" + ServerSocketUtil.getPort(base +
YarnConfiguration.getRMDefaultPortNumber(confKey, conf), 10), conf);
}
}
public static void setConfForRM(String rmId, String prefix, String value,
Configuration conf) {
conf.set(HAUtil.addSuffix(prefix, rmId), value);
}
}
| true |
1ae2ad9f68d41dc159457c83216f42981862189c
|
Java
|
kbalbertyu/ContentCrawler
|
/src/main/java/jp/btimes/source/Asahi.java
|
UTF-8
| 3,886 | 2.234375 | 2 |
[] |
no_license
|
package jp.btimes.source;
import cn.btimes.model.common.Article;
import cn.btimes.model.common.BTExceptions.PastDateException;
import cn.btimes.model.common.CSSQuery;
import cn.btimes.model.common.Category;
import cn.btimes.model.common.Image;
import cn.btimes.utils.Common;
import com.amzass.utils.common.Constants;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.WebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
/**
* @author <a href="mailto:[email protected]">Albert Yu</a> 2020/4/19 22:08
*/
public class Asahi extends Source {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private static final int MAX_PAST_DAYS = 1;
private static final Map<String, Category> URLS = new HashMap<>();
static {
URLS.put("http://www.asahi.com/business/list/", Category.FINANCE_JP);
URLS.put("https://www.asahi.com/national/list/", Category.SOCIETY_JP);
URLS.put("https://www.asahi.com/politics/list/", Category.SOCIETY_JP);
URLS.put("http://www.asahi.com/international/list/", Category.INTL_SCIENCE_JP);
URLS.put("http://www.asahi.com/tech_science/list/", Category.INTL_SCIENCE_JP);
URLS.put("http://www.asahi.com/apital/medicalnews/list.html?iref=com_api_med_medicalnewstop", Category.INTL_SCIENCE_JP);
URLS.put("http://www.asahi.com/culture/list/?iref=com_cultop_all_list", Category.GENERAL_JP);
}
@Override
protected Map<String, Category> getUrls() {
return URLS;
}
@Override
protected String getDateRegex() {
return "\\d{1,2}/\\d{1,2}";
}
@Override
protected String getDateFormat() {
return "MM/dd";
}
@Override
protected CSSQuery getCSSQuery() {
return new CSSQuery(".Section > ul.List > li", ".ArticleText", "a", "",
"", ".Time");
}
@Override
protected int getSourceId() {
return 2;
}
@Override
protected List<Article> parseList(Document doc) {
List<Article> articles = new ArrayList<>();
Elements list = this.readList(doc);
int i = 0;
for (Element row : list) {
try {
Article article = new Article();
this.parseTitle(row, article);
String title = StringUtils.removePattern(article.getTitle(), "\\(\\d{1,2}/\\d{1,2}\\)");
article.setTitle(title);
this.parseDate(row, article);
articles.add(article);
} catch (PastDateException e) {
if (i++ < Constants.MAX_REPEAT_TIMES) {
continue;
}
logger.warn("Article that past {} minutes detected, complete the list fetching: ", config.getMaxPastMinutes(), e);
break;
}
}
return articles;
}
@Override
protected Date parseDateText(String timeText) {
return this.parseDateTextWithDay(timeText, this.getDateRegex(), this.getDateFormat(), MAX_PAST_DAYS);
}
@Override
protected void readArticle(WebDriver driver, Article article) {
this.readContent(driver, article);
Document doc = Jsoup.parse(driver.getPageSource());
Elements imageElms = doc.select(".ImagesMod > .Image > ul.Thum img");
if (imageElms.size() == 0) {
return;
}
List<Image> images = article.getContentImages();
for (Element imageElm : imageElms) {
String src = imageElm.attr("src");
src = StringUtils.replace(src, "L.", ".");
String absSrc = Common.getAbsoluteUrl(src, article.getUrl());
Image image = new Image(absSrc, "");
images.add(image);
}
}
}
| true |
99f0241dc8208cec0b728c053c93d73ba6f2ef7b
|
Java
|
viktor-235/SafeNote
|
/src/main/java/com/viktor235/safenote/delegator/Thingable.java
|
UTF-8
| 134 | 1.789063 | 2 |
[] |
no_license
|
package com.viktor235.safenote.delegator;
/**
* Created by User on 17.07.2017.
*/
public interface Thingable {
void thing();
}
| true |
b84c33d7ef2b7164bc6b5723dacae1bf46df51c8
|
Java
|
RuudyLee/MapTest
|
/app/src/main/java/com/example/maptest/VehicleActivity.java
|
UTF-8
| 7,275 | 2.15625 | 2 |
[] |
no_license
|
package com.example.maptest;
import android.*;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.model.LatLng;
public class VehicleActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
public static final String TAG = VehicleActivity.class.getSimpleName();
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private LatLng previousLatLng = null;
private long previousTime;
private float x = 0;
private float y = 0;
private float z = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vehicle);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(1 * 1000) // 1 seconds
.setFastestInterval(1 * 1000); // 1 second
previousTime = SystemClock.elapsedRealtime();
}
@Override
protected void onResume() {
super.onResume();
mGoogleApiClient.connect();
}
@Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
/*
* GoogleApiClient Method
*/
@Override
public void onConnected(@Nullable Bundle bundle) {
Log.i(TAG, "Location services connected.");
Location location = null;
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else {
handleNewLocation(location);
}
}
/*
* GoogleApiClient Method
*/
@Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Location services suspended. Please reconnect.");
}
/*
* GoogleApiClient Method
*/
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start Activity that tries to resolve error
connectionResult.startResolutionForResult(this, 9000);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
@Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
public void handleNewLocation(Location location) {
double currentLat = location.getLatitude();
double currentLong = location.getLongitude();
LatLng latLng = new LatLng(currentLat, currentLong);
// exit if no previous location was stored
if (previousLatLng == null) {
previousLatLng = latLng;
previousTime = SystemClock.elapsedRealtime();
return;
}
// Calculate speed
double speed = getSpeed(latLng);
// Display
TextView speedText = (TextView) findViewById(R.id.vehicleSpeed);
String cSpeedInString = String.valueOf(speed);
String cToDisplay = "Speed by Calculation: " + cSpeedInString.substring(0, cSpeedInString.indexOf(".") + 2);
speedText.setText(cToDisplay);
TextView formulaText = (TextView) findViewById(R.id.formulaSpeed);
String fSpeedInString = String.valueOf(location.getSpeed());
String fToDisplay = "Speed by Formula: " + fSpeedInString.substring(0, fSpeedInString.indexOf(".") + 2);
formulaText.setText(fToDisplay);
}
public double getSpeed(LatLng currentLatLng) {
// radius of earth in metres
double r = 6371000;
// P
double lat1 = Math.toRadians(previousLatLng.latitude);
double lon1 = Math.toRadians(previousLatLng.longitude);
double rho1 = r * Math.cos(lat1);
double z1 = r * Math.sin(lat1);
double x1 = rho1 * Math.cos(lon1);
double y1 = rho1 * Math.sin(lon1);
// Q
double lat2 = Math.toRadians(currentLatLng.latitude);
double lon2 = Math.toRadians(currentLatLng.longitude);
double rho2 = r * Math.cos(lat2);
double z2 = r * Math.sin(lat2);
double x2 = rho2 * Math.cos(lon2);
double y2 = rho2 * Math.sin(lon2);
// Dot product
double dot = (x1 * x2 + y1 * y2 + z1 * z2);
double cos_theta = dot / (r * r);
double theta = Math.acos(cos_theta);
// calculate speed
double dist = r * theta;
long time_s = (SystemClock.elapsedRealtime() - previousTime) / 1000;
double speed_mps = dist / time_s;
// update frame values
previousLatLng = currentLatLng;
previousTime = SystemClock.elapsedRealtime();
return speed_mps * 3.6;
}
/////////////
// BUTTONS //
/////////////
public void healthPressed(View view) {
Intent intent = new Intent(this, HealthActivity.class);
startActivity(intent);
}
public void mapsPressed(View view) {
Intent intent = new Intent(this, MapsActivity.class);
startActivity(intent);
}
public void mediaPressed(View view) {
Intent intent = new Intent(this, MediaActivity.class);
startActivity(intent);
}
public void infoPressed(View view) {
Intent intent = new Intent(this, InfoActivity.class);
startActivity(intent);
}
public void settingsPressed(View view) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
}
}
| true |