blob_id stringlengths 40 40 | __id__ int64 225 39,780B | directory_id stringlengths 40 40 | path stringlengths 6 313 | content_id stringlengths 40 40 | detected_licenses list | license_type stringclasses 2
values | repo_name stringlengths 6 132 | repo_url stringlengths 25 151 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 70 | visit_date timestamp[ns] | revision_date timestamp[ns] | committer_date timestamp[ns] | github_id int64 7.28k 689M ⌀ | star_events_count int64 0 131k | fork_events_count int64 0 48k | gha_license_id stringclasses 23
values | gha_fork bool 2
classes | gha_event_created_at timestamp[ns] | gha_created_at timestamp[ns] | gha_updated_at timestamp[ns] | gha_pushed_at timestamp[ns] | gha_size int64 0 40.4M ⌀ | gha_stargazers_count int32 0 112k ⌀ | gha_forks_count int32 0 39.4k ⌀ | gha_open_issues_count int32 0 11k ⌀ | gha_language stringlengths 1 21 ⌀ | gha_archived bool 2
classes | gha_disabled bool 1
class | content stringlengths 7 4.37M | src_encoding stringlengths 3 16 | language stringclasses 1
value | length_bytes int64 7 4.37M | extension stringclasses 24
values | filename stringlengths 4 174 | language_id stringclasses 1
value | entities list | contaminating_dataset stringclasses 0
values | malware_signatures list | redacted_content stringlengths 7 4.37M | redacted_length_bytes int64 7 4.37M | alphanum_fraction float32 0.25 0.94 | alpha_fraction float32 0.25 0.94 | num_lines int32 1 84k | avg_line_length float32 0.76 99.9 | std_line_length float32 0 220 | max_line_length int32 5 998 | is_vendor bool 2
classes | is_generated bool 1
class | max_hex_length int32 0 319 | hex_fraction float32 0 0.38 | max_unicode_length int32 0 408 | unicode_fraction float32 0 0.36 | max_base64_length int32 0 506 | base64_fraction float32 0 0.5 | avg_csv_sep_count float32 0 4 | is_autogen_header bool 1
class | is_empty_html bool 1
class | shard stringclasses 16
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2a26807128181efb4c1be33cf59e830faf1e911a | 36,189,394,463,911 | 7bf187ed40cac92e5b44f9d798d86b2850ae82a8 | /service-sys-offdct-provider/src/main/java/com/xrlj/servicesysoffdct/common/officeclient/OfficeClient.java | 6fddfc65be40352f153fd743d7ec391c1216790e | [] | no_license | xrlj/service-sys-offdct | https://github.com/xrlj/service-sys-offdct | bc474f7887aeb726e2ef663f0fa9e6da35bb8b28 | 16946d2de896030e928d57c0931ba0bb56e85817 | refs/heads/master | 2022-07-13T20:50:07.920000 | 2022-06-17T08:50:27 | 2022-06-17T08:50:27 | 196,414,964 | 0 | 1 | null | false | 2022-03-08T21:29:20 | 2019-07-11T14:54:43 | 2021-07-14T07:39:26 | 2022-03-08T21:29:19 | 80,109 | 0 | 1 | 2 | Java | false | false | package com.xrlj.servicesysoffdct.common.officeclient;
import com.itextpdf.io.image.ImageType;
import com.xrlj.servicesysoffdct.common.ImgType;
import java.io.File;
import java.util.List;
import java.util.Map;
public interface OfficeClient {
OfficeClientType getOfficeClientType();
/**
* doc转pdf。
* @param docPath doc文件路径。本地绝对路径或者网络路径。
* @return 返回生成后的pdf文件或者返回null
*/
File docToPdf(String docPath);
/**
* doc按模板填充,导出。
* @param docTemplatePath doc模板本地绝对路径或者网络路径。
* @param data 模板待渲染数据
* @return 返回渲染后doc文件或者返回null
*/
File genDocByTemplate(String docTemplatePath, Map data);
/**
* pdf转图片。目前实现转成jpg或者png格式。
* @param pdfPath
* @param page 转换指定页,null则转换全部页码
* @param resolution 图片解析度,默认300
* @param imgType
* @return
*/
List<File> pdfToImg(String pdfPath, Integer page, Integer resolution, ImgType imgType) throws Exception;
}
| UTF-8 | Java | 1,162 | java | OfficeClient.java | Java | [] | null | [] | package com.xrlj.servicesysoffdct.common.officeclient;
import com.itextpdf.io.image.ImageType;
import com.xrlj.servicesysoffdct.common.ImgType;
import java.io.File;
import java.util.List;
import java.util.Map;
public interface OfficeClient {
OfficeClientType getOfficeClientType();
/**
* doc转pdf。
* @param docPath doc文件路径。本地绝对路径或者网络路径。
* @return 返回生成后的pdf文件或者返回null
*/
File docToPdf(String docPath);
/**
* doc按模板填充,导出。
* @param docTemplatePath doc模板本地绝对路径或者网络路径。
* @param data 模板待渲染数据
* @return 返回渲染后doc文件或者返回null
*/
File genDocByTemplate(String docTemplatePath, Map data);
/**
* pdf转图片。目前实现转成jpg或者png格式。
* @param pdfPath
* @param page 转换指定页,null则转换全部页码
* @param resolution 图片解析度,默认300
* @param imgType
* @return
*/
List<File> pdfToImg(String pdfPath, Integer page, Integer resolution, ImgType imgType) throws Exception;
}
| 1,162 | 0.686837 | 0.683652 | 38 | 23.789474 | 22.267698 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.368421 | false | false | 9 |
474cdcade2f7d8e240abeca5a6571e3ce1668c43 | 12,017,318,562,121 | 54fadc5d6ba59cfcfb0beabbc73bdef482a4bdaa | /hl/zjc/src/project/java/com/zjc/goods/service/ZjcGoodsAttributeService.java | 5b3f7f3629d848bf9187aa3c4218690b17696a2f | [] | no_license | chenshaobo2018/a1xiongmao | https://github.com/chenshaobo2018/a1xiongmao | b9ec22784e4760f3328ef63358862ca4d8f769ec | e158708f567a5f8335adda8ceaff8ad5d48031ac | refs/heads/master | 2020-05-16T08:25:09.656000 | 2019-04-27T11:09:49 | 2019-04-27T11:09:49 | 182,678,821 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package com.zjc.goods.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import aos.framework.core.dao.SqlDao;
import aos.framework.core.typewrap.Dto;
import aos.framework.core.typewrap.Dtos;
import aos.framework.core.utils.AOSJson;
import aos.framework.core.utils.AOSUtils;
import aos.framework.web.router.HttpModel;
import aos.system.common.id.IdService;
import aos.system.common.utils.SystemCons;
import com.zjc.goods.dao.ZjcGoodsAttributeDao;
import com.zjc.goods.dao.po.ZjcGoodsAttributePO;
/**
* 商品属性管理
*
* @author Administrator
*
*/
@Service(value="zjcGoodsAttributeService")
public class ZjcGoodsAttributeService {
@Autowired
private SqlDao sqlDao;
@Autowired
private IdService idService;
@Autowired
private ZjcGoodsAttributeDao zjcGoodsAttributeDao;
/**
* 初始化商品规格
* @param httpModel
*/
public void initGoodsAttribute(HttpModel httpModel){
httpModel.setViewPath("project/zjc/goodsManaer/goodsAttribute.jsp");
}
/**
* 查询商品属性
* @param httpModel
*/
public void listGoodsAttribute(HttpModel httpModel){
Dto qDto = httpModel.getInDto();
List<Dto> attributeDtos = sqlDao.list("com.zjc.goods.dao.ZjcGoodsAttributeDao.listAndTypePage", qDto);
httpModel.setOutMsg(AOSJson.toGridJson(attributeDtos, qDto.getPageTotal()));
}
/**
* 新增商品属性
* @param httpModel
*/
public void saveGoodsAttribute(HttpModel httpModel){
Dto outDto = Dtos.newOutDto();
Dto inDto = httpModel.getInDto();
ZjcGoodsAttributePO zjcGoodsAttributePO = new ZjcGoodsAttributePO();
zjcGoodsAttributePO.copyProperties(inDto);
zjcGoodsAttributePO.setAttr_id(idService.nextValue(SystemCons.SEQ.SEQ_SYSTEM).intValue());
zjcGoodsAttributeDao.insert(zjcGoodsAttributePO);
//cacheMasterDataService.cacheParamOption(aos_paramsPO.getParams_key(), aos_paramsPO.getValue());
outDto.setAppMsg("商品属性新增成功");
httpModel.setOutMsg(AOSJson.toJson(outDto));
}
/**
* 修改商品属性
* @param httpModel
*/
public void upDateGoodsAttribute(HttpModel httpModel){
Dto outDto = Dtos.newOutDto();
Dto inDto = httpModel.getInDto();
//ZjcGoodsAttributePO zjcGoodsAttributeOldPO = zjcGoodsAttributeDao.selectByKey(inDto.getInteger("attr_id"));
ZjcGoodsAttributePO zjcGoodsAttributePO = new ZjcGoodsAttributePO();
zjcGoodsAttributePO.copyProperties(inDto);
zjcGoodsAttributeDao.updateByKey(zjcGoodsAttributePO);
outDto.setAppMsg("商品属性修改成功");
httpModel.setOutMsg(AOSJson.toJson(outDto));
}
/**
* 删除商品属性
* @param httpModel
*/
public void deleteGoodsAttribute(HttpModel httpModel){
String[] selectionIds = httpModel.getInDto().getRows();
int rows = 0;
for (String attr_id : selectionIds) {
//ZjcGoodsAttributePO zjcGoodsAttributePO = zjcGoodsAttributeDao.selectByKey(Integer.valueOf(attr_id));
zjcGoodsAttributeDao.deleteByKey(Integer.valueOf(attr_id));
//cacheMasterDataService.delParamOption(aos_paramsPO.getParams_key());
rows++;
}
httpModel.setOutMsg(AOSUtils.merge("操作成功,成功删除[{0}]条商品属性。", rows));
}
/**
* 不分页列表查询。
* @param httpModel
*/
public void getGoodsAttributeList(HttpModel httpModel){
Dto qDto = httpModel.getInDto();
List<Dto> attributeDtos = sqlDao.list("com.zjc.goods.dao.ZjcGoodsAttributeDao.list", qDto);
httpModel.setOutMsg(AOSJson.toGridJson(attributeDtos, qDto.getPageTotal()));
}
}
| UTF-8 | Java | 3,650 | java | ZjcGoodsAttributeService.java | Java | [
{
"context": "odsAttributePO;\r\n\r\n/**\r\n * 商品属性管理\r\n * \r\n * @author Administrator\r\n *\r\n */\r\n@Service(value=\"zjcGoodsAttributeServic",
"end": 671,
"score": 0.9747406244277954,
"start": 658,
"tag": "NAME",
"value": "Administrator"
}
] | null | [] | /**
*
*/
package com.zjc.goods.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import aos.framework.core.dao.SqlDao;
import aos.framework.core.typewrap.Dto;
import aos.framework.core.typewrap.Dtos;
import aos.framework.core.utils.AOSJson;
import aos.framework.core.utils.AOSUtils;
import aos.framework.web.router.HttpModel;
import aos.system.common.id.IdService;
import aos.system.common.utils.SystemCons;
import com.zjc.goods.dao.ZjcGoodsAttributeDao;
import com.zjc.goods.dao.po.ZjcGoodsAttributePO;
/**
* 商品属性管理
*
* @author Administrator
*
*/
@Service(value="zjcGoodsAttributeService")
public class ZjcGoodsAttributeService {
@Autowired
private SqlDao sqlDao;
@Autowired
private IdService idService;
@Autowired
private ZjcGoodsAttributeDao zjcGoodsAttributeDao;
/**
* 初始化商品规格
* @param httpModel
*/
public void initGoodsAttribute(HttpModel httpModel){
httpModel.setViewPath("project/zjc/goodsManaer/goodsAttribute.jsp");
}
/**
* 查询商品属性
* @param httpModel
*/
public void listGoodsAttribute(HttpModel httpModel){
Dto qDto = httpModel.getInDto();
List<Dto> attributeDtos = sqlDao.list("com.zjc.goods.dao.ZjcGoodsAttributeDao.listAndTypePage", qDto);
httpModel.setOutMsg(AOSJson.toGridJson(attributeDtos, qDto.getPageTotal()));
}
/**
* 新增商品属性
* @param httpModel
*/
public void saveGoodsAttribute(HttpModel httpModel){
Dto outDto = Dtos.newOutDto();
Dto inDto = httpModel.getInDto();
ZjcGoodsAttributePO zjcGoodsAttributePO = new ZjcGoodsAttributePO();
zjcGoodsAttributePO.copyProperties(inDto);
zjcGoodsAttributePO.setAttr_id(idService.nextValue(SystemCons.SEQ.SEQ_SYSTEM).intValue());
zjcGoodsAttributeDao.insert(zjcGoodsAttributePO);
//cacheMasterDataService.cacheParamOption(aos_paramsPO.getParams_key(), aos_paramsPO.getValue());
outDto.setAppMsg("商品属性新增成功");
httpModel.setOutMsg(AOSJson.toJson(outDto));
}
/**
* 修改商品属性
* @param httpModel
*/
public void upDateGoodsAttribute(HttpModel httpModel){
Dto outDto = Dtos.newOutDto();
Dto inDto = httpModel.getInDto();
//ZjcGoodsAttributePO zjcGoodsAttributeOldPO = zjcGoodsAttributeDao.selectByKey(inDto.getInteger("attr_id"));
ZjcGoodsAttributePO zjcGoodsAttributePO = new ZjcGoodsAttributePO();
zjcGoodsAttributePO.copyProperties(inDto);
zjcGoodsAttributeDao.updateByKey(zjcGoodsAttributePO);
outDto.setAppMsg("商品属性修改成功");
httpModel.setOutMsg(AOSJson.toJson(outDto));
}
/**
* 删除商品属性
* @param httpModel
*/
public void deleteGoodsAttribute(HttpModel httpModel){
String[] selectionIds = httpModel.getInDto().getRows();
int rows = 0;
for (String attr_id : selectionIds) {
//ZjcGoodsAttributePO zjcGoodsAttributePO = zjcGoodsAttributeDao.selectByKey(Integer.valueOf(attr_id));
zjcGoodsAttributeDao.deleteByKey(Integer.valueOf(attr_id));
//cacheMasterDataService.delParamOption(aos_paramsPO.getParams_key());
rows++;
}
httpModel.setOutMsg(AOSUtils.merge("操作成功,成功删除[{0}]条商品属性。", rows));
}
/**
* 不分页列表查询。
* @param httpModel
*/
public void getGoodsAttributeList(HttpModel httpModel){
Dto qDto = httpModel.getInDto();
List<Dto> attributeDtos = sqlDao.list("com.zjc.goods.dao.ZjcGoodsAttributeDao.list", qDto);
httpModel.setOutMsg(AOSJson.toGridJson(attributeDtos, qDto.getPageTotal()));
}
}
| 3,650 | 0.738136 | 0.737564 | 114 | 28.68421 | 28.048929 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.526316 | false | false | 9 |
e7345082b1ed13ed6b9fb0d03cab65cea9baec89 | 37,177,236,930,176 | 70d64d5004ef9c59be742d9d0805c5ebecb23555 | /src/DB/BDD.java | 22f4876f9a8ce9c1da0642f09110348c00628258 | [] | no_license | abdoubouddine/-Application-de-gestion-du-recouvrement | https://github.com/abdoubouddine/-Application-de-gestion-du-recouvrement | 319d01b2bd7509bce5c5f526d377704236fca61b | 026d0515be8e4d4d48207743159d923674656322 | refs/heads/master | 2023-06-07T14:42:54.208000 | 2021-07-01T14:21:41 | 2021-07-01T14:21:41 | 382,058,433 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package DB;
import java.net.Socket;
import java.sql.*;
public class BDD {
Connection connection;
Statement statement;
String SQL;
String url;
Socket client;
public BDD(String url) {
this.url = url;
}
public Connection connexionDatabase() {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager.getConnection(url);
}
catch (Exception e) {
System.err.println(e);
}
return connection;
}
public Connection closeconnexion() {
try {
connection.close();
}
catch (Exception e) {
System.err.println(e);
}
return connection;
}
public ResultSet exécutionQuery(String sql) {
connexionDatabase();
ResultSet resultSet = null;
try {
statement = connection.createStatement();
resultSet = statement.executeQuery(sql);
System.out.println(sql);
}
catch (SQLException ex) {
System.err.println(ex);
}
return resultSet;
}
public String exécutionUpdate(String sql) {
connexionDatabase();
String result = "";
try {
statement = connection.createStatement();
statement.executeUpdate(sql);
result = sql;
} catch (SQLException ex) {
result = ex.toString();
}
return result;
}
public ResultSet querySelectAll(String nomTable) {
connexionDatabase();
SQL = "SELECT * FROM " + nomTable;
return this.exécutionQuery(SQL);
}
public ResultSet querySelectAll(String nomTable, String état) {
connexionDatabase();
SQL = "SELECT * FROM " + nomTable + " WHERE " + état;
return this.exécutionQuery(SQL);
}
public ResultSet querySelect(String[] nomColonne, String nomTable) {
connexionDatabase();
int i;
SQL = "SELECT ";
for (i = 0; i <= nomColonne.length - 1; i++) {
SQL += nomColonne[i];
if (i < nomColonne.length - 1) {
SQL += ",";
}
}
SQL += " FROM " + nomTable;
return this.exécutionQuery(SQL);
}
public ResultSet fcSelectCommand(String[] nomColonne, String nomTable, String état) {
connexionDatabase();
int i;
SQL = "SELECT ";
for (i = 0; i <= nomColonne.length - 1; i++) {
SQL += nomColonne[i];
if (i < nomColonne.length - 1) {
SQL += ",";
}
}
SQL += " FROM " + nomTable + " WHERE " + état;
return this.exécutionQuery(SQL);
}
public ResultSet fbSelectCommand(String[] nomColonne, String[] nomTable, Object[] état) {
connexionDatabase();
int i;
SQL = "SELECT ";
for (i = 0; i <= nomColonne.length - 1; i++) {
SQL += nomColonne[i];
if (i < nomColonne.length - 1) {
SQL += ",";
}
}
SQL+= "FROM " ;
for (i = 0; i <= nomTable.length - 1; i++) {
SQL += nomTable[i] ;
if (i < nomTable.length - 1) {
SQL += ",";
}
}
SQL+= " WHERE ";
for (i = 0; i <= état.length - 1; i++) {
SQL += état[i] ;
if (i < état.length - 1) {
SQL += " AND ";
}
}
return this.exécutionQuery(SQL);
}
public ResultSet ijSelectCommand(String[] nomColonne, String[] nomTable, Object[] état) {
connexionDatabase();
int i;
SQL = "SELECT ";
for (i = 0; i <= nomColonne.length - 1; i++) {
SQL += nomColonne[i];
if (i < nomColonne.length - 1) {
SQL += ",";
}
}
SQL+= "FROM " + nomTable[0] + " INNER JOIN " + nomTable[1] +" ON "+ état[0] + " WHERE " + état[1] ;
return this.exécutionQuery(SQL);
}
public String queryInsert(String nomTable, Object[] contenuTableau) {
connexionDatabase();
int i;
SQL = "INSERT INTO " + nomTable + " VALUES(";
for (i = 0; i <= contenuTableau.length - 1; i++) {
SQL += "'" + contenuTableau[i] + "'";
if (i < contenuTableau.length - 1) {
SQL += ",";
}
}
SQL += ")";
return this.exécutionUpdate(SQL);
}
public String queryInsert(String nomTable, String[] nomColonne, Object[] contenuTableau) {
connexionDatabase();
int i;
SQL = "INSERT INTO " + nomTable + "(";
for (i = 0; i <= nomColonne.length - 1; i++) {
SQL += nomColonne[i];
if (i < nomColonne.length - 1) {
SQL += ",";
}
}
SQL += ") VALUES(";
for (i = 0; i <= contenuTableau.length - 1; i++) {
SQL += "'" + contenuTableau[i] + "'";
if (i < contenuTableau.length - 1) {
SQL += ",";
}
}
SQL += ")";
return this.exécutionUpdate(SQL);
}
public String queryUpdate(String nomTable, String[] nomColonne, Object[] contenuTableau, String état) {
connexionDatabase();
int i;
SQL = "UPDATE " + nomTable + " SET ";
for (i = 0; i <= nomColonne.length - 1; i++) {
SQL += nomColonne[i] + "='" + contenuTableau[i] + "'";
if (i < nomColonne.length - 1) {
SQL += ",";
}
}
SQL += " WHERE " + état;
return this.exécutionUpdate(SQL);
}
public String queryUpdate(String nomTable, String[] nomColonne, double[] contenuTableau, String état) {
connexionDatabase();
int i;
SQL = "UPDATE " + nomTable + " SET ";
for (i = 0; i <= nomColonne.length - 1; i++) {
SQL += nomColonne[i] + "='" + contenuTableau[i] + "'";
if (i < nomColonne.length - 1) {
SQL += ",";
}
}
SQL += " WHERE " + état;
return this.exécutionUpdate(SQL);
}
public String queryDelete(String nomtable) {
connexionDatabase();
SQL = "DELETE FROM " + nomtable;
return this.exécutionUpdate(SQL);
}
public String queryDelete(String nomTable, Object état) {
connexionDatabase();
SQL = "DELETE FROM " + nomTable + " WHERE " + état;
return this.exécutionUpdate(SQL);
}
}
| ISO-8859-1 | Java | 6,494 | java | BDD.java | Java | [] | null | [] | package DB;
import java.net.Socket;
import java.sql.*;
public class BDD {
Connection connection;
Statement statement;
String SQL;
String url;
Socket client;
public BDD(String url) {
this.url = url;
}
public Connection connexionDatabase() {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager.getConnection(url);
}
catch (Exception e) {
System.err.println(e);
}
return connection;
}
public Connection closeconnexion() {
try {
connection.close();
}
catch (Exception e) {
System.err.println(e);
}
return connection;
}
public ResultSet exécutionQuery(String sql) {
connexionDatabase();
ResultSet resultSet = null;
try {
statement = connection.createStatement();
resultSet = statement.executeQuery(sql);
System.out.println(sql);
}
catch (SQLException ex) {
System.err.println(ex);
}
return resultSet;
}
public String exécutionUpdate(String sql) {
connexionDatabase();
String result = "";
try {
statement = connection.createStatement();
statement.executeUpdate(sql);
result = sql;
} catch (SQLException ex) {
result = ex.toString();
}
return result;
}
public ResultSet querySelectAll(String nomTable) {
connexionDatabase();
SQL = "SELECT * FROM " + nomTable;
return this.exécutionQuery(SQL);
}
public ResultSet querySelectAll(String nomTable, String état) {
connexionDatabase();
SQL = "SELECT * FROM " + nomTable + " WHERE " + état;
return this.exécutionQuery(SQL);
}
public ResultSet querySelect(String[] nomColonne, String nomTable) {
connexionDatabase();
int i;
SQL = "SELECT ";
for (i = 0; i <= nomColonne.length - 1; i++) {
SQL += nomColonne[i];
if (i < nomColonne.length - 1) {
SQL += ",";
}
}
SQL += " FROM " + nomTable;
return this.exécutionQuery(SQL);
}
public ResultSet fcSelectCommand(String[] nomColonne, String nomTable, String état) {
connexionDatabase();
int i;
SQL = "SELECT ";
for (i = 0; i <= nomColonne.length - 1; i++) {
SQL += nomColonne[i];
if (i < nomColonne.length - 1) {
SQL += ",";
}
}
SQL += " FROM " + nomTable + " WHERE " + état;
return this.exécutionQuery(SQL);
}
public ResultSet fbSelectCommand(String[] nomColonne, String[] nomTable, Object[] état) {
connexionDatabase();
int i;
SQL = "SELECT ";
for (i = 0; i <= nomColonne.length - 1; i++) {
SQL += nomColonne[i];
if (i < nomColonne.length - 1) {
SQL += ",";
}
}
SQL+= "FROM " ;
for (i = 0; i <= nomTable.length - 1; i++) {
SQL += nomTable[i] ;
if (i < nomTable.length - 1) {
SQL += ",";
}
}
SQL+= " WHERE ";
for (i = 0; i <= état.length - 1; i++) {
SQL += état[i] ;
if (i < état.length - 1) {
SQL += " AND ";
}
}
return this.exécutionQuery(SQL);
}
public ResultSet ijSelectCommand(String[] nomColonne, String[] nomTable, Object[] état) {
connexionDatabase();
int i;
SQL = "SELECT ";
for (i = 0; i <= nomColonne.length - 1; i++) {
SQL += nomColonne[i];
if (i < nomColonne.length - 1) {
SQL += ",";
}
}
SQL+= "FROM " + nomTable[0] + " INNER JOIN " + nomTable[1] +" ON "+ état[0] + " WHERE " + état[1] ;
return this.exécutionQuery(SQL);
}
public String queryInsert(String nomTable, Object[] contenuTableau) {
connexionDatabase();
int i;
SQL = "INSERT INTO " + nomTable + " VALUES(";
for (i = 0; i <= contenuTableau.length - 1; i++) {
SQL += "'" + contenuTableau[i] + "'";
if (i < contenuTableau.length - 1) {
SQL += ",";
}
}
SQL += ")";
return this.exécutionUpdate(SQL);
}
public String queryInsert(String nomTable, String[] nomColonne, Object[] contenuTableau) {
connexionDatabase();
int i;
SQL = "INSERT INTO " + nomTable + "(";
for (i = 0; i <= nomColonne.length - 1; i++) {
SQL += nomColonne[i];
if (i < nomColonne.length - 1) {
SQL += ",";
}
}
SQL += ") VALUES(";
for (i = 0; i <= contenuTableau.length - 1; i++) {
SQL += "'" + contenuTableau[i] + "'";
if (i < contenuTableau.length - 1) {
SQL += ",";
}
}
SQL += ")";
return this.exécutionUpdate(SQL);
}
public String queryUpdate(String nomTable, String[] nomColonne, Object[] contenuTableau, String état) {
connexionDatabase();
int i;
SQL = "UPDATE " + nomTable + " SET ";
for (i = 0; i <= nomColonne.length - 1; i++) {
SQL += nomColonne[i] + "='" + contenuTableau[i] + "'";
if (i < nomColonne.length - 1) {
SQL += ",";
}
}
SQL += " WHERE " + état;
return this.exécutionUpdate(SQL);
}
public String queryUpdate(String nomTable, String[] nomColonne, double[] contenuTableau, String état) {
connexionDatabase();
int i;
SQL = "UPDATE " + nomTable + " SET ";
for (i = 0; i <= nomColonne.length - 1; i++) {
SQL += nomColonne[i] + "='" + contenuTableau[i] + "'";
if (i < nomColonne.length - 1) {
SQL += ",";
}
}
SQL += " WHERE " + état;
return this.exécutionUpdate(SQL);
}
public String queryDelete(String nomtable) {
connexionDatabase();
SQL = "DELETE FROM " + nomtable;
return this.exécutionUpdate(SQL);
}
public String queryDelete(String nomTable, Object état) {
connexionDatabase();
SQL = "DELETE FROM " + nomTable + " WHERE " + état;
return this.exécutionUpdate(SQL);
}
}
| 6,494 | 0.4959 | 0.490175 | 260 | 23.857693 | 22.540028 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.915385 | false | false | 9 |
305800713d0b04530303ed00999ad0803219394d | 17,257,178,646,228 | 9df88f588204c4a26f55f4e87ecc473d26200cd7 | /app/src/main/java/com/example/android/guidetodc/Place.java | c03c127523e047e3310ddfdf0c21088470dff5f0 | [] | no_license | stef2dotoh/GuideToDC | https://github.com/stef2dotoh/GuideToDC | 4ba02fb370db45c47ef59e2cf89e1c9b364a397c | ec9adbbe3cc444bcff456484371e7c01d6bccea2 | refs/heads/master | 2021-08-30T18:21:43.753000 | 2017-12-19T00:23:54 | 2017-12-19T00:23:54 | 114,700,616 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.android.guidetodc;
/**
* {@link Place} represents the various locations visitors to DC can check out
*/
public class Place {
/**
* Resource ID for place image
*/
private int mImageResourceId;
/**
* Name of place
*/
private int mName;
/**
* Address
*/
private int mAddress;
/**
* Contact information
*/
private int mTelephone;
/**
* Web address
*/
private int mWeb;
/**
* Constructs a new place with initial values for the following
* @param imageResourceId
* @param name
* @param address
* @param telephone
* @param web
*/
public Place(int imageResourceId, int name, int address, int telephone, int web) {
mImageResourceId = imageResourceId;
mName = name;
mAddress = address;
mTelephone = telephone;
mWeb = web;
}
/**
* Returns place image
*/
public int getImageResourceId() {
return mImageResourceId;
}
/**
* Returns place name
*/
public int getName() {
return mName;
}
/**
* Returns place address
*/
public int getAddress() {
return mAddress;
}
/**
* Returns telephone number
*/
public int getTelephone() {
return mTelephone;
}
/**
* Returns web address
*/
public int getWeb() {
return mWeb;
}
}
| UTF-8 | Java | 1,460 | java | Place.java | Java | [] | null | [] | package com.example.android.guidetodc;
/**
* {@link Place} represents the various locations visitors to DC can check out
*/
public class Place {
/**
* Resource ID for place image
*/
private int mImageResourceId;
/**
* Name of place
*/
private int mName;
/**
* Address
*/
private int mAddress;
/**
* Contact information
*/
private int mTelephone;
/**
* Web address
*/
private int mWeb;
/**
* Constructs a new place with initial values for the following
* @param imageResourceId
* @param name
* @param address
* @param telephone
* @param web
*/
public Place(int imageResourceId, int name, int address, int telephone, int web) {
mImageResourceId = imageResourceId;
mName = name;
mAddress = address;
mTelephone = telephone;
mWeb = web;
}
/**
* Returns place image
*/
public int getImageResourceId() {
return mImageResourceId;
}
/**
* Returns place name
*/
public int getName() {
return mName;
}
/**
* Returns place address
*/
public int getAddress() {
return mAddress;
}
/**
* Returns telephone number
*/
public int getTelephone() {
return mTelephone;
}
/**
* Returns web address
*/
public int getWeb() {
return mWeb;
}
}
| 1,460 | 0.543151 | 0.543151 | 84 | 16.380953 | 16.444643 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.238095 | false | false | 9 |
1277fb06b2ece0da5d3e74927f5a6ec6eeb907ca | 25,486,335,982,148 | 7722b58b270c1d96fbe132c2a51ada1f1c5ac70b | /backoffice-admin/src/main/java/com/vates/wifibus/backoffice/validator/BrandFormValidator.java | a48e7385b3723679b084a247bec49934a33e9a98 | [] | no_license | laplata2003/wifibus-backoffice | https://github.com/laplata2003/wifibus-backoffice | 373c0b384411b18931f04107d3c717a46318757f | c5b988de30ed7d5ed8491bd24e67805c000729fb | refs/heads/master | 2018-05-18T08:42:59.629000 | 2017-10-12T16:35:10 | 2017-10-12T16:35:10 | 93,191,680 | 0 | 1 | null | false | 2017-10-12T16:35:11 | 2017-06-02T18:04:41 | 2017-06-06T19:00:40 | 2017-10-12T16:35:10 | 307 | 0 | 1 | 0 | Java | null | null | package com.vates.wifibus.backoffice.validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import com.vates.wifibus.backoffice.model.Brand;
import com.vates.wifibus.backoffice.model.BrandForm;
import com.vates.wifibus.backoffice.service.BrandService;
/**
*
* @author Luis Stubbia
*
*/
@Component
public class BrandFormValidator implements Validator {
private static final Logger logger = LoggerFactory.getLogger(BrandFormValidator.class);
@Autowired
private BrandService brandService;
@Override
public boolean supports(Class<?> clazz) {
return clazz.equals(BrandForm.class);
}
@Override
public void validate(Object brandForm, Errors errors) {
logger.debug("Validando {}", brandForm);
int numberOfOccurrences = 0;
Brand originalBrand = null;
BrandForm form = (BrandForm) brandForm;
if(form.getId() != null){
numberOfOccurrences ++;
originalBrand = brandService.getById(form.getId()).get();
}
validateName(errors, form, numberOfOccurrences, originalBrand);
}
private void validateName(Errors errors, BrandForm form, int numberOfOccurrences, Brand originalBrand) {
if (StringUtils.isEmpty(form.getName())) {
errors.rejectValue("name", "brandForm.required.name", "El nombre del Branding es requerido");
} else {
if(originalBrand != null && !originalBrand.getName().equals(form.getName())){
numberOfOccurrences --;
}
Long numberOfDuplicatedNames = brandService.countByName(form.getName());
if(null != numberOfDuplicatedNames && numberOfDuplicatedNames.intValue() > numberOfOccurrences){
errors.rejectValue("name", "brandForm.required.name", "El nombre del Branding ya existe");
}
}
if (StringUtils.isEmpty(form.getCobrand())) {
errors.rejectValue("cobrand", "brandForm.required.cobrand", "El cobranding es requerido");
}
if (StringUtils.isEmpty(form.getLogoImage())) {
errors.rejectValue("logoImage", "brandForm.required.logoImage", "La imagen de logo es requerida");
}
if (StringUtils.isEmpty(form.getBackgroundImage())) {
errors.rejectValue("backgroundImage", "brandForm.required.backgroundImage", "La imagen de fondo es requerida");
}
}
}
| UTF-8 | Java | 2,526 | java | BrandFormValidator.java | Java | [
{
"context": "fice.service.BrandService;\r\n\r\n/**\r\n * \r\n * @author Luis Stubbia\r\n * \r\n */\r\n@Component\r\npublic class BrandFormVali",
"end": 567,
"score": 0.9998572468757629,
"start": 555,
"tag": "NAME",
"value": "Luis Stubbia"
}
] | null | [] | package com.vates.wifibus.backoffice.validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import com.vates.wifibus.backoffice.model.Brand;
import com.vates.wifibus.backoffice.model.BrandForm;
import com.vates.wifibus.backoffice.service.BrandService;
/**
*
* @author <NAME>
*
*/
@Component
public class BrandFormValidator implements Validator {
private static final Logger logger = LoggerFactory.getLogger(BrandFormValidator.class);
@Autowired
private BrandService brandService;
@Override
public boolean supports(Class<?> clazz) {
return clazz.equals(BrandForm.class);
}
@Override
public void validate(Object brandForm, Errors errors) {
logger.debug("Validando {}", brandForm);
int numberOfOccurrences = 0;
Brand originalBrand = null;
BrandForm form = (BrandForm) brandForm;
if(form.getId() != null){
numberOfOccurrences ++;
originalBrand = brandService.getById(form.getId()).get();
}
validateName(errors, form, numberOfOccurrences, originalBrand);
}
private void validateName(Errors errors, BrandForm form, int numberOfOccurrences, Brand originalBrand) {
if (StringUtils.isEmpty(form.getName())) {
errors.rejectValue("name", "brandForm.required.name", "El nombre del Branding es requerido");
} else {
if(originalBrand != null && !originalBrand.getName().equals(form.getName())){
numberOfOccurrences --;
}
Long numberOfDuplicatedNames = brandService.countByName(form.getName());
if(null != numberOfDuplicatedNames && numberOfDuplicatedNames.intValue() > numberOfOccurrences){
errors.rejectValue("name", "brandForm.required.name", "El nombre del Branding ya existe");
}
}
if (StringUtils.isEmpty(form.getCobrand())) {
errors.rejectValue("cobrand", "brandForm.required.cobrand", "El cobranding es requerido");
}
if (StringUtils.isEmpty(form.getLogoImage())) {
errors.rejectValue("logoImage", "brandForm.required.logoImage", "La imagen de logo es requerida");
}
if (StringUtils.isEmpty(form.getBackgroundImage())) {
errors.rejectValue("backgroundImage", "brandForm.required.backgroundImage", "La imagen de fondo es requerida");
}
}
}
| 2,520 | 0.721299 | 0.720111 | 68 | 35.14706 | 32.440563 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.691176 | false | false | 9 |
573b8354222f0d0e8700820866386cf62767079b | 35,442,070,158,320 | 51b0113105c204b93973b2521a66e34dc2b1fc7a | /src/main/java/ps5/components/customFields/CFEditMockup.java | 47433695afb1dca139a9005f1c8092e747085e6c | [] | no_license | uzair1990/SVN_BackUP_CLK | https://github.com/uzair1990/SVN_BackUP_CLK | 8109f091fe94f860b9c672801e15880aff3a4eeb | 7f4fed9bf309bbaea05926bdb5af374e0a126333 | refs/heads/master | 2017-11-30T11:25:05.537000 | 2016-11-11T17:17:50 | 2016-11-11T17:17:50 | 81,482,743 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ps5.components.customFields;
import org.apache.tapestry.annotations.Parameter;
import ps5.psapi.fields.FieldOp;
import ps5.psapi.fields.FieldSession;
import com.cinteractive.ps3.mockups.CustomField;
import com.cinteractive.ps3.newsecurity.PSPermission;
import com.cinteractive.ps3.newsecurity.Permissionable;
import com.cinteractive.ps3.newsecurity.Verbs;
import com.cinteractive.ps3.work.Template;
import com.cinteractive.ps3.work.Work;
/**
* Use FieldDisplay instead
*/
@Deprecated
public abstract class CFEditMockup extends CFMockupBase {
@Parameter(required = false)
public abstract boolean getMayEditBean();
public abstract void setMayEditBean(boolean bool);
@Parameter(required = false)
public abstract boolean getMayEditBeanCustomFields();
public abstract void setMayEditBeanCustomFields(boolean bool);
// 0=show all, 1=show required only, 2=show optional only
@Parameter(required = false, defaultValue = "0")
public abstract int getWhichToShow();
public abstract void setWhichToShow(int intVal);
// Whether to omit the encosing table.
@Parameter(required = false, defaultValue = "false")
public abstract boolean getOmitTable();
public abstract void setOmitTable(boolean boolVal);
// Allows editing always. Added for the External idea page, since no user is logged in.
@Parameter(required = false, defaultValue = "false")
public abstract boolean getIgnorePermissions();
public abstract void setIgnorePermissions(boolean b);
public FieldSession initFieldSession() {
return new FieldSession(getObject(), FieldOp.EDIT, getSession());
}
public boolean getShow(CustomField x) {
int z= getWhichToShow();
boolean show = false;
if (!x.isLocked()) {
show = z==0 || (z==2);
}
return show;
}
public boolean getMayEdit() {
if (getIgnorePermissions()) return true;
if (getCustomField().isLocked()) return false;
if (getObject() instanceof Permissionable) { // if it's a PSObject we access to its permissions directly
PSPermission permission = getPermission((Permissionable) getObject());
return permission.mayEdit()
&& (permission.hasPermission(Verbs.EDIT_CUSTOM_FIELDS)
|| !getCustomField().isApplyPermissions()
);
} else { // if it's a bean (i.e. GroupBean) having no access to the corresponding PSObject permissions
return getMayEditBean() && (getMayEditBeanCustomFields() || !getCustomField().isApplyPermissions());
}
}
public boolean getIsInTemplate() {
return (getObject() instanceof Work) && Template.isInTemplate((Work)getObject());
}
@Override
public boolean getHasCustomFields() {
// Do not show locked custom fields
return
!getContext().getCustomFieldsUniverse().getCustomFields(
getObject().getPSType(),
CustomField.createUnlockedFilter(getObject().getPSType())).isEmpty();
}
} | UTF-8 | Java | 3,199 | java | CFEditMockup.java | Java | [] | null | [] | package ps5.components.customFields;
import org.apache.tapestry.annotations.Parameter;
import ps5.psapi.fields.FieldOp;
import ps5.psapi.fields.FieldSession;
import com.cinteractive.ps3.mockups.CustomField;
import com.cinteractive.ps3.newsecurity.PSPermission;
import com.cinteractive.ps3.newsecurity.Permissionable;
import com.cinteractive.ps3.newsecurity.Verbs;
import com.cinteractive.ps3.work.Template;
import com.cinteractive.ps3.work.Work;
/**
* Use FieldDisplay instead
*/
@Deprecated
public abstract class CFEditMockup extends CFMockupBase {
@Parameter(required = false)
public abstract boolean getMayEditBean();
public abstract void setMayEditBean(boolean bool);
@Parameter(required = false)
public abstract boolean getMayEditBeanCustomFields();
public abstract void setMayEditBeanCustomFields(boolean bool);
// 0=show all, 1=show required only, 2=show optional only
@Parameter(required = false, defaultValue = "0")
public abstract int getWhichToShow();
public abstract void setWhichToShow(int intVal);
// Whether to omit the encosing table.
@Parameter(required = false, defaultValue = "false")
public abstract boolean getOmitTable();
public abstract void setOmitTable(boolean boolVal);
// Allows editing always. Added for the External idea page, since no user is logged in.
@Parameter(required = false, defaultValue = "false")
public abstract boolean getIgnorePermissions();
public abstract void setIgnorePermissions(boolean b);
public FieldSession initFieldSession() {
return new FieldSession(getObject(), FieldOp.EDIT, getSession());
}
public boolean getShow(CustomField x) {
int z= getWhichToShow();
boolean show = false;
if (!x.isLocked()) {
show = z==0 || (z==2);
}
return show;
}
public boolean getMayEdit() {
if (getIgnorePermissions()) return true;
if (getCustomField().isLocked()) return false;
if (getObject() instanceof Permissionable) { // if it's a PSObject we access to its permissions directly
PSPermission permission = getPermission((Permissionable) getObject());
return permission.mayEdit()
&& (permission.hasPermission(Verbs.EDIT_CUSTOM_FIELDS)
|| !getCustomField().isApplyPermissions()
);
} else { // if it's a bean (i.e. GroupBean) having no access to the corresponding PSObject permissions
return getMayEditBean() && (getMayEditBeanCustomFields() || !getCustomField().isApplyPermissions());
}
}
public boolean getIsInTemplate() {
return (getObject() instanceof Work) && Template.isInTemplate((Work)getObject());
}
@Override
public boolean getHasCustomFields() {
// Do not show locked custom fields
return
!getContext().getCustomFieldsUniverse().getCustomFields(
getObject().getPSType(),
CustomField.createUnlockedFilter(getObject().getPSType())).isEmpty();
}
} | 3,199 | 0.662395 | 0.657706 | 85 | 35.658825 | 28.99637 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.635294 | false | false | 9 |
5aa92d467f6221948dbc7fe6452b5dcc87f7f711 | 7,224,135,058,216 | 85b7973ffb4936105bdcff88c50abe7c112bc460 | /src/main/java/com/tosk/wekatabletmenu/model/ProductsNSales.java | 0777b7979a35585a5d65e4227e4df68fa863dcfc | [] | no_license | haibbi/wekatabletmenuspringboot | https://github.com/haibbi/wekatabletmenuspringboot | 20e61cb830761093441cadc991ddce869f940f48 | 588267d3657187a5dc1822a4b6790c2c5e565087 | refs/heads/master | 2018-04-01T03:03:33.109000 | 2017-04-14T12:33:36 | 2017-04-14T12:33:36 | 86,785,159 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tosk.wekatabletmenu.model;
import java.util.List;
/**
* Created by haibbi on 31.03.2017
*/
public class ProductsNSales {
private List<String> products;
private List<List<String>> transaction;
public String string() {
return "ProductsNSales{" +
"products=" + products +
", transaction=" + transaction +
'}';
}
public List<String> getProducts() {
return products;
}
public void setProducts(List<String> products) {
this.products = products;
}
public List<List<String>> getTransaction() {
return transaction;
}
public void setTransaction(List<List<String>> transaction) {
this.transaction = transaction;
}
}
| UTF-8 | Java | 763 | java | ProductsNSales.java | Java | [
{
"context": ".model;\n\nimport java.util.List;\n\n/**\n * Created by haibbi on 31.03.2017\n */\npublic class ProductsNSales {\n\n",
"end": 88,
"score": 0.9995457530021667,
"start": 82,
"tag": "USERNAME",
"value": "haibbi"
}
] | null | [] | package com.tosk.wekatabletmenu.model;
import java.util.List;
/**
* Created by haibbi on 31.03.2017
*/
public class ProductsNSales {
private List<String> products;
private List<List<String>> transaction;
public String string() {
return "ProductsNSales{" +
"products=" + products +
", transaction=" + transaction +
'}';
}
public List<String> getProducts() {
return products;
}
public void setProducts(List<String> products) {
this.products = products;
}
public List<List<String>> getTransaction() {
return transaction;
}
public void setTransaction(List<List<String>> transaction) {
this.transaction = transaction;
}
}
| 763 | 0.602883 | 0.592398 | 35 | 20.799999 | 19.060505 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 9 |
f44d460b37e80e75becef23eebfc4eb580644779 | 19,550,691,197,192 | c6939c1fab491921ba45881b9b80243cf8b38cb0 | /encurtador/src/main/java/br/com/api/encurtador/bean/ShortenRequest.java | 34acd09faff94d46065d05d3c0244621058e57b7 | [] | no_license | brbbruno/APIencurtadorJava | https://github.com/brbbruno/APIencurtadorJava | 7f7967bb779ce641362e15cb1318ea53c2277460 | b06375757ce0de42fe2280a92d2cecd20df1cc08 | refs/heads/master | 2023-04-14T18:08:54.242000 | 2021-04-22T04:41:22 | 2021-04-22T04:41:22 | 360,392,033 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.api.encurtador.bean;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ShortenRequest {
private String url;
private String nomeEscolhido;
private String dataExpiracao;
@JsonCreator
public ShortenRequest(@JsonProperty("url") String url,
@JsonProperty("nomeEscolhido") String nomeEscolhido,
@JsonProperty("dataExpiracao") String dataExpiracao) {
this.url = url;
this.nomeEscolhido = nomeEscolhido;
this.dataExpiracao = dataExpiracao;
}
public String getNomeEscolhido() {
return nomeEscolhido;
}
public void setNomeEscolhido(String nomeEscolhido) {
this.nomeEscolhido = nomeEscolhido;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDataExpiracao() {
return dataExpiracao;
}
public void setDataExpiracao(String dataExpiracao) {
this.dataExpiracao = dataExpiracao;
}
} | UTF-8 | Java | 1,115 | java | ShortenRequest.java | Java | [] | null | [] | package br.com.api.encurtador.bean;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ShortenRequest {
private String url;
private String nomeEscolhido;
private String dataExpiracao;
@JsonCreator
public ShortenRequest(@JsonProperty("url") String url,
@JsonProperty("nomeEscolhido") String nomeEscolhido,
@JsonProperty("dataExpiracao") String dataExpiracao) {
this.url = url;
this.nomeEscolhido = nomeEscolhido;
this.dataExpiracao = dataExpiracao;
}
public String getNomeEscolhido() {
return nomeEscolhido;
}
public void setNomeEscolhido(String nomeEscolhido) {
this.nomeEscolhido = nomeEscolhido;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDataExpiracao() {
return dataExpiracao;
}
public void setDataExpiracao(String dataExpiracao) {
this.dataExpiracao = dataExpiracao;
}
} | 1,115 | 0.658296 | 0.658296 | 43 | 24.953489 | 22.375187 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.395349 | false | false | 9 |
5e1edf63c49689702afa69b7af91d8f160d26365 | 13,159,779,862,417 | 96a2fed5068380e5d7191549ae7f6743a2b9cdcb | /src/main/java/llvm/AndLLVM.java | 67bb29f53f86abb98a6c4118133af9579fe0f8d7 | [] | no_license | carolinecullen/mini-compiler-java | https://github.com/carolinecullen/mini-compiler-java | 9e1571b83f003733a08d06252998584e81b7419a | d74a86dc140ac8ca2fdadd4931e14fd6e6237603 | refs/heads/master | 2020-04-12T17:48:38.748000 | 2018-12-21T02:56:41 | 2018-12-21T02:56:41 | 152,615,053 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package llvm;
import arm.AddArm;
import arm.AndArm;
import arm.MovtArm;
import arm.MovwArm;
import cfg.CfgNode;
import java.util.ArrayList;
public class AndLLVM
implements InstructionLLVM
{
public Register result;
public String ty;
public ExprReturn op1;
public ExprReturn op2;
String instruction;
public void setInstruction(String instruction) {
this.instruction = instruction;
}
public AndLLVM(ExprReturn l, ExprReturn r) {
BoolLLVM n = new BoolLLVM();
ty = n.name;
result = new Register(new BoolLLVM());
op1 = l;
op2 = r;
instruction = this.toString();
}
public String getInstruction() {
return instruction;
}
public String toString() {
return result + " = and " + ty + " " + op1.toString() + ", " + op2.toString();
}
public ArrayList<String> getArm(CfgNode c) {
ArrayList<String> ret_str = new ArrayList<>();
if (op1 instanceof ImmediateLLVM && op2 instanceof ImmediateLLVM) {
ExprReturn al1 = getImmediateMovInstructions((ImmediateLLVM)op1, ret_str);
ExprReturn al2 = getImmediateMovInstructions((ImmediateLLVM)op2, ret_str);
AndArm andarm = new AndArm(result, al1, al2);
ret_str.add(andarm.toString());
} else if (op1 instanceof ImmediateLLVM) {
ExprReturn al1 = getImmediateMovInstructions((ImmediateLLVM)op1, ret_str);
AndArm andarm = new AndArm(result, al1, op2);
ret_str.add(andarm.toString());
} else if (op2 instanceof ImmediateLLVM) {
ExprReturn al1 = getImmediateMovInstructions((ImmediateLLVM)op2, ret_str);
AndArm andarm = new AndArm(result, op1, al1);
ret_str.add(andarm.toString());
} else {
AndArm andarm = new AndArm(result, op1, op2);
ret_str.add(andarm.toString());
}
return ret_str;
}
public void replaceRegForOpt(String func) {
checkAndReplace(op1, func);
checkAndReplace(op2, func);
}
private void checkAndReplace(ExprReturn op, String func) {
if(op instanceof Register) {
Register new_op = (Register)op;
if(new_op.reg_type instanceof IdLLVM) {
((Register) op).reg_name = ((Register) op).reg_name + func;
}
}
}
public Register getReturnVal() {
return result;
}
public void replaceRet(Register r) {
result = r;
}
}
| UTF-8 | Java | 2,523 | java | AndLLVM.java | Java | [] | null | [] | package llvm;
import arm.AddArm;
import arm.AndArm;
import arm.MovtArm;
import arm.MovwArm;
import cfg.CfgNode;
import java.util.ArrayList;
public class AndLLVM
implements InstructionLLVM
{
public Register result;
public String ty;
public ExprReturn op1;
public ExprReturn op2;
String instruction;
public void setInstruction(String instruction) {
this.instruction = instruction;
}
public AndLLVM(ExprReturn l, ExprReturn r) {
BoolLLVM n = new BoolLLVM();
ty = n.name;
result = new Register(new BoolLLVM());
op1 = l;
op2 = r;
instruction = this.toString();
}
public String getInstruction() {
return instruction;
}
public String toString() {
return result + " = and " + ty + " " + op1.toString() + ", " + op2.toString();
}
public ArrayList<String> getArm(CfgNode c) {
ArrayList<String> ret_str = new ArrayList<>();
if (op1 instanceof ImmediateLLVM && op2 instanceof ImmediateLLVM) {
ExprReturn al1 = getImmediateMovInstructions((ImmediateLLVM)op1, ret_str);
ExprReturn al2 = getImmediateMovInstructions((ImmediateLLVM)op2, ret_str);
AndArm andarm = new AndArm(result, al1, al2);
ret_str.add(andarm.toString());
} else if (op1 instanceof ImmediateLLVM) {
ExprReturn al1 = getImmediateMovInstructions((ImmediateLLVM)op1, ret_str);
AndArm andarm = new AndArm(result, al1, op2);
ret_str.add(andarm.toString());
} else if (op2 instanceof ImmediateLLVM) {
ExprReturn al1 = getImmediateMovInstructions((ImmediateLLVM)op2, ret_str);
AndArm andarm = new AndArm(result, op1, al1);
ret_str.add(andarm.toString());
} else {
AndArm andarm = new AndArm(result, op1, op2);
ret_str.add(andarm.toString());
}
return ret_str;
}
public void replaceRegForOpt(String func) {
checkAndReplace(op1, func);
checkAndReplace(op2, func);
}
private void checkAndReplace(ExprReturn op, String func) {
if(op instanceof Register) {
Register new_op = (Register)op;
if(new_op.reg_type instanceof IdLLVM) {
((Register) op).reg_name = ((Register) op).reg_name + func;
}
}
}
public Register getReturnVal() {
return result;
}
public void replaceRet(Register r) {
result = r;
}
}
| 2,523 | 0.603646 | 0.592549 | 88 | 27.670454 | 24.541117 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.659091 | false | false | 9 |
f40d0251a8baa2e41fb46593265489b5fb8b1097 | 27,968,827,055,306 | b9972de7611b70161120a0486362685039edc4ee | /src/main/java/com/dxxt/im/websocket/NettyServer.java | 560740e8d0951eb2447bada7666a3f77319e63ad | [] | no_license | GeXin666/im-server | https://github.com/GeXin666/im-server | 525f00f7a73e0291ad639cbe91a3aa61e62e1563 | 3b2f5522caddc5f74f73aff7e39cac0ba45eb3a6 | refs/heads/master | 2022-12-27T09:33:29.157000 | 2020-10-09T09:44:13 | 2020-10-09T09:44:13 | 298,989,589 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dxxt.im.websocket;
import com.dxxt.im.config.AppConfig;
import io.netty.channel.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@Slf4j
@Component
public class NettyServer {
private EventLoopGroup bossGroup = new NioEventLoopGroup(1);
private EventLoopGroup workerGroup = new NioEventLoopGroup(32);
@PostConstruct
public void startServer() throws Exception {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.DEBUG))
.option(ChannelOption.SO_BACKLOG, 128)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
.option(ChannelOption.ALLOCATOR, ByteBufAllocator.DEFAULT)
.childOption(ChannelOption.SO_KEEPALIVE, false)
.childHandler(new ServerInitializer());
b.bind("0.0.0.0", AppConfig.imServerPort).sync();
log.info("Netty Server started on port: {}", AppConfig.imServerPort);
}
@PreDestroy
public void stop() {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
log.info("Netty Server stopped on port: {}", AppConfig.imServerPort);
}
}
| UTF-8 | Java | 1,635 | java | NettyServer.java | Java | [
{
"context": "Handler(new ServerInitializer());\n b.bind(\"0.0.0.0\", AppConfig.imServerPort).sync();\n log.inf",
"end": 1306,
"score": 0.9996724724769592,
"start": 1299,
"tag": "IP_ADDRESS",
"value": "0.0.0.0"
}
] | null | [] | package com.dxxt.im.websocket;
import com.dxxt.im.config.AppConfig;
import io.netty.channel.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@Slf4j
@Component
public class NettyServer {
private EventLoopGroup bossGroup = new NioEventLoopGroup(1);
private EventLoopGroup workerGroup = new NioEventLoopGroup(32);
@PostConstruct
public void startServer() throws Exception {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.DEBUG))
.option(ChannelOption.SO_BACKLOG, 128)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
.option(ChannelOption.ALLOCATOR, ByteBufAllocator.DEFAULT)
.childOption(ChannelOption.SO_KEEPALIVE, false)
.childHandler(new ServerInitializer());
b.bind("0.0.0.0", AppConfig.imServerPort).sync();
log.info("Netty Server started on port: {}", AppConfig.imServerPort);
}
@PreDestroy
public void stop() {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
log.info("Netty Server stopped on port: {}", AppConfig.imServerPort);
}
}
| 1,635 | 0.725382 | 0.714985 | 47 | 33.787235 | 23.658867 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.638298 | false | false | 9 |
eb1de714ecbedf2480f5543a457ee19a90c723e3 | 22,359,599,808,487 | c3cedb642eb2f02532c77e09e93436f970c77d0a | /src/mainWindow/model/Info.java | 1c59a846560ea9a14181d02715de650c643e9d16 | [
"MIT"
] | permissive | CurseRED/p2p-file-transmitter | https://github.com/CurseRED/p2p-file-transmitter | 222b6e2a9b971bdd8473ee27bd4f3716ad1f422e | 96bd353567cef5193f865c5f4adf8a537a4baa7d | refs/heads/master | 2021-03-01T17:06:02.634000 | 2020-03-23T20:45:27 | 2020-03-23T20:45:27 | 245,800,973 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package mainWindow.model;
import javafx.beans.property.SimpleStringProperty;
public class Info {
private SimpleStringProperty filename;
public Info(String filename) {
this.filename = new SimpleStringProperty(filename);
}
public String getFilename() {
return filename.get();
}
public SimpleStringProperty filenameProperty() {
return filename;
}
public void setFilename(String filename) {
this.filename.set(filename);
}
}
| UTF-8 | Java | 495 | java | Info.java | Java | [] | null | [] | package mainWindow.model;
import javafx.beans.property.SimpleStringProperty;
public class Info {
private SimpleStringProperty filename;
public Info(String filename) {
this.filename = new SimpleStringProperty(filename);
}
public String getFilename() {
return filename.get();
}
public SimpleStringProperty filenameProperty() {
return filename;
}
public void setFilename(String filename) {
this.filename.set(filename);
}
}
| 495 | 0.682828 | 0.682828 | 24 | 19.625 | 19.817528 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.291667 | false | false | 9 |
9ccb11430a7b0906ef5f408abf697c68ad19c5dd | 22,359,599,806,957 | 7b030fc6061f4a6def58aadb86053db2d00dfbaf | /src/main/java/kata/mower/dto/Position.java | df724379487b1754b4dadae2f2a7b13a5805ca2b | [] | no_license | HalloumiYoussef/automower | https://github.com/HalloumiYoussef/automower | 580a4f0b7e20263df673ff8e50ad088d33792946 | 442722585af0db2bf762f579a14ba441c3bbeda1 | refs/heads/master | 2020-03-20T09:51:41.288000 | 2018-08-02T21:18:34 | 2018-08-02T21:18:34 | 137,351,056 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package kata.mower.dto;
import kata.mower.config.AppMower;
import kata.mower.enums.EnumMove;
import kata.mower.enums.EnumOrient;
import kata.mower.util.EnumOrientUtil;
import org.apache.commons.lang3.StringUtils;
/**
* Created by YHI on 11/06/2018.
*/
public class Position {
private static final String SEP = " ";
private int x;
private int y;
private EnumOrient orientation;
public Position() {
//Default
}
public Position(int x, int y, EnumOrient orientation) {
this.x = x;
this.y = y;
this.orientation = orientation;
}
int getX() {
return x;
}
int getY() {
return y;
}
EnumOrient getOrientation() {
return orientation;
}
void processInstruction(EnumMove move) {
if(EnumMove.A.equals(move)){
moveForward();
}
if(EnumMove.D.equals(move)){
this.orientation = EnumOrientUtil.turnToRight(this.orientation);
}
if(EnumMove.G.equals(move)){
this.orientation = EnumOrientUtil.turnToLeft(this.orientation);
}
}
private void moveForward() {
if(EnumOrient.N.equals(this.orientation)){
incrementY();
}else if(EnumOrient.S.equals(this.orientation)){
decrementY();
}else if(EnumOrient.E.equals(this.orientation)){
incrementX();
}else if(EnumOrient.W.equals(this.orientation)){
decrementX();
}
}
private void incrementY() {
if(y < AppMower.upperRightY) {
this.y++;
}
}
private void decrementY() {
if(y > 0) {
this.y--;
}
}
private void decrementX() {
if(x > 0) {
this.x--;
}
}
private void incrementX() {
if(x < AppMower.upperRightX) {
this.x++;
}
}
@Override
public String toString() {
return StringUtils.join(x, SEP, y, SEP, orientation);
}
}
| UTF-8 | Java | 2,021 | java | Position.java | Java | [
{
"context": "ache.commons.lang3.StringUtils;\n\n/**\n * Created by YHI on 11/06/2018.\n */\npublic class Position {\n\n p",
"end": 236,
"score": 0.9976197481155396,
"start": 233,
"tag": "USERNAME",
"value": "YHI"
}
] | null | [] | package kata.mower.dto;
import kata.mower.config.AppMower;
import kata.mower.enums.EnumMove;
import kata.mower.enums.EnumOrient;
import kata.mower.util.EnumOrientUtil;
import org.apache.commons.lang3.StringUtils;
/**
* Created by YHI on 11/06/2018.
*/
public class Position {
private static final String SEP = " ";
private int x;
private int y;
private EnumOrient orientation;
public Position() {
//Default
}
public Position(int x, int y, EnumOrient orientation) {
this.x = x;
this.y = y;
this.orientation = orientation;
}
int getX() {
return x;
}
int getY() {
return y;
}
EnumOrient getOrientation() {
return orientation;
}
void processInstruction(EnumMove move) {
if(EnumMove.A.equals(move)){
moveForward();
}
if(EnumMove.D.equals(move)){
this.orientation = EnumOrientUtil.turnToRight(this.orientation);
}
if(EnumMove.G.equals(move)){
this.orientation = EnumOrientUtil.turnToLeft(this.orientation);
}
}
private void moveForward() {
if(EnumOrient.N.equals(this.orientation)){
incrementY();
}else if(EnumOrient.S.equals(this.orientation)){
decrementY();
}else if(EnumOrient.E.equals(this.orientation)){
incrementX();
}else if(EnumOrient.W.equals(this.orientation)){
decrementX();
}
}
private void incrementY() {
if(y < AppMower.upperRightY) {
this.y++;
}
}
private void decrementY() {
if(y > 0) {
this.y--;
}
}
private void decrementX() {
if(x > 0) {
this.x--;
}
}
private void incrementX() {
if(x < AppMower.upperRightX) {
this.x++;
}
}
@Override
public String toString() {
return StringUtils.join(x, SEP, y, SEP, orientation);
}
}
| 2,021 | 0.552697 | 0.547254 | 100 | 19.209999 | 18.282393 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.34 | false | false | 9 |
7bc1efb629326db3beb437e75d1b7222a256472f | 10,986,526,411,617 | 2b7e3a8a90f91f02b44dacd1ce88bfaaff8ed29e | /Weather/app/src/main/java/com/two/assignment/itsmap/weather/util/WeatherUtil.java | a3fad74fe7785977ac66240469f2acb8aeb5b141 | [] | no_license | jacobboes/ITSMAP-Assignment2 | https://github.com/jacobboes/ITSMAP-Assignment2 | de8ec833d39ff09e3b52fd69502494328ebecae1 | c58f6843b61b45901cd2c1929bfb26fc6eebdce1 | refs/heads/master | 2021-01-20T09:30:14.984000 | 2017-06-05T09:18:11 | 2017-06-05T09:18:11 | 90,259,596 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.two.assignment.itsmap.weather.util;
public class WeatherUtil {
public static final long AARHUS = 2624652;
public static final String WEATHER_API = "http://api.openweathermap.org/data/2.5/weather?id=" + AARHUS + "&APPID=834f986e836d3f48358ffe332d7f0f37";
public static final String BROADCAST_WEATHER = "COM.TWO.ASSIGNMENT.ITSMAP.BROADCAST";
}
| UTF-8 | Java | 367 | java | WeatherUtil.java | Java | [] | null | [] | package com.two.assignment.itsmap.weather.util;
public class WeatherUtil {
public static final long AARHUS = 2624652;
public static final String WEATHER_API = "http://api.openweathermap.org/data/2.5/weather?id=" + AARHUS + "&APPID=834f986e836d3f48358ffe332d7f0f37";
public static final String BROADCAST_WEATHER = "COM.TWO.ASSIGNMENT.ITSMAP.BROADCAST";
}
| 367 | 0.765668 | 0.681199 | 7 | 51.42857 | 49.583572 | 151 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 9 |
b47605edfc654d13314ef90b234a4999a6ade050 | 30,605,936,958,619 | 30cbaed96d0f0ed012dbb95219b3d16085584ebd | /java/edu/neu/madcourse/manusaxena/Assignment8/realtimedatabase/models/User.java | 42598c79e7f08b27ce3d2bbae39ca2d093404f7d | [] | no_license | manavmradul11/Android-Development--Scroggle-Game | https://github.com/manavmradul11/Android-Development--Scroggle-Game | c02dba2ee9298d484681a6b5875990e3d5e4a9c5 | 877f530f9f74515ceae50c2c6853330bc0b5e228 | refs/heads/master | 2021-01-19T17:05:15.680000 | 2017-04-14T20:53:57 | 2017-04-14T20:53:57 | 88,301,992 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.neu.madcourse.manusaxena.Assignment8.realtimedatabase.models;
import com.google.firebase.database.IgnoreExtraProperties;
@IgnoreExtraProperties
public class User {
public String identity;
public String username;
public boolean active;
public int score;
public int xcord;
public int ycord;
public User(){
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public User(String identity,String username,boolean active, int score){
this.identity= identity;
this.username = username;
this.active = active;
this.score = score;
}
}
| UTF-8 | Java | 653 | java | User.java | Java | [
{
"context": " this.identity= identity;\n this.username = username;\n this.active = active;\n this.score",
"end": 584,
"score": 0.9990929365158081,
"start": 576,
"tag": "USERNAME",
"value": "username"
}
] | null | [] | package edu.neu.madcourse.manusaxena.Assignment8.realtimedatabase.models;
import com.google.firebase.database.IgnoreExtraProperties;
@IgnoreExtraProperties
public class User {
public String identity;
public String username;
public boolean active;
public int score;
public int xcord;
public int ycord;
public User(){
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public User(String identity,String username,boolean active, int score){
this.identity= identity;
this.username = username;
this.active = active;
this.score = score;
}
}
| 653 | 0.701378 | 0.699847 | 27 | 23.185184 | 24.006229 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 9 |
58701c7fc4e695d1b769b2d47093c10d93815a77 | 77,309,414,366 | fbac972f72a7e2dc6a5be6cb534da900cb682623 | /src/main/java/com/thoughtworks/mapstruct/example7/demo2/CarMapper.java | a23cb0d2c6a7a74b1418606b6f24568fa71d9eb2 | [] | no_license | Matt-Kevin0608/mapStruct | https://github.com/Matt-Kevin0608/mapStruct | e97c46fc788cee3672c69a3db6251976963fba64 | f3f8799396bca8686f969d30daef721a2a6ef211 | refs/heads/master | 2023-02-13T06:42:59.338000 | 2021-01-05T07:02:41 | 2021-01-05T07:02:41 | 323,657,480 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.thoughtworks.mapstruct.example7.demo2;
import com.thoughtworks.mapstruct.example1.performance.Car;
import com.thoughtworks.mapstruct.example1.performance.CarDto;
import com.thoughtworks.mapstruct.example1.performance.Engine;
import com.thoughtworks.mapstruct.example1.performance.EngineDto;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;
@Mapper(uses = EngineMapper.class)
public interface CarMapper {
CarMapper INSTANCE = Mappers.getMapper( CarMapper.class );
@Mapping(source = "engine", target = "engineDto")
CarDto toDto(Car car);
} | UTF-8 | Java | 614 | java | CarMapper.java | Java | [] | null | [] | package com.thoughtworks.mapstruct.example7.demo2;
import com.thoughtworks.mapstruct.example1.performance.Car;
import com.thoughtworks.mapstruct.example1.performance.CarDto;
import com.thoughtworks.mapstruct.example1.performance.Engine;
import com.thoughtworks.mapstruct.example1.performance.EngineDto;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;
@Mapper(uses = EngineMapper.class)
public interface CarMapper {
CarMapper INSTANCE = Mappers.getMapper( CarMapper.class );
@Mapping(source = "engine", target = "engineDto")
CarDto toDto(Car car);
} | 614 | 0.80456 | 0.794788 | 19 | 31.368422 | 24.561867 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.578947 | false | false | 9 |
d8036e91cfa525f00a523b70b1a5fc1e487579c3 | 13,529,146,986,377 | 8c56a7d2ae2c0482d29300227c2de7548e4c221e | /src/cn/eros/IntegerCompare.java | 463e494c039f9fd22fd44f4afe32f70e70ce2790 | [] | no_license | MirZhou/java-example | https://github.com/MirZhou/java-example | 9f776b2aa6bf8f5bb057dfdc75a0bf9fa0021e27 | 2984281b618da161db666d45356c5d9e6a0b2f7e | refs/heads/master | 2023-04-01T11:55:17.897000 | 2021-04-08T14:31:53 | 2021-04-08T14:31:53 | 262,263,709 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.eros;
/**
* Integer类型数据比较
* <p>Create time: 2020-05-28 11:49</p>
*
* @author Eros
**/
public class IntegerCompare {
public static void main(String[] args) {
/*
* Integer会缓存-128~127的数字,值在此范围内时,其引用地址相同
*/
Integer val1 = 100;
Integer val2 = 100;
Integer val3 = 128;
Integer val4 = 128;
// 打印对象存储地址
System.out.println(System.identityHashCode(val1));
System.out.println(System.identityHashCode(val2));
System.out.println(System.identityHashCode(val3));
System.out.println(System.identityHashCode(val4));
// true
System.out.println(val1 == val2);
// true
System.out.println(val1.equals(val2));
// false
System.out.println(val3 == val4);
// true
System.out.println(val3.equals(val4));
}
}
| UTF-8 | Java | 943 | java | IntegerCompare.java | Java | [
{
"context": "<p>Create time: 2020-05-28 11:49</p>\n *\n * @author Eros\n **/\npublic class IntegerCompare {\n public sta",
"end": 97,
"score": 0.9583504796028137,
"start": 93,
"tag": "USERNAME",
"value": "Eros"
}
] | null | [] | package cn.eros;
/**
* Integer类型数据比较
* <p>Create time: 2020-05-28 11:49</p>
*
* @author Eros
**/
public class IntegerCompare {
public static void main(String[] args) {
/*
* Integer会缓存-128~127的数字,值在此范围内时,其引用地址相同
*/
Integer val1 = 100;
Integer val2 = 100;
Integer val3 = 128;
Integer val4 = 128;
// 打印对象存储地址
System.out.println(System.identityHashCode(val1));
System.out.println(System.identityHashCode(val2));
System.out.println(System.identityHashCode(val3));
System.out.println(System.identityHashCode(val4));
// true
System.out.println(val1 == val2);
// true
System.out.println(val1.equals(val2));
// false
System.out.println(val3 == val4);
// true
System.out.println(val3.equals(val4));
}
}
| 943 | 0.579793 | 0.52698 | 34 | 24.617647 | 18.995378 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.382353 | false | false | 9 |
ae81d225c5adf0f017c83b0d992e5dfc2ef45f2b | 33,930,241,643,481 | 687b6ee9aa24ad3671a2f0646b8e694e89d2714b | /src/Controller/MainController.java | a1e5cbeec069d8ef9c797a006ea5f6aabd8c662d | [] | no_license | anngo14/PlayerX | https://github.com/anngo14/PlayerX | 3f89d32d498604dcb461fb4ee959046e12a43c1d | ad416fa7a0aac43a13140a0b7818f5bb33ef217d | refs/heads/master | 2021-06-15T12:26:34.330000 | 2021-05-23T05:34:55 | 2021-05-23T05:34:55 | 195,589,661 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Controller;
import java.awt.Dimension;
import java.awt.Font;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Optional;
import java.util.ResourceBundle;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import Model.MediaItem;
import Model.Music;
import Model.User;
import javafx.animation.FadeTransition;
import javafx.animation.Timeline;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;
import javafx.scene.media.MediaPlayer;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;
public class MainController implements Initializable, Controller{
private final int cid = 1;
private static MainController instance = null;
private Controller currentController = null;
FadeTransition fade;
private User u;
@FXML
ImageView userImg;
@FXML
ImageView powerImg;
@FXML
StackPane panel;
@FXML
Text welcomeText;
@FXML
Text userNameText;
public MainController()
{
}
public MainController(User user)
{
u = user;
}
public static MainController getInstance()
{
if (instance == null)
instance = new MainController();
return instance;
}
public void setUser(User user)
{
u = user;
}
public User getUser()
{
return u;
}
public int getId()
{
return cid;
}
@FXML
public void loginAction()
{
fade.stop();
fade = new FadeTransition(Duration.millis(750), panel);
fade.setFromValue(1.0);
fade.setToValue(0);
fade.play();
changeView(ViewType.HOMEVIEW, u, Optional.empty(), Optional.empty(), Optional.empty());
}
@FXML
public void exitApplication()
{
int input = confirmationBox();
if(input == 0)
{
System.exit(0);
}
else {
return;
}
}
@FXML
public void switchUser()
{
changeView(ViewType.SWITCHUSER, u, Optional.empty(), Optional.empty(), Optional.empty());
}
public int confirmationBox()
{
JFrame jf=new JFrame();
jf.setAlwaysOnTop(true);
JLabel label = new JLabel("Are You Sure You Want to Exit?");
label.setFont(new Font("Arial", Font.BOLD, 24));
UIManager.put("OptionPane.minimumSize",new Dimension(150,100));
int input = JOptionPane.showConfirmDialog(jf, label);
return input;
}
public void changeView(ViewType viewType, User user, Optional<MediaItem> item, Optional<ArrayList<Music>> itemList, Optional<ArrayList<User>> userList)
{
String viewName = "";
Controller controller = null;
switch(viewType)
{
case HOMEVIEW:
viewName = "/View/HomeView.fxml";
controller = new HomeController(user);
break;
case WELCOMEVIEW:
viewName = "/View/WelcomeView.fxml";
controller = new MainController(user);
break;
case VIDEOVIEW:
viewName = "/View/MediaListView.fxml";
controller = new VideoController(user);
break;
case MUSICPLAYERVIEW:
viewName = "/View/MusicPlayerView.fxml";
controller = new MusicPlayerController(user, item.get(), itemList.get());
break;
case MUSICVIEW:
viewName = "/View/MediaListView.fxml";
controller = new MusicController(user);
break;
case VIDEOPLAYERVIEW:
viewName = "/View/VideoPlayerView.fxml";
controller = new VideoPlayerController(user, item.get());
break;
case SPOTIFYVIEW:
viewName = "/View/SpotifyView.fxml";
controller = new SpotifyController(user);
case SWITCHUSER:
viewName = "/View/SwitchUserView.fxml";
controller = new SwitchUserController(user);
break;
case ADDUSER:
viewName = "/View/NewUserView.fxml";
controller = new NewUserController(user, userList.get());
break;
}
try {
FXMLLoader loader = new FXMLLoader(this.getClass().getResource(viewName));
loader.setController(controller);
StackPane pane = loader.load();
panel.getChildren().setAll(pane);
fade.stop();
fade = new FadeTransition(Duration.millis(750), panel);
fade.setFromValue(0);
fade.setToValue(1);
fade.play();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
if(!u.getImgSrc().equals("Resources/rounded-512.png"))
{
try {
userImg.setImage(new Image(new File(u.getImgSrc()).toURI().toURL().toExternalForm()));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
userNameText.setText(u.getUserName());
welcomeText.setStyle("-fx-font-family: 'Rubik Mono One', sans-serif; -fx-font-size: 140;");
welcomeText.setWrappingWidth(400);
fade = new FadeTransition(Duration.millis(1450), panel);
fade.setFromValue(1.0);
fade.setToValue(0.95);
fade.setCycleCount(Timeline.INDEFINITE);
fade.setAutoReverse(true);
fade.play();
}
}
| UTF-8 | Java | 5,222 | java | MainController.java | Java | [] | null | [] | package Controller;
import java.awt.Dimension;
import java.awt.Font;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Optional;
import java.util.ResourceBundle;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import Model.MediaItem;
import Model.Music;
import Model.User;
import javafx.animation.FadeTransition;
import javafx.animation.Timeline;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.StackPane;
import javafx.scene.media.MediaPlayer;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;
public class MainController implements Initializable, Controller{
private final int cid = 1;
private static MainController instance = null;
private Controller currentController = null;
FadeTransition fade;
private User u;
@FXML
ImageView userImg;
@FXML
ImageView powerImg;
@FXML
StackPane panel;
@FXML
Text welcomeText;
@FXML
Text userNameText;
public MainController()
{
}
public MainController(User user)
{
u = user;
}
public static MainController getInstance()
{
if (instance == null)
instance = new MainController();
return instance;
}
public void setUser(User user)
{
u = user;
}
public User getUser()
{
return u;
}
public int getId()
{
return cid;
}
@FXML
public void loginAction()
{
fade.stop();
fade = new FadeTransition(Duration.millis(750), panel);
fade.setFromValue(1.0);
fade.setToValue(0);
fade.play();
changeView(ViewType.HOMEVIEW, u, Optional.empty(), Optional.empty(), Optional.empty());
}
@FXML
public void exitApplication()
{
int input = confirmationBox();
if(input == 0)
{
System.exit(0);
}
else {
return;
}
}
@FXML
public void switchUser()
{
changeView(ViewType.SWITCHUSER, u, Optional.empty(), Optional.empty(), Optional.empty());
}
public int confirmationBox()
{
JFrame jf=new JFrame();
jf.setAlwaysOnTop(true);
JLabel label = new JLabel("Are You Sure You Want to Exit?");
label.setFont(new Font("Arial", Font.BOLD, 24));
UIManager.put("OptionPane.minimumSize",new Dimension(150,100));
int input = JOptionPane.showConfirmDialog(jf, label);
return input;
}
public void changeView(ViewType viewType, User user, Optional<MediaItem> item, Optional<ArrayList<Music>> itemList, Optional<ArrayList<User>> userList)
{
String viewName = "";
Controller controller = null;
switch(viewType)
{
case HOMEVIEW:
viewName = "/View/HomeView.fxml";
controller = new HomeController(user);
break;
case WELCOMEVIEW:
viewName = "/View/WelcomeView.fxml";
controller = new MainController(user);
break;
case VIDEOVIEW:
viewName = "/View/MediaListView.fxml";
controller = new VideoController(user);
break;
case MUSICPLAYERVIEW:
viewName = "/View/MusicPlayerView.fxml";
controller = new MusicPlayerController(user, item.get(), itemList.get());
break;
case MUSICVIEW:
viewName = "/View/MediaListView.fxml";
controller = new MusicController(user);
break;
case VIDEOPLAYERVIEW:
viewName = "/View/VideoPlayerView.fxml";
controller = new VideoPlayerController(user, item.get());
break;
case SPOTIFYVIEW:
viewName = "/View/SpotifyView.fxml";
controller = new SpotifyController(user);
case SWITCHUSER:
viewName = "/View/SwitchUserView.fxml";
controller = new SwitchUserController(user);
break;
case ADDUSER:
viewName = "/View/NewUserView.fxml";
controller = new NewUserController(user, userList.get());
break;
}
try {
FXMLLoader loader = new FXMLLoader(this.getClass().getResource(viewName));
loader.setController(controller);
StackPane pane = loader.load();
panel.getChildren().setAll(pane);
fade.stop();
fade = new FadeTransition(Duration.millis(750), panel);
fade.setFromValue(0);
fade.setToValue(1);
fade.play();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
if(!u.getImgSrc().equals("Resources/rounded-512.png"))
{
try {
userImg.setImage(new Image(new File(u.getImgSrc()).toURI().toURL().toExternalForm()));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
userNameText.setText(u.getUserName());
welcomeText.setStyle("-fx-font-family: 'Rubik Mono One', sans-serif; -fx-font-size: 140;");
welcomeText.setWrappingWidth(400);
fade = new FadeTransition(Duration.millis(1450), panel);
fade.setFromValue(1.0);
fade.setToValue(0.95);
fade.setCycleCount(Timeline.INDEFINITE);
fade.setAutoReverse(true);
fade.play();
}
}
| 5,222 | 0.682689 | 0.674646 | 205 | 23.473171 | 21.773008 | 153 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.42439 | false | false | 9 |
3bfbd791fe92489ac8d1837083ad3300f859f48d | 23,553,600,702,441 | 765871ea18172edcdb86cf35a9f7e35c32144120 | /app/src/main/java/net/ddns/vidapet/vidapet/ConversaActivity.java | cbbb2772bba3598c360cfb85ecf7f2dd7257e6f5 | [] | no_license | FabioLafayete/Vida-PET | https://github.com/FabioLafayete/Vida-PET | 01b131415b6a3b215b8e0f86ba9789b3dc83f30a | 9453a6e2d188c3e73a8d4a9eea49f6daf87776b3 | refs/heads/master | 2022-11-22T01:56:51.912000 | 2020-07-28T20:01:04 | 2020-07-28T20:01:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.ddns.vidapet.vidapet;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
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 net.ddns.vidapet.adapter.MensagemAdapter;
import net.ddns.vidapet.helper.Base64Custom;
import net.ddns.vidapet.helper.Preferences;
import net.ddns.vidapet.model.Conversa;
import net.ddns.vidapet.model.Mensagem;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import de.hdodenhof.circleimageview.CircleImageView;
public class ConversaActivity extends AppCompatActivity {
private Toolbar toolbar;
private EditText editMensagem;
private ImageButton btEnviar;
private DatabaseReference databaseReference, databaseReference2, databaseReference3, databaseIMG;
private ListView lvMensagens;
private ArrayAdapter<Mensagem> arrayAdapter;
private ArrayList<Mensagem> arrayListmensagens;
private ValueEventListener valueEventListenerMensagens;
private Conversa conversa;
private TextView nomeContato;
private CircleImageView imgContato;
private ImageView btnVoltar;
//DESTINATARIO
private String nomeUsuarioDestinatario;
private String idUsuarioDestinatario;
//REMETENTE
private String idUsuarioLogado;
private String nomeUsuarioLogado;
private String mydate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_conversa);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
boolean connected = false;
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if((connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null && connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED)
|| (connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null && connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.getState() == NetworkInfo.State.CONNECTED)) {
//we are connected to a network
connected = true;
} else {
connected = false;
Toast.makeText(getApplicationContext(), "Sem conexão com a Internet", Toast.LENGTH_SHORT).show();
}
toolbar = (Toolbar) findViewById(R.id.tb_Conversa);
editMensagem = (EditText) findViewById(R.id.edit_mensagem);
btEnviar = (ImageButton) findViewById(R.id.bt_enviar);
lvMensagens = (ListView) findViewById(R.id.lv_mensagens);
nomeContato = (TextView) findViewById(R.id.txt_toolbar);
btnVoltar = (ImageView) findViewById(R.id.img_voltar_toolbar);
btnVoltar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
finish();
}
});
//RECUPERAR DADOS DO USUARIO LOGADO
Preferences preferences = new Preferences(ConversaActivity.this);
idUsuarioLogado = preferences.getIdentificador();
nomeUsuarioLogado = preferences.getNome();
//RECUPERAR DADOS ENVIADOS NA INTENT
Bundle extra = getIntent().getExtras(); //OBJETO UTILIZADO PARA ENVIAR DADOS ENTRE INTENTS
if(extra != null){
//RECUPERAR DADOS (DESTINATARIO)
nomeUsuarioDestinatario = extra.getString("nome");
idUsuarioDestinatario = Base64Custom.converterBase64(extra.getString("email"));
}
//CONFIGURANDO A TOOLBAR
//toolbar.setTitle(nomeUsuarioDestinatario);
//toolbar.setNavigationIcon(R.drawable.ic_keyboard_arrow_left);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
/***********************************************************
* IMAGEM USUARIO CONTATO
***********************************************************/
nomeContato.setText(nomeUsuarioDestinatario);
nomeContato.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
abrirPerfil();
}
});
databaseIMG = FirebaseDatabase.getInstance().getReference()
.child("FotoPerfil")
.child(idUsuarioDestinatario)
.child("imagem");
databaseIMG.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
imgContato = (CircleImageView) findViewById(R.id.img_toolbar);
if(dataSnapshot.getValue() != null){
Object url = dataSnapshot.getValue(Object.class);
Glide.with(getApplicationContext()).load(url).into(imgContato);
}else {
imgContato.setImageResource(R.drawable.img_usuario);
}
imgContato.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
abrirPerfil();
}
});
}
@Override
public void onCancelled(DatabaseError databaseError) {
imgContato = (CircleImageView) findViewById(R.id.imgTelaUsuarioHomePage);
imgContato.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(ConversaActivity.this, TelaUsuario.class));
}
});
}
});
/***********************************************************
* MONTAGEM LISTVIEW E ADAPTER
***********************************************************/
arrayListmensagens = new ArrayList<>();
/*arrayAdapter = new ArrayAdapter<String>(
ConversaActivity.this,
android.R.layout.simple_list_item_1,
arrayListmensagens
);*/
arrayAdapter = new MensagemAdapter(ConversaActivity.this, arrayListmensagens);
lvMensagens.setAdapter(arrayAdapter);
/***********************************************************
* RECUPERAR MENSAGENS
***********************************************************/
databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference = databaseReference.child("Mensagens")
.child(idUsuarioLogado)
.child(idUsuarioDestinatario);
databaseReference.keepSynced(true);
//CRIAR LISTENER PARA MENSAGENS
valueEventListenerMensagens = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//LIMPAR ARRAY DE MENSAGENS
arrayListmensagens.clear();
//RECUPERAR MENSAGENS
for(DataSnapshot dados: dataSnapshot.getChildren()){
//RECUPERAR MENSAGEM INDIVIDUAL
Mensagem mensagem = dados.getValue(Mensagem.class);
//ADICIONAR AO LIST
arrayListmensagens.add(mensagem);
}
arrayAdapter.notifyDataSetChanged(); //Notificando que dados mudaram
lvMensagens.setSelection(lvMensagens.getAdapter().getCount() - 1);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
databaseReference.addValueEventListener(valueEventListenerMensagens);
//ENVIAR MENSAGEM
btEnviar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String textoMensagem = editMensagem.getText().toString();
//VERFICAR SE FOI PREECHIDA A MENSAGEM
if(textoMensagem.isEmpty()){
Toast.makeText(ConversaActivity.this, "Por favor, preencha o campo de mensagem antes de enviar :)",
Toast.LENGTH_SHORT).show();
} else{
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
mydate = sdf.format(new Date());
/**************************************************************************
* SALVAR MENSAGENS NO FIREBASE
**************************************************************************/
Mensagem mensagem = new Mensagem();
mensagem.setIdUsuario(idUsuarioLogado);
mensagem.setMensagem(textoMensagem);
mensagem.setData(mydate);
//SALVAR MENSAGEM PARA O REMETENTE
Boolean retornoRemetente = salvarMensagemFirebase(idUsuarioLogado, idUsuarioDestinatario, mensagem);
if(!retornoRemetente){
Toast.makeText(ConversaActivity.this, "Erro ao enviar mensagens", Toast.LENGTH_SHORT).show();
}
//SALVAR MENSAGEM PARA O DESTINATARIO
Boolean retornoDestinatario = salvarMensagemFirebase(idUsuarioDestinatario, idUsuarioLogado, mensagem);
if(!retornoDestinatario){
Toast.makeText(ConversaActivity.this, "Erro ao enviar mensagens", Toast.LENGTH_SHORT).show();
}
/**************************************************************************
* SALVAR CONVERSAS
**************************************************************************/
//SALVAR CONVERSA REMETENTE
conversa = new Conversa();
conversa.setIdUsuario(idUsuarioDestinatario);
conversa.setNome(nomeUsuarioDestinatario);
conversa.setMensagem(textoMensagem);
conversa.setData(mydate);
conversa.setEmail(Base64Custom.decodificadorBase64(idUsuarioDestinatario));
Boolean retornoConvRem = salvarConversaFirebase(idUsuarioLogado, idUsuarioDestinatario, conversa);
if(!retornoConvRem){
Toast.makeText(ConversaActivity.this, "Erro ao salvar mensagens", Toast.LENGTH_SHORT).show();
}
//SALVAR CONVERSA DESTINATARIO
conversa = new Conversa();
conversa.setIdUsuario(idUsuarioLogado);
conversa.setNome(nomeUsuarioLogado);
conversa.setMensagem(textoMensagem);
conversa.setData(mydate);
conversa.setEmail(Base64Custom.decodificadorBase64(idUsuarioLogado));
Boolean retornoConvDest = salvarConversaFirebase(idUsuarioDestinatario, idUsuarioLogado, conversa);
if(!retornoConvDest){
Toast.makeText(ConversaActivity.this, "Erro ao salvar mensagens", Toast.LENGTH_SHORT).show();
}
//APAGAR TEXTO DIGITADO APÓS ENVIAR
editMensagem.setText("");
}
}
});
}
public static void showToolBar(Toolbar toolbar,
final AppCompatActivity activity) {
activity.setSupportActionBar(toolbar);
activity.getSupportActionBar().setDisplayShowTitleEnabled(false);
@SuppressWarnings("deprecation")
Drawable drawable = activity.getResources().getDrawable(
R.drawable.img_usuario);
drawable.setColorFilter(
activity.getResources().getColor(R.color.colorPrimaryDark),
android.graphics.PorterDuff.Mode.SRC_ATOP);
activity.getSupportActionBar().setHomeAsUpIndicator(drawable);
toolbar.setBackgroundColor(activity.getResources().getColor(
R.color.colorPrimary));
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
activity.finish();
}
});
}
private Boolean salvarMensagemFirebase(String idRemetente, String idDestinatario, Mensagem mensagem ){
try{
databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference = databaseReference.child("Mensagens");
databaseReference.child(idRemetente)
.child(idDestinatario)
.push()
.setValue(mensagem);
return true;
} catch (Exception e){
e.printStackTrace();
return false;
}
}
private Boolean salvarConversaFirebase(String idRemetente, String idDestinatario, Conversa conversa ){
try{
databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference = databaseReference.child("Conversas");
databaseReference.child(idRemetente)
.child(idDestinatario)
.setValue(conversa);
return true;
} catch (Exception e){
e.printStackTrace();
return false;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_conversas, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.item_ver_perfil: abrirPerfil();
return true;
case R.id.item_limpar_conversa: limparConversa();
return true;
case R.id.item_apagar_conversa: apagarConversa();
default: return super.onOptionsItemSelected(item);
}
}
private void abrirPerfil(){
Preferences preferences = new Preferences(ConversaActivity.this);
Intent intent = new Intent(ConversaActivity.this, TelaPerfilAnfitriao.class);
intent.putExtra("emailAnfitriao", Base64Custom.decodificadorBase64(idUsuarioDestinatario)); //data is a string variable holding some value.
intent.putExtra("itemMensagem", "false");
startActivity(intent);
}
public void limparConversa(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(ConversaActivity.this);
//Configurando a AlertDialog
alertDialog.setTitle("Limpar conversa");
alertDialog.setMessage("Deseja realmente limpar esta conversa?");
alertDialog.setCancelable(false);
//BOTAO SIM
alertDialog.setPositiveButton("SIM", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
databaseReference2 = FirebaseDatabase.getInstance().getReference()
.child("Mensagens")
.child(idUsuarioLogado)
.child(idUsuarioDestinatario);
databaseReference2.removeValue();
//SALVAR CONVERSA REMETENTE
conversa = new Conversa();
conversa.setIdUsuario(idUsuarioDestinatario);
conversa.setNome(nomeUsuarioDestinatario);
conversa.setMensagem("");
conversa.setEmail(Base64Custom.decodificadorBase64(idUsuarioDestinatario));
Boolean retornoConvRem = salvarConversaFirebase(idUsuarioLogado, idUsuarioDestinatario, conversa);
if(!retornoConvRem){
Toast.makeText(ConversaActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
Toast.makeText(getApplicationContext(), "Conversa limpa!", Toast.LENGTH_SHORT).show();
}
});
//BOTAO CANCELAR
alertDialog.setNegativeButton("NÃO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.create();
alertDialog.show();
}
private void apagarConversa(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(ConversaActivity.this);
//Configurando a AlertDialog
alertDialog.setTitle("Apagar conversa");
alertDialog.setMessage("Deseja realmente apagar esta conversa?");
alertDialog.setCancelable(false);
//BOTAO SIM
alertDialog.setPositiveButton("SIM", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
databaseReference2 = FirebaseDatabase.getInstance().getReference()
.child("Mensagens")
.child(idUsuarioLogado)
.child(idUsuarioDestinatario);
databaseReference2.removeValue();
databaseReference3 = FirebaseDatabase.getInstance().getReference()
.child("Conversas")
.child(idUsuarioLogado)
.child(idUsuarioDestinatario);
databaseReference3.removeValue();
startActivity(new Intent(ConversaActivity.this, TelaMensagem.class));
finish();
Toast.makeText(getApplicationContext(), "Conversa apagada!", Toast.LENGTH_SHORT).show();
}
});
//BOTAO CANCELAR
alertDialog.setNegativeButton("NÃO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.create();
alertDialog.show();
}
@Override
protected void onStop() {
super.onStop();
databaseReference.removeEventListener(valueEventListenerMensagens);
}
@Override
protected void onRestart() {
super.onRestart();
databaseReference.addValueEventListener(valueEventListenerMensagens);
}
}
| UTF-8 | Java | 20,376 | java | ConversaActivity.java | Java | [] | null | [] | package net.ddns.vidapet.vidapet;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
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 net.ddns.vidapet.adapter.MensagemAdapter;
import net.ddns.vidapet.helper.Base64Custom;
import net.ddns.vidapet.helper.Preferences;
import net.ddns.vidapet.model.Conversa;
import net.ddns.vidapet.model.Mensagem;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import de.hdodenhof.circleimageview.CircleImageView;
public class ConversaActivity extends AppCompatActivity {
private Toolbar toolbar;
private EditText editMensagem;
private ImageButton btEnviar;
private DatabaseReference databaseReference, databaseReference2, databaseReference3, databaseIMG;
private ListView lvMensagens;
private ArrayAdapter<Mensagem> arrayAdapter;
private ArrayList<Mensagem> arrayListmensagens;
private ValueEventListener valueEventListenerMensagens;
private Conversa conversa;
private TextView nomeContato;
private CircleImageView imgContato;
private ImageView btnVoltar;
//DESTINATARIO
private String nomeUsuarioDestinatario;
private String idUsuarioDestinatario;
//REMETENTE
private String idUsuarioLogado;
private String nomeUsuarioLogado;
private String mydate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_conversa);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
boolean connected = false;
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if((connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null && connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED)
|| (connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null && connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.getState() == NetworkInfo.State.CONNECTED)) {
//we are connected to a network
connected = true;
} else {
connected = false;
Toast.makeText(getApplicationContext(), "Sem conexão com a Internet", Toast.LENGTH_SHORT).show();
}
toolbar = (Toolbar) findViewById(R.id.tb_Conversa);
editMensagem = (EditText) findViewById(R.id.edit_mensagem);
btEnviar = (ImageButton) findViewById(R.id.bt_enviar);
lvMensagens = (ListView) findViewById(R.id.lv_mensagens);
nomeContato = (TextView) findViewById(R.id.txt_toolbar);
btnVoltar = (ImageView) findViewById(R.id.img_voltar_toolbar);
btnVoltar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
finish();
}
});
//RECUPERAR DADOS DO USUARIO LOGADO
Preferences preferences = new Preferences(ConversaActivity.this);
idUsuarioLogado = preferences.getIdentificador();
nomeUsuarioLogado = preferences.getNome();
//RECUPERAR DADOS ENVIADOS NA INTENT
Bundle extra = getIntent().getExtras(); //OBJETO UTILIZADO PARA ENVIAR DADOS ENTRE INTENTS
if(extra != null){
//RECUPERAR DADOS (DESTINATARIO)
nomeUsuarioDestinatario = extra.getString("nome");
idUsuarioDestinatario = Base64Custom.converterBase64(extra.getString("email"));
}
//CONFIGURANDO A TOOLBAR
//toolbar.setTitle(nomeUsuarioDestinatario);
//toolbar.setNavigationIcon(R.drawable.ic_keyboard_arrow_left);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
/***********************************************************
* IMAGEM USUARIO CONTATO
***********************************************************/
nomeContato.setText(nomeUsuarioDestinatario);
nomeContato.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
abrirPerfil();
}
});
databaseIMG = FirebaseDatabase.getInstance().getReference()
.child("FotoPerfil")
.child(idUsuarioDestinatario)
.child("imagem");
databaseIMG.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
imgContato = (CircleImageView) findViewById(R.id.img_toolbar);
if(dataSnapshot.getValue() != null){
Object url = dataSnapshot.getValue(Object.class);
Glide.with(getApplicationContext()).load(url).into(imgContato);
}else {
imgContato.setImageResource(R.drawable.img_usuario);
}
imgContato.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
abrirPerfil();
}
});
}
@Override
public void onCancelled(DatabaseError databaseError) {
imgContato = (CircleImageView) findViewById(R.id.imgTelaUsuarioHomePage);
imgContato.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(ConversaActivity.this, TelaUsuario.class));
}
});
}
});
/***********************************************************
* MONTAGEM LISTVIEW E ADAPTER
***********************************************************/
arrayListmensagens = new ArrayList<>();
/*arrayAdapter = new ArrayAdapter<String>(
ConversaActivity.this,
android.R.layout.simple_list_item_1,
arrayListmensagens
);*/
arrayAdapter = new MensagemAdapter(ConversaActivity.this, arrayListmensagens);
lvMensagens.setAdapter(arrayAdapter);
/***********************************************************
* RECUPERAR MENSAGENS
***********************************************************/
databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference = databaseReference.child("Mensagens")
.child(idUsuarioLogado)
.child(idUsuarioDestinatario);
databaseReference.keepSynced(true);
//CRIAR LISTENER PARA MENSAGENS
valueEventListenerMensagens = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//LIMPAR ARRAY DE MENSAGENS
arrayListmensagens.clear();
//RECUPERAR MENSAGENS
for(DataSnapshot dados: dataSnapshot.getChildren()){
//RECUPERAR MENSAGEM INDIVIDUAL
Mensagem mensagem = dados.getValue(Mensagem.class);
//ADICIONAR AO LIST
arrayListmensagens.add(mensagem);
}
arrayAdapter.notifyDataSetChanged(); //Notificando que dados mudaram
lvMensagens.setSelection(lvMensagens.getAdapter().getCount() - 1);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
databaseReference.addValueEventListener(valueEventListenerMensagens);
//ENVIAR MENSAGEM
btEnviar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String textoMensagem = editMensagem.getText().toString();
//VERFICAR SE FOI PREECHIDA A MENSAGEM
if(textoMensagem.isEmpty()){
Toast.makeText(ConversaActivity.this, "Por favor, preencha o campo de mensagem antes de enviar :)",
Toast.LENGTH_SHORT).show();
} else{
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
mydate = sdf.format(new Date());
/**************************************************************************
* SALVAR MENSAGENS NO FIREBASE
**************************************************************************/
Mensagem mensagem = new Mensagem();
mensagem.setIdUsuario(idUsuarioLogado);
mensagem.setMensagem(textoMensagem);
mensagem.setData(mydate);
//SALVAR MENSAGEM PARA O REMETENTE
Boolean retornoRemetente = salvarMensagemFirebase(idUsuarioLogado, idUsuarioDestinatario, mensagem);
if(!retornoRemetente){
Toast.makeText(ConversaActivity.this, "Erro ao enviar mensagens", Toast.LENGTH_SHORT).show();
}
//SALVAR MENSAGEM PARA O DESTINATARIO
Boolean retornoDestinatario = salvarMensagemFirebase(idUsuarioDestinatario, idUsuarioLogado, mensagem);
if(!retornoDestinatario){
Toast.makeText(ConversaActivity.this, "Erro ao enviar mensagens", Toast.LENGTH_SHORT).show();
}
/**************************************************************************
* SALVAR CONVERSAS
**************************************************************************/
//SALVAR CONVERSA REMETENTE
conversa = new Conversa();
conversa.setIdUsuario(idUsuarioDestinatario);
conversa.setNome(nomeUsuarioDestinatario);
conversa.setMensagem(textoMensagem);
conversa.setData(mydate);
conversa.setEmail(Base64Custom.decodificadorBase64(idUsuarioDestinatario));
Boolean retornoConvRem = salvarConversaFirebase(idUsuarioLogado, idUsuarioDestinatario, conversa);
if(!retornoConvRem){
Toast.makeText(ConversaActivity.this, "Erro ao salvar mensagens", Toast.LENGTH_SHORT).show();
}
//SALVAR CONVERSA DESTINATARIO
conversa = new Conversa();
conversa.setIdUsuario(idUsuarioLogado);
conversa.setNome(nomeUsuarioLogado);
conversa.setMensagem(textoMensagem);
conversa.setData(mydate);
conversa.setEmail(Base64Custom.decodificadorBase64(idUsuarioLogado));
Boolean retornoConvDest = salvarConversaFirebase(idUsuarioDestinatario, idUsuarioLogado, conversa);
if(!retornoConvDest){
Toast.makeText(ConversaActivity.this, "Erro ao salvar mensagens", Toast.LENGTH_SHORT).show();
}
//APAGAR TEXTO DIGITADO APÓS ENVIAR
editMensagem.setText("");
}
}
});
}
public static void showToolBar(Toolbar toolbar,
final AppCompatActivity activity) {
activity.setSupportActionBar(toolbar);
activity.getSupportActionBar().setDisplayShowTitleEnabled(false);
@SuppressWarnings("deprecation")
Drawable drawable = activity.getResources().getDrawable(
R.drawable.img_usuario);
drawable.setColorFilter(
activity.getResources().getColor(R.color.colorPrimaryDark),
android.graphics.PorterDuff.Mode.SRC_ATOP);
activity.getSupportActionBar().setHomeAsUpIndicator(drawable);
toolbar.setBackgroundColor(activity.getResources().getColor(
R.color.colorPrimary));
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
activity.finish();
}
});
}
private Boolean salvarMensagemFirebase(String idRemetente, String idDestinatario, Mensagem mensagem ){
try{
databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference = databaseReference.child("Mensagens");
databaseReference.child(idRemetente)
.child(idDestinatario)
.push()
.setValue(mensagem);
return true;
} catch (Exception e){
e.printStackTrace();
return false;
}
}
private Boolean salvarConversaFirebase(String idRemetente, String idDestinatario, Conversa conversa ){
try{
databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference = databaseReference.child("Conversas");
databaseReference.child(idRemetente)
.child(idDestinatario)
.setValue(conversa);
return true;
} catch (Exception e){
e.printStackTrace();
return false;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_conversas, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.item_ver_perfil: abrirPerfil();
return true;
case R.id.item_limpar_conversa: limparConversa();
return true;
case R.id.item_apagar_conversa: apagarConversa();
default: return super.onOptionsItemSelected(item);
}
}
private void abrirPerfil(){
Preferences preferences = new Preferences(ConversaActivity.this);
Intent intent = new Intent(ConversaActivity.this, TelaPerfilAnfitriao.class);
intent.putExtra("emailAnfitriao", Base64Custom.decodificadorBase64(idUsuarioDestinatario)); //data is a string variable holding some value.
intent.putExtra("itemMensagem", "false");
startActivity(intent);
}
public void limparConversa(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(ConversaActivity.this);
//Configurando a AlertDialog
alertDialog.setTitle("Limpar conversa");
alertDialog.setMessage("Deseja realmente limpar esta conversa?");
alertDialog.setCancelable(false);
//BOTAO SIM
alertDialog.setPositiveButton("SIM", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
databaseReference2 = FirebaseDatabase.getInstance().getReference()
.child("Mensagens")
.child(idUsuarioLogado)
.child(idUsuarioDestinatario);
databaseReference2.removeValue();
//SALVAR CONVERSA REMETENTE
conversa = new Conversa();
conversa.setIdUsuario(idUsuarioDestinatario);
conversa.setNome(nomeUsuarioDestinatario);
conversa.setMensagem("");
conversa.setEmail(Base64Custom.decodificadorBase64(idUsuarioDestinatario));
Boolean retornoConvRem = salvarConversaFirebase(idUsuarioLogado, idUsuarioDestinatario, conversa);
if(!retornoConvRem){
Toast.makeText(ConversaActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
Toast.makeText(getApplicationContext(), "Conversa limpa!", Toast.LENGTH_SHORT).show();
}
});
//BOTAO CANCELAR
alertDialog.setNegativeButton("NÃO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.create();
alertDialog.show();
}
private void apagarConversa(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(ConversaActivity.this);
//Configurando a AlertDialog
alertDialog.setTitle("Apagar conversa");
alertDialog.setMessage("Deseja realmente apagar esta conversa?");
alertDialog.setCancelable(false);
//BOTAO SIM
alertDialog.setPositiveButton("SIM", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
databaseReference2 = FirebaseDatabase.getInstance().getReference()
.child("Mensagens")
.child(idUsuarioLogado)
.child(idUsuarioDestinatario);
databaseReference2.removeValue();
databaseReference3 = FirebaseDatabase.getInstance().getReference()
.child("Conversas")
.child(idUsuarioLogado)
.child(idUsuarioDestinatario);
databaseReference3.removeValue();
startActivity(new Intent(ConversaActivity.this, TelaMensagem.class));
finish();
Toast.makeText(getApplicationContext(), "Conversa apagada!", Toast.LENGTH_SHORT).show();
}
});
//BOTAO CANCELAR
alertDialog.setNegativeButton("NÃO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.create();
alertDialog.show();
}
@Override
protected void onStop() {
super.onStop();
databaseReference.removeEventListener(valueEventListenerMensagens);
}
@Override
protected void onRestart() {
super.onRestart();
databaseReference.addValueEventListener(valueEventListenerMensagens);
}
}
| 20,376 | 0.574318 | 0.5726 | 497 | 38.989941 | 30.781666 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545272 | false | false | 9 |
4ef6faa6f278237de2d63fd969f1c691a1d2e976 | 15,556,371,590,504 | a3cca2a4c20fe7b8153012a1a65ccbc5d7896013 | /src/main/java/com/gpsmonitoring/dao/IGpsDao.java | 836281c0c54eb627bf12f68dfd926b1072915fe4 | [] | no_license | ATsurkanu/GpsMonitoring | https://github.com/ATsurkanu/GpsMonitoring | bcf5e27351e52b36304a9428d3028e8ec8d7bab6 | 6e5124af360a13180caa3998f4b0ad392ec0fe2e | refs/heads/master | 2020-04-06T07:02:31.630000 | 2016-09-14T15:28:54 | 2016-09-14T15:28:54 | 60,758,234 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.gpsmonitoring.dao;
import java.util.List;
import com.gpsmonitoring.entity.GpsPosition;
public interface IGpsDao {
void savePosition(GpsPosition position);
List<GpsPosition> getAllPositions();
List<GpsPosition> getPositionsByDriverId(Long driverId);
}
| UTF-8 | Java | 276 | java | IGpsDao.java | Java | [] | null | [] | package com.gpsmonitoring.dao;
import java.util.List;
import com.gpsmonitoring.entity.GpsPosition;
public interface IGpsDao {
void savePosition(GpsPosition position);
List<GpsPosition> getAllPositions();
List<GpsPosition> getPositionsByDriverId(Long driverId);
}
| 276 | 0.793478 | 0.793478 | 15 | 17.4 | 19.591835 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 9 |
a018c56cff6d6ec77f5ff13f10855a7ca2cf30e9 | 29,703,993,854,316 | 4d105b057626eb05f6b4a3196bd4debdd68867c4 | /src/main/java/com/ssm/chapter2/builder/TicketBuilder.java | 3e2eb8ab1bfda068b2b238ce8b4d2879fd47cb90 | [] | no_license | kujin521/SSM | https://github.com/kujin521/SSM | 8d9b772763882e7eb835182c21ea2f3b2b3425c8 | dbace5457f4c9c9eac004778e52a3f23b9be40b5 | refs/heads/master | 2020-07-10T04:40:11.344000 | 2019-08-24T14:36:43 | 2019-08-24T14:36:43 | 204,169,310 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package main.java.com.ssm.chapter2.builder;
public class TicketBuilder {
public static Object builder(TicketHelper helper) {
System.out.println("ͨ��TicketHelper������Ʊ��Ϣ");
return null;
}
}
| UTF-8 | Java | 221 | java | TicketBuilder.java | Java | [] | null | [] | package main.java.com.ssm.chapter2.builder;
public class TicketBuilder {
public static Object builder(TicketHelper helper) {
System.out.println("ͨ��TicketHelper������Ʊ��Ϣ");
return null;
}
}
| 221 | 0.722222 | 0.717172 | 8 | 23.75 | 20.992558 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.125 | false | false | 9 |
836706798abc459f1e634a7308101183768dc8b9 | 35,553,739,283,928 | 838c596b4efa267c1f7b9e8a5d90af3df7d526f3 | /JustDemo/src/com/ngandroid/demo/TopicActivity.java | f60294ae00b0f2447bb49f3eb20d7f4c1d75d01c | [] | no_license | jiang4920/JustDemo | https://github.com/jiang4920/JustDemo | f9c21a811d38d2b45a6abbdf65c787eba15f033f | 8436f74d8e9d3a3a2b253b8006eadc3522e3e22c | refs/heads/master | 2020-04-05T23:06:10.033000 | 2013-11-07T06:00:06 | 2013-11-07T06:00:06 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ngandroid.demo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import com.ngandroid.demo.adapter.TopicListAdapter;
import com.ngandroid.demo.topic.IDataLoadedListener;
import com.ngandroid.demo.topic.content.TopicData;
import com.ngandroid.demo.topic.content.TopicListData;
import com.ngandroid.demo.topic.task.TopicListTask;
import com.ngandroid.demo.util.NGAURL;
import com.ngandroid.demo.util.PageUtil;
import com.ngandroid.demo.widget.PageSelectDialog;
import com.ngandroid.demo.widget.PageSelectDialog.OnSelectedListener;
public class TopicActivity extends Activity implements OnClickListener, OnCheckedChangeListener, OnItemClickListener {
private static final String TAG = "JustDemo TopicActivity.java";
private ListView topicLv;
private TopicListAdapter mTopicListAdapter;
/**
* 上一页
*/
public Button preBt;
/**
* 下一页
*/
public Button nextBt;
/**
* 发帖按钮
*/
private Button postBt;
private TextView pageTv;
private RadioGroup tabGroup;
//http://bbs.ngacn.cc/thread.php?lite=js&order_by=postdatedesc&fid=320&page=1
protected static final String POST = "&order_by=postdatedesc";
protected static final String REPLY = "&order_by=lastpostdesc";
protected static final String HEADER = "&order_by=postdatedesc";
protected static final String RECOMMAND = "&recommend=1";
private String topicParam = POST;
private ProgressBar progressBar;
TopicListData data;
String mFid;
String mUrl_base;
String mType;
TextView mTitleTv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_topic);
topicLv = (ListView)findViewById(R.id.topic_list);
topicLv.setOnItemClickListener(this);
preBt = (Button)findViewById(R.id.topic_arrow_left);
nextBt = (Button)findViewById(R.id.topic_arrow_right);
postBt = (Button)findViewById(R.id.topic_post);
findViewById(R.id.topic_page).setOnClickListener(this);
mTitleTv = (TextView)findViewById(R.id.guide_head_title);
postBt.setOnClickListener(this);
preBt.setOnClickListener(this);
nextBt.setOnClickListener(this);
pageTv = (TextView)findViewById(R.id.topic_page);
tabGroup = (RadioGroup)findViewById(R.id.topic_tabs);
progressBar = (ProgressBar)findViewById(R.id.topic_progress);
tabGroup.setOnCheckedChangeListener(this);
mUrl_base = this.getIntent().getStringExtra("base_url");
mType = this.getIntent().getStringExtra("type");
tabGroup.setVisibility("commom_topic".equals(mType)?View.VISIBLE:View.GONE);
mTitleTv.setText(this.getIntent().getStringExtra("plate"));
refresh();
}
int mCurPageIndex = 1;
public void refresh(){
progressBar.setVisibility(View.VISIBLE);
String page = mCurPageIndex+"";
String param = topicParam;
String url = mUrl_base+param+ "&page=" + page;
new TopicListTask(this, new IDataLoadedListener() {
@Override
public void onPostFinished(Object obj) {
data = (TopicListData) obj;
if (mTopicListAdapter == null) {
mTopicListAdapter = new TopicListAdapter(
TopicActivity.this, data);
topicLv.setAdapter(mTopicListAdapter);
} else {
mTopicListAdapter.refresh(data);
}
topicLv.smoothScrollToPosition(0);
Log.v(TAG, "mCurPageIndex:"+mCurPageIndex);
pageTv.setText(""+mCurPageIndex);
progressBar.setVisibility(View.GONE);
}
@Override
public void onPostError(Integer status) {
}
}).execute(url);
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.topic_arrow_left:
mCurPageIndex = PageUtil.prePage(mCurPageIndex);
refresh();
break;
case R.id.topic_arrow_right:
if(data != null){
Log.v(TAG, "data.getTopicPageCount():"+data.getTopicPageCount());
mCurPageIndex = PageUtil.nextPage(mCurPageIndex, data.getTopicPageCount());
refresh();
}
break;
case R.id.topic_post:
Intent intent = new Intent();
intent.setClass(this, PostActivity.class);
intent.putExtra("action", "new");
intent.putExtra("fid", mFid);
this.startActivity(intent);
break;
case R.id.topic_page:
if(data!= null){
PageSelectDialog.create(this, data.getTopicPageCount(), listener).show();
}
break;
}
}
OnSelectedListener listener = new OnSelectedListener() {
@Override
public void onSelected(boolean isSelected, int page) {
if(isSelected){
mCurPageIndex = page;
refresh();
}
}
};
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.topic_new_topic:
topicParam = POST;
break;
case R.id.topic_new_reply:
topicParam = REPLY;
break;
case R.id.topic_header:
topicParam = HEADER;
break;
case R.id.topic_recommand:
topicParam = RECOMMAND;
break;
}
Log.v(TAG, "onCheckedChanged:"+topicParam);
mCurPageIndex = 1;
refresh();
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Log.v(TAG, "pos:"+arg2);
if(mTopicListAdapter.getItem(arg2) == null){
Log.v(TAG, "topic item is NULL, i do not know why!");
}
startReplyActivity(mTopicListAdapter.getItem(arg2));
}
private void startReplyActivity(TopicData topic){
Intent intent = new Intent();
intent.setClass(this, TopicReplyActivity.class);
intent.putExtra("topic", topic);
this.startActivity(intent);
}
}
| UTF-8 | Java | 6,252 | java | TopicActivity.java | Java | [] | null | [] | package com.ngandroid.demo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import com.ngandroid.demo.adapter.TopicListAdapter;
import com.ngandroid.demo.topic.IDataLoadedListener;
import com.ngandroid.demo.topic.content.TopicData;
import com.ngandroid.demo.topic.content.TopicListData;
import com.ngandroid.demo.topic.task.TopicListTask;
import com.ngandroid.demo.util.NGAURL;
import com.ngandroid.demo.util.PageUtil;
import com.ngandroid.demo.widget.PageSelectDialog;
import com.ngandroid.demo.widget.PageSelectDialog.OnSelectedListener;
public class TopicActivity extends Activity implements OnClickListener, OnCheckedChangeListener, OnItemClickListener {
private static final String TAG = "JustDemo TopicActivity.java";
private ListView topicLv;
private TopicListAdapter mTopicListAdapter;
/**
* 上一页
*/
public Button preBt;
/**
* 下一页
*/
public Button nextBt;
/**
* 发帖按钮
*/
private Button postBt;
private TextView pageTv;
private RadioGroup tabGroup;
//http://bbs.ngacn.cc/thread.php?lite=js&order_by=postdatedesc&fid=320&page=1
protected static final String POST = "&order_by=postdatedesc";
protected static final String REPLY = "&order_by=lastpostdesc";
protected static final String HEADER = "&order_by=postdatedesc";
protected static final String RECOMMAND = "&recommend=1";
private String topicParam = POST;
private ProgressBar progressBar;
TopicListData data;
String mFid;
String mUrl_base;
String mType;
TextView mTitleTv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_topic);
topicLv = (ListView)findViewById(R.id.topic_list);
topicLv.setOnItemClickListener(this);
preBt = (Button)findViewById(R.id.topic_arrow_left);
nextBt = (Button)findViewById(R.id.topic_arrow_right);
postBt = (Button)findViewById(R.id.topic_post);
findViewById(R.id.topic_page).setOnClickListener(this);
mTitleTv = (TextView)findViewById(R.id.guide_head_title);
postBt.setOnClickListener(this);
preBt.setOnClickListener(this);
nextBt.setOnClickListener(this);
pageTv = (TextView)findViewById(R.id.topic_page);
tabGroup = (RadioGroup)findViewById(R.id.topic_tabs);
progressBar = (ProgressBar)findViewById(R.id.topic_progress);
tabGroup.setOnCheckedChangeListener(this);
mUrl_base = this.getIntent().getStringExtra("base_url");
mType = this.getIntent().getStringExtra("type");
tabGroup.setVisibility("commom_topic".equals(mType)?View.VISIBLE:View.GONE);
mTitleTv.setText(this.getIntent().getStringExtra("plate"));
refresh();
}
int mCurPageIndex = 1;
public void refresh(){
progressBar.setVisibility(View.VISIBLE);
String page = mCurPageIndex+"";
String param = topicParam;
String url = mUrl_base+param+ "&page=" + page;
new TopicListTask(this, new IDataLoadedListener() {
@Override
public void onPostFinished(Object obj) {
data = (TopicListData) obj;
if (mTopicListAdapter == null) {
mTopicListAdapter = new TopicListAdapter(
TopicActivity.this, data);
topicLv.setAdapter(mTopicListAdapter);
} else {
mTopicListAdapter.refresh(data);
}
topicLv.smoothScrollToPosition(0);
Log.v(TAG, "mCurPageIndex:"+mCurPageIndex);
pageTv.setText(""+mCurPageIndex);
progressBar.setVisibility(View.GONE);
}
@Override
public void onPostError(Integer status) {
}
}).execute(url);
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.topic_arrow_left:
mCurPageIndex = PageUtil.prePage(mCurPageIndex);
refresh();
break;
case R.id.topic_arrow_right:
if(data != null){
Log.v(TAG, "data.getTopicPageCount():"+data.getTopicPageCount());
mCurPageIndex = PageUtil.nextPage(mCurPageIndex, data.getTopicPageCount());
refresh();
}
break;
case R.id.topic_post:
Intent intent = new Intent();
intent.setClass(this, PostActivity.class);
intent.putExtra("action", "new");
intent.putExtra("fid", mFid);
this.startActivity(intent);
break;
case R.id.topic_page:
if(data!= null){
PageSelectDialog.create(this, data.getTopicPageCount(), listener).show();
}
break;
}
}
OnSelectedListener listener = new OnSelectedListener() {
@Override
public void onSelected(boolean isSelected, int page) {
if(isSelected){
mCurPageIndex = page;
refresh();
}
}
};
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.topic_new_topic:
topicParam = POST;
break;
case R.id.topic_new_reply:
topicParam = REPLY;
break;
case R.id.topic_header:
topicParam = HEADER;
break;
case R.id.topic_recommand:
topicParam = RECOMMAND;
break;
}
Log.v(TAG, "onCheckedChanged:"+topicParam);
mCurPageIndex = 1;
refresh();
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Log.v(TAG, "pos:"+arg2);
if(mTopicListAdapter.getItem(arg2) == null){
Log.v(TAG, "topic item is NULL, i do not know why!");
}
startReplyActivity(mTopicListAdapter.getItem(arg2));
}
private void startReplyActivity(TopicData topic){
Intent intent = new Intent();
intent.setClass(this, TopicReplyActivity.class);
intent.putExtra("topic", topic);
this.startActivity(intent);
}
}
| 6,252 | 0.679615 | 0.677207 | 199 | 29.306532 | 21.972607 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.934673 | false | false | 9 |
5081262aad9a498f236eea15484fc154a069223d | 180,388,660,460 | 83380915dc4355ea4ea05307222c88f3077f83ab | /services/distribution/src/main/java/app/coronawarn/server/services/distribution/config/DistributionServiceConfig.java | 9c66ab2e4245b521519264cb17ecf9dc400e840c | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-unknown"
] | permissive | corona-warn-app/cwa-server | https://github.com/corona-warn-app/cwa-server | d1c4f25f44f5c2970c4351cf663d599dc4549a83 | c61d55f6f83b6d005cb6aca9e9b455afac572d72 | refs/heads/main | 2023-08-07T14:50:25.777000 | 2023-05-10T07:59:47 | 2023-05-10T07:59:47 | 260,712,390 | 2,174 | 497 | Apache-2.0 | false | 2023-05-10T07:59:48 | 2020-05-02T15:07:31 | 2023-05-07T05:18:50 | 2023-05-10T07:59:47 | 33,432 | 1,884 | 380 | 0 | Java | false | false | package app.coronawarn.server.services.distribution.config;
import app.coronawarn.server.common.protocols.external.exposurenotification.SignatureInfo;
import app.coronawarn.server.common.shared.util.SerializationUtils;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.File;
import java.util.List;
import java.util.stream.Collectors;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.PositiveOrZero;
import javax.validation.constraints.Size;
import org.bouncycastle.util.encoders.Hex;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;
@ConfigurationProperties(prefix = "services.distribution")
@Validated
public class DistributionServiceConfig {
public static class AllowList {
@JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public static class CertificateAllowList {
private String serviceProvider;
private String hostname;
private String fingerprint256;
@JsonProperty("serviceProviderAllowlistEndpoint")
private String serviceProviderAllowlistEndpoint;
public String getFingerprint256() {
return fingerprint256;
}
public String getHostname() {
return hostname;
}
public String getServiceProvider() {
return serviceProvider;
}
public String getServiceProviderAllowlistEndpoint() {
return serviceProviderAllowlistEndpoint;
}
@JsonProperty("fingerprint256")
public void setFingerprint256(final String fingerprint256) {
this.fingerprint256 = fingerprint256;
}
@JsonProperty("hostname")
public void setHostname(final String hostname) {
this.hostname = hostname;
}
@JsonProperty("serviceProvider")
public void setServiceProvider(final String serviceProvider) {
this.serviceProvider = serviceProvider;
}
public void setServiceProviderAllowlistEndpoint(final String serviceProviderAllowlistEndpoint) {
this.serviceProviderAllowlistEndpoint = serviceProviderAllowlistEndpoint;
}
}
@JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public static class ServiceProvider {
@JsonProperty("serviceProviderAllowlistEndpoint")
private String serviceProviderAllowlistEndpoint;
@JsonProperty("fingerprint256")
private String fingerprint256;
public String getFingerprint256() {
return fingerprint256;
}
public String getServiceProviderAllowlistEndpoint() {
return serviceProviderAllowlistEndpoint;
}
public void setFingerprint256(final String fingerprint256) {
this.fingerprint256 = fingerprint256;
}
public void setServiceProviderAllowlistEndpoint(final String serviceProviderAllowlistEndpoint) {
this.serviceProviderAllowlistEndpoint = serviceProviderAllowlistEndpoint;
}
}
private List<CertificateAllowList> certificates;
private List<ServiceProvider> serviceProviders;
public List<CertificateAllowList> getCertificates() {
return certificates;
}
public List<ServiceProvider> getServiceProviders() {
return serviceProviders;
}
@JsonProperty("certificates")
public void setCertificates(final List<CertificateAllowList> certificates) {
this.certificates = certificates;
}
@JsonProperty("serviceProviders")
public void setServiceProviders(final List<ServiceProvider> serviceProviders) {
this.serviceProviders = serviceProviders;
}
}
public static class Api {
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String versionPath;
@Pattern(regexp = VERSION_REGEX)
private String versionV1;
@Pattern(regexp = VERSION_REGEX)
private String versionV2;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String countryPath;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String originCountry;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String datePath;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String hourPath;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String diagnosisKeysPath;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String parametersPath;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String appConfigFileName;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String appConfigV2IosFileName;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String appConfigV2AndroidFileName;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String statisticsFileName;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String localStatisticsFileName;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String traceWarningsPath;
public String getAppConfigFileName() {
return appConfigFileName;
}
public String getAppConfigV2AndroidFileName() {
return appConfigV2AndroidFileName;
}
public String getAppConfigV2IosFileName() {
return appConfigV2IosFileName;
}
public String getCountryPath() {
return countryPath;
}
public String getDatePath() {
return datePath;
}
public String getDiagnosisKeysPath() {
return diagnosisKeysPath;
}
public String getHourPath() {
return hourPath;
}
public String getLocalStatisticsFileName() {
return localStatisticsFileName;
}
public String getOriginCountry() {
return originCountry;
}
public String getParametersPath() {
return parametersPath;
}
public String getStatisticsFileName() {
return statisticsFileName;
}
public String getTraceWarningsPath() {
return traceWarningsPath;
}
public String getVersionPath() {
return versionPath;
}
public String getVersionV1() {
return versionV1;
}
public String getVersionV2() {
return versionV2;
}
public void setAppConfigFileName(final String appConfigFileName) {
this.appConfigFileName = appConfigFileName;
}
public void setAppConfigV2AndroidFileName(final String appConfigV2AndroidFileName) {
this.appConfigV2AndroidFileName = appConfigV2AndroidFileName;
}
public void setAppConfigV2IosFileName(final String appConfigV2IosFileName) {
this.appConfigV2IosFileName = appConfigV2IosFileName;
}
public void setCountryPath(final String countryPath) {
this.countryPath = countryPath;
}
public void setDatePath(final String datePath) {
this.datePath = datePath;
}
public void setDiagnosisKeysPath(final String diagnosisKeysPath) {
this.diagnosisKeysPath = diagnosisKeysPath;
}
public void setHourPath(final String hourPath) {
this.hourPath = hourPath;
}
public void setLocalStatisticsFileName(final String localStatisticsFileName) {
this.localStatisticsFileName = localStatisticsFileName;
}
public void setOriginCountry(final String originCountry) {
this.originCountry = originCountry;
}
public void setParametersPath(final String parametersPath) {
this.parametersPath = parametersPath;
}
public void setStatisticsFileName(final String statisticsFileName) {
this.statisticsFileName = statisticsFileName;
}
public void setTraceWarningsPath(final String traceWarningsPath) {
this.traceWarningsPath = traceWarningsPath;
}
public void setVersionPath(final String versionPath) {
this.versionPath = versionPath;
}
public void setVersionV1(final String versionV1) {
this.versionV1 = versionV1;
}
public void setVersionV2(final String versionV2) {
this.versionV2 = versionV2;
}
}
public static class AppConfigParameters {
public static class AndroidEventDrivenUserSurveyParameters extends CommonEdusParameters {
@NotNull
private Boolean requireBasicIntegrity;
@NotNull
private Boolean requireCtsProfileMatch;
@NotNull
private Boolean requireEvaluationTypeBasic;
@NotNull
private Boolean requireEvaluationTypeHardwareBacked;
public Boolean getRequireBasicIntegrity() {
return requireBasicIntegrity;
}
public Boolean getRequireCtsProfileMatch() {
return requireCtsProfileMatch;
}
public Boolean getRequireEvaluationTypeBasic() {
return requireEvaluationTypeBasic;
}
public Boolean getRequireEvaluationTypeHardwareBacked() {
return requireEvaluationTypeHardwareBacked;
}
public void setRequireBasicIntegrity(final Boolean requireBasicIntegrity) {
this.requireBasicIntegrity = requireBasicIntegrity;
}
public void setRequireCtsProfileMatch(final Boolean requireCtsProfileMatch) {
this.requireCtsProfileMatch = requireCtsProfileMatch;
}
public void setRequireEvaluationTypeBasic(final Boolean requireEvaluationTypeBasic) {
this.requireEvaluationTypeBasic = requireEvaluationTypeBasic;
}
public void setRequireEvaluationTypeHardwareBacked(final Boolean requireEvaluationTypeHardwareBacked) {
this.requireEvaluationTypeHardwareBacked = requireEvaluationTypeHardwareBacked;
}
}
public static class AndroidExposureDetectionParameters {
private static final int LOWER_BOUNDARY_OVERALL_TIMEOUT = 0;
public static final String MIN_VALUE_ERROR_MESSAGE_OVERALL_TIMEOUT =
"Android Exposure Detection: overall timeout in seconds must be greater than or equal to "
+ LOWER_BOUNDARY_OVERALL_TIMEOUT;
private static final int UPPER_BOUNDARY_OVERALL_TIMEOUT = 3600;
public static final String MAX_VALUE_ERROR_MESSAGE_OVERALL_TIMEOUT =
"Android Exposure Detection: overall timeout in seconds must be lower than or equal to "
+ UPPER_BOUNDARY_OVERALL_TIMEOUT;
private static final int LOWER_BOUNDARY_MAX_EXPOSURE_DETECTIONS = 0;
public static final String MIN_VALUE_ERROR_MESSAGE_MAX_EXPOSURE_DETECTIONS =
"Android Exposure Detection: max exposure detections per interval must be greater than or equal to "
+ LOWER_BOUNDARY_MAX_EXPOSURE_DETECTIONS;
private static final int UPPER_BOUNDARY_MAX_EXPOSURE_DETECTIONS = 6;
public static final String MAX_VALUE_ERROR_MESSAGE_MAX_EXPOSURE_DETECTIONS =
"Android Exposure Detection: max exposure detections per interval must be lower than or equal to "
+ UPPER_BOUNDARY_MAX_EXPOSURE_DETECTIONS;
@Min(value = LOWER_BOUNDARY_MAX_EXPOSURE_DETECTIONS, message = MIN_VALUE_ERROR_MESSAGE_MAX_EXPOSURE_DETECTIONS)
@Max(value = UPPER_BOUNDARY_MAX_EXPOSURE_DETECTIONS, message = MAX_VALUE_ERROR_MESSAGE_MAX_EXPOSURE_DETECTIONS)
private Integer maxExposureDetectionsPerInterval;
@Min(value = LOWER_BOUNDARY_OVERALL_TIMEOUT, message = MIN_VALUE_ERROR_MESSAGE_OVERALL_TIMEOUT)
@Max(value = UPPER_BOUNDARY_OVERALL_TIMEOUT, message = MAX_VALUE_ERROR_MESSAGE_OVERALL_TIMEOUT)
private Integer overallTimeoutInSeconds;
public Integer getMaxExposureDetectionsPerInterval() {
return maxExposureDetectionsPerInterval;
}
public Integer getOverallTimeoutInSeconds() {
return overallTimeoutInSeconds;
}
public void setMaxExposureDetectionsPerInterval(final Integer maxExposureDetectionsPerInterval) {
this.maxExposureDetectionsPerInterval = maxExposureDetectionsPerInterval;
}
public void setOverallTimeoutInSeconds(final Integer overallTimeoutInSeconds) {
this.overallTimeoutInSeconds = overallTimeoutInSeconds;
}
}
public static class AndroidKeyDownloadParameters extends CommonKeyDownloadParameters {
private static final int LOWER_BOUNDARY_DOWNLOAD_TIMEOUT = 0;
public static final String MIN_VALUE_ERROR_MESSAGE_DOWNLOAD_TIMEOUT =
"Download timeout in seconds must be greater than or equal to " + LOWER_BOUNDARY_DOWNLOAD_TIMEOUT;
private static final int UPPER_BOUNDARY_DOWNLOAD_TIMEOUT = 1800;
public static final String MAX_VALUE_ERROR_MESSAGE_DOWNLOAD_TIMEOUT =
"Download timeout in seconds must be lower than or equal to " + UPPER_BOUNDARY_DOWNLOAD_TIMEOUT;
private static final int LOWER_BOUNDARY_OVERALL_TIMEOUT = 0;
public static final String MIN_VALUE_ERROR_MESSAGE_OVERALL_TIMEOUT =
"Android Key Download: overall timeout in seconds must be greater than or equal to "
+ LOWER_BOUNDARY_OVERALL_TIMEOUT;
private static final int UPPER_BOUNDARY_OVERALL_TIMEOUT = 1800;
public static final String MAX_VALUE_ERROR_MESSAGE_OVERALL_TIMEOUT =
"Android Key Download: overall timeout in seconds must be lower than or equal to "
+ UPPER_BOUNDARY_OVERALL_TIMEOUT;
@Min(value = LOWER_BOUNDARY_DOWNLOAD_TIMEOUT, message = MIN_VALUE_ERROR_MESSAGE_DOWNLOAD_TIMEOUT)
@Max(value = UPPER_BOUNDARY_DOWNLOAD_TIMEOUT, message = MAX_VALUE_ERROR_MESSAGE_DOWNLOAD_TIMEOUT)
private Integer downloadTimeoutInSeconds;
@Min(value = LOWER_BOUNDARY_OVERALL_TIMEOUT, message = MIN_VALUE_ERROR_MESSAGE_OVERALL_TIMEOUT)
@Max(value = UPPER_BOUNDARY_OVERALL_TIMEOUT, message = MAX_VALUE_ERROR_MESSAGE_OVERALL_TIMEOUT)
private Integer overallTimeoutInSeconds;
public Integer getDownloadTimeoutInSeconds() {
return downloadTimeoutInSeconds;
}
public Integer getOverallTimeoutInSeconds() {
return overallTimeoutInSeconds;
}
public void setDownloadTimeoutInSeconds(final Integer downloadTimeoutInSeconds) {
this.downloadTimeoutInSeconds = downloadTimeoutInSeconds;
}
public void setOverallTimeoutInSeconds(final Integer overallTimeoutInSeconds) {
this.overallTimeoutInSeconds = overallTimeoutInSeconds;
}
}
public static class AndroidPrivacyPreservingAnalyticsParameters extends CommonPpaParameters {
@NotNull
private Boolean requireBasicIntegrity;
@NotNull
private Boolean requireCtsProfileMatch;
@NotNull
private Boolean requireEvaluationTypeBasic;
@NotNull
private Boolean requireEvaluationTypeHardwareBacked;
public Boolean getRequireBasicIntegrity() {
return requireBasicIntegrity;
}
public Boolean getRequireCtsProfileMatch() {
return requireCtsProfileMatch;
}
public Boolean getRequireEvaluationTypeBasic() {
return requireEvaluationTypeBasic;
}
public Boolean getRequireEvaluationTypeHardwareBacked() {
return requireEvaluationTypeHardwareBacked;
}
public void setRequireBasicIntegrity(final Boolean requireBasicIntegrity) {
this.requireBasicIntegrity = requireBasicIntegrity;
}
public void setRequireCtsProfileMatch(final Boolean requireCtsProfileMatch) {
this.requireCtsProfileMatch = requireCtsProfileMatch;
}
public void setRequireEvaluationTypeBasic(final Boolean requireEvaluationTypeBasic) {
this.requireEvaluationTypeBasic = requireEvaluationTypeBasic;
}
public void setRequireEvaluationTypeHardwareBacked(final Boolean requireEvaluationTypeHardwareBacked) {
this.requireEvaluationTypeHardwareBacked = requireEvaluationTypeHardwareBacked;
}
}
public static class AndroidSrsPpacParameters extends AndroidPrivacyPreservingAnalyticsParameters {
}
private static class CommonEdusParameters {
@Size(min = 1, max = 30)
private String otpQueryParameterName;
@NotNull
private Boolean surveyOnHighRiskEnabled;
@Pattern(regexp = URL_REGEX)
private String surveyOnHighRiskUrl;
public String getOtpQueryParameterName() {
return otpQueryParameterName;
}
public Boolean getSurveyOnHighRiskEnabled() {
return surveyOnHighRiskEnabled;
}
public String getSurveyOnHighRiskUrl() {
return surveyOnHighRiskUrl;
}
public void setOtpQueryParameterName(final String otpQueryParameterName) {
this.otpQueryParameterName = otpQueryParameterName;
}
public void setSurveyOnHighRiskEnabled(final Boolean surveyOnHighRiskEnabled) {
this.surveyOnHighRiskEnabled = surveyOnHighRiskEnabled;
}
public void setSurveyOnHighRiskUrl(final String surveyOnHighRiskUrl) {
this.surveyOnHighRiskUrl = surveyOnHighRiskUrl;
}
}
private abstract static class CommonKeyDownloadParameters {
private String revokedDayPackages;
private String revokedHourPackages;
public List<DeserializedDayPackageMetadata> getRevokedDayPackages() {
return SerializationUtils.deserializeJson(revokedDayPackages,
typeFactory -> typeFactory.constructCollectionType(List.class, DeserializedDayPackageMetadata.class));
}
public List<DeserializedHourPackageMetadata> getRevokedHourPackages() {
return SerializationUtils.deserializeJson(revokedHourPackages,
typeFactory -> typeFactory
.constructCollectionType(List.class, DeserializedHourPackageMetadata.class));
}
public void setRevokedDayPackages(final String revokedDayPackages) {
this.revokedDayPackages = revokedDayPackages;
}
public void setRevokedHourPackages(final String revokedHourPackages) {
this.revokedHourPackages = revokedHourPackages;
}
}
private static class CommonPpaParameters {
private Double probabilityToSubmit;
private Double probabilityToSubmitExposureWindows;
@PositiveOrZero
private Integer hoursSinceTestRegistrationToSubmitTestResultMetadata;
@PositiveOrZero
private Integer hoursSinceTestToSubmitKeySubmissionMetadata;
public Integer getHoursSinceTestRegistrationToSubmitTestResultMetadata() {
return hoursSinceTestRegistrationToSubmitTestResultMetadata;
}
public Integer getHoursSinceTestToSubmitKeySubmissionMetadata() {
return hoursSinceTestToSubmitKeySubmissionMetadata;
}
public Double getProbabilityToSubmit() {
return probabilityToSubmit;
}
public Double getProbabilityToSubmitExposureWindows() {
return probabilityToSubmitExposureWindows;
}
public void setHoursSinceTestRegistrationToSubmitTestResultMetadata(final Integer integer) {
this.hoursSinceTestRegistrationToSubmitTestResultMetadata = integer;
}
public void setHoursSinceTestToSubmitKeySubmissionMetadata(
final Integer hoursSinceTestToSubmitKeySubmissionMetadata) {
this.hoursSinceTestToSubmitKeySubmissionMetadata = hoursSinceTestToSubmitKeySubmissionMetadata;
}
public void setProbabilityToSubmit(final Double probabilityToSubmit) {
this.probabilityToSubmit = probabilityToSubmit;
}
public void setProbabilityToSubmitExposureWindows(final Double probabilityToSubmitExposureWindows) {
this.probabilityToSubmitExposureWindows = probabilityToSubmitExposureWindows;
}
}
public static class DeserializedDayPackageMetadata {
private String region;
private String date;
private String etag;
public String getDate() {
return date;
}
public String getEtag() {
return etag;
}
public String getRegion() {
return region;
}
}
public static class DeserializedHourPackageMetadata extends DeserializedDayPackageMetadata {
private Integer hour;
public Integer getHour() {
return hour;
}
}
public static class DgcParameters {
public static class DgcBlocklistParameters {
public static class DgcBlockedUvciChunk {
List<Integer> indices;
String hash;
Integer validFrom;
public byte[] getHash() {
return Hex.decode(hash);
}
public List<Integer> getIndices() {
return indices;
}
public Integer getValidFrom() {
return validFrom;
}
public void setHash(final String hash) {
this.hash = hash;
}
public void setIndices(final List<Integer> indices) {
this.indices = indices;
}
public void setValidFrom(final Integer validFrom) {
this.validFrom = validFrom;
}
}
private String blockedUvciChunks;
/**
* Parse String from application.yaml parameter.
*
* @return parsed string in a list of DgcBlockedUvciChunk.
*/
public List<DgcBlockedUvciChunk> getBlockedUvciChunks() {
return SerializationUtils.deserializeJson(blockedUvciChunks,
typeFactory -> typeFactory
.constructCollectionType(List.class, DgcBlockedUvciChunk.class));
}
public void setBlockedUvciChunks(final String blockedUvciChunks) {
this.blockedUvciChunks = blockedUvciChunks;
}
}
public static class DgcTestCertificateParameters {
@Min(0)
@Max(60)
private Integer waitAfterPublicKeyRegistrationInSeconds;
@Min(0)
@Max(60)
private Integer waitForRetryInSeconds;
public Integer getWaitAfterPublicKeyRegistrationInSeconds() {
return waitAfterPublicKeyRegistrationInSeconds;
}
public Integer getWaitForRetryInSeconds() {
return waitForRetryInSeconds;
}
public void setWaitAfterPublicKeyRegistrationInSeconds(final Integer waitAfterPublicKeyRegistrationInSeconds) {
this.waitAfterPublicKeyRegistrationInSeconds = waitAfterPublicKeyRegistrationInSeconds;
}
public void setWaitForRetryInSeconds(final Integer waitForRetryInSeconds) {
this.waitForRetryInSeconds = waitForRetryInSeconds;
}
}
private DgcTestCertificateParameters dgcTestCertificateParameters;
@Min(0)
@Max(100)
private Integer expirationThresholdInDays;
private DgcBlocklistParameters blockListParameters;
private String iosDgcReissueServicePublicKeyDigest;
private String androidDgcReissueServicePublicKeyDigest;
public byte[] getAndroidDgcReissueServicePublicKeyDigest() {
return Hex.decode(androidDgcReissueServicePublicKeyDigest);
}
public DgcBlocklistParameters getBlockListParameters() {
return blockListParameters;
}
public Integer getExpirationThresholdInDays() {
return expirationThresholdInDays;
}
public byte[] getIosDgcReissueServicePublicKeyDigest() {
return Hex.decode(iosDgcReissueServicePublicKeyDigest);
}
public DgcTestCertificateParameters getTestCertificateParameters() {
return dgcTestCertificateParameters;
}
public void setAndroidDgcReissueServicePublicKeyDigest(final String androidDgcReissueServicePublicKeyDigest) {
this.androidDgcReissueServicePublicKeyDigest = androidDgcReissueServicePublicKeyDigest;
}
public void setBlockListParameters(final DgcBlocklistParameters blockListParameters) {
this.blockListParameters = blockListParameters;
}
public void setExpirationThresholdInDays(final Integer expirationThresholdInDays) {
this.expirationThresholdInDays = expirationThresholdInDays;
}
public void setIosDgcReissueServicePublicKeyDigest(final String iosDgcReissueServicePublicKeyDigest) {
this.iosDgcReissueServicePublicKeyDigest = iosDgcReissueServicePublicKeyDigest;
}
public void setTestCertificateParameters(final DgcTestCertificateParameters dgcTestCertificateParameters) {
this.dgcTestCertificateParameters = dgcTestCertificateParameters;
}
}
public static class IosEventDrivenUserSurveyParameters extends CommonEdusParameters {
}
public static class IosExposureDetectionParameters {
private static final int MIN_VALUE_MAX_EXPOSURE_DETECTIONS = 0;
public static final String MIN_VALUE_ERROR_MESSAGE_MAX_EXPOSURE_DETECTIONS =
"IOS Exposure Detection: max exposure detections per interval must be greater than or equal to "
+ MIN_VALUE_MAX_EXPOSURE_DETECTIONS;
private static final int MAX_VALUE_MAX_EXPOSURE_DETECTIONS = 6;
public static final String MAX_VALUE_ERROR_MESSAGE_MAX_EXPOSURE_DETECTIONS =
"IOS Exposure Detection: max exposure detections per interval must be lower than or equal to "
+ MAX_VALUE_MAX_EXPOSURE_DETECTIONS;
@Min(value = MIN_VALUE_MAX_EXPOSURE_DETECTIONS, message = MIN_VALUE_ERROR_MESSAGE_MAX_EXPOSURE_DETECTIONS)
@Max(value = MAX_VALUE_MAX_EXPOSURE_DETECTIONS, message = MAX_VALUE_ERROR_MESSAGE_MAX_EXPOSURE_DETECTIONS)
private Integer maxExposureDetectionsPerInterval;
public Integer getMaxExposureDetectionsPerInterval() {
return maxExposureDetectionsPerInterval;
}
public void setMaxExposureDetectionsPerInterval(final Integer maxExposureDetectionsPerInterval) {
this.maxExposureDetectionsPerInterval = maxExposureDetectionsPerInterval;
}
}
public static class IosKeyDownloadParameters extends CommonKeyDownloadParameters {
}
public static class IosPrivacyPreservingAnalyticsParameters extends CommonPpaParameters {
}
private IosKeyDownloadParameters iosKeyDownloadParameters;
private AndroidKeyDownloadParameters androidKeyDownloadParameters;
private IosExposureDetectionParameters iosExposureDetectionParameters;
private AndroidExposureDetectionParameters androidExposureDetectionParameters;
private IosEventDrivenUserSurveyParameters iosEventDrivenUserSurveyParameters;
private AndroidEventDrivenUserSurveyParameters androidEventDrivenUserSurveyParameters;
private IosPrivacyPreservingAnalyticsParameters iosPrivacyPreservingAnalyticsParameters;
private AndroidPrivacyPreservingAnalyticsParameters androidPrivacyPreservingAnalyticsParameters;
private AndroidSrsPpacParameters androidSrsPpacParameters;
private DgcParameters dgcParameters;
@Min(1)
@Max(1000)
private int srsTimeSinceOnboardingInHours;
@Min(1)
@Max(1000)
private int srsTimeBetweenSubmissionsInDays;
public AndroidEventDrivenUserSurveyParameters getAndroidEventDrivenUserSurveyParameters() {
return androidEventDrivenUserSurveyParameters;
}
public AndroidExposureDetectionParameters getAndroidExposureDetectionParameters() {
return androidExposureDetectionParameters;
}
public AndroidKeyDownloadParameters getAndroidKeyDownloadParameters() {
return androidKeyDownloadParameters;
}
public AndroidPrivacyPreservingAnalyticsParameters getAndroidPrivacyPreservingAnalyticsParameters() {
return androidPrivacyPreservingAnalyticsParameters;
}
public AndroidSrsPpacParameters getAndroidSrsPpacParameters() {
return androidSrsPpacParameters;
}
public DgcParameters getDgcParameters() {
return dgcParameters;
}
public IosEventDrivenUserSurveyParameters getIosEventDrivenUserSurveyParameters() {
return iosEventDrivenUserSurveyParameters;
}
public IosExposureDetectionParameters getIosExposureDetectionParameters() {
return iosExposureDetectionParameters;
}
public IosKeyDownloadParameters getIosKeyDownloadParameters() {
return iosKeyDownloadParameters;
}
public IosPrivacyPreservingAnalyticsParameters getIosPrivacyPreservingAnalyticsParameters() {
return iosPrivacyPreservingAnalyticsParameters;
}
public int getSrsTimeBetweenSubmissionsInDays() {
return srsTimeBetweenSubmissionsInDays;
}
public int getSrsTimeSinceOnboardingInHours() {
return srsTimeSinceOnboardingInHours;
}
public void setAndroidEventDrivenUserSurveyParameters(
final AndroidEventDrivenUserSurveyParameters androidEventDrivenUserSurveyParameters) {
this.androidEventDrivenUserSurveyParameters = androidEventDrivenUserSurveyParameters;
}
public void setAndroidExposureDetectionParameters(
final AndroidExposureDetectionParameters androidExposureDetectionParameters) {
this.androidExposureDetectionParameters = androidExposureDetectionParameters;
}
public void setAndroidKeyDownloadParameters(final AndroidKeyDownloadParameters androidKeyDownloadParameters) {
this.androidKeyDownloadParameters = androidKeyDownloadParameters;
}
public void setAndroidPrivacyPreservingAnalyticsParameters(
final AndroidPrivacyPreservingAnalyticsParameters androidPrivacyPreservingAnalyticsParameters) {
this.androidPrivacyPreservingAnalyticsParameters = androidPrivacyPreservingAnalyticsParameters;
}
public void setAndroidSrsPpacParameters(final AndroidSrsPpacParameters androidSrsPpacParameters) {
this.androidSrsPpacParameters = androidSrsPpacParameters;
}
public void setDgcParameters(final DgcParameters dgcParameters) {
this.dgcParameters = dgcParameters;
}
public void setIosEventDrivenUserSurveyParameters(
final IosEventDrivenUserSurveyParameters iosEventDrivenUserSurveyParameters) {
this.iosEventDrivenUserSurveyParameters = iosEventDrivenUserSurveyParameters;
}
public void setIosExposureDetectionParameters(final IosExposureDetectionParameters iosExposureDetectionParameters) {
this.iosExposureDetectionParameters = iosExposureDetectionParameters;
}
public void setIosKeyDownloadParameters(final IosKeyDownloadParameters iosKeyDownloadParameters) {
this.iosKeyDownloadParameters = iosKeyDownloadParameters;
}
public void setIosPrivacyPreservingAnalyticsParameters(
final IosPrivacyPreservingAnalyticsParameters iosPrivacyPreservingAnalyticsParameters) {
this.iosPrivacyPreservingAnalyticsParameters = iosPrivacyPreservingAnalyticsParameters;
}
public void setSrsTimeBetweenSubmissionsInDays(final int srsTimeBetweenSubmissionsInDays) {
this.srsTimeBetweenSubmissionsInDays = srsTimeBetweenSubmissionsInDays;
}
public void setSrsTimeSinceOnboardingInHours(final int srsTimeSinceOnboardingInHours) {
this.srsTimeSinceOnboardingInHours = srsTimeSinceOnboardingInHours;
}
}
public static class AppFeature {
private String label;
private Integer value;
public String getLabel() {
return label;
}
public Integer getValue() {
return value;
}
public void setLabel(final String label) {
this.label = label;
}
public void setValue(final Integer value) {
this.value = value;
}
}
public static class AppVersions {
private String latestIos;
private String minIos;
private String latestAndroid;
private String minAndroid;
@PositiveOrZero
private Integer latestAndroidVersionCode;
@PositiveOrZero
private Integer minAndroidVersionCode;
public String getLatestAndroid() {
return latestAndroid;
}
public Integer getLatestAndroidVersionCode() {
return latestAndroidVersionCode;
}
public String getLatestIos() {
return latestIos;
}
public String getMinAndroid() {
return minAndroid;
}
public Integer getMinAndroidVersionCode() {
return minAndroidVersionCode;
}
public String getMinIos() {
return minIos;
}
public void setLatestAndroid(final String latestAndroid) {
this.latestAndroid = latestAndroid;
}
public void setLatestAndroidVersionCode(final Integer latestAndroidVersionCode) {
this.latestAndroidVersionCode = latestAndroidVersionCode;
}
public void setLatestIos(final String latestIos) {
this.latestIos = latestIos;
}
public void setMinAndroid(final String minAndroid) {
this.minAndroid = minAndroid;
}
public void setMinAndroidVersionCode(final Integer minAndroidVersionCode) {
this.minAndroidVersionCode = minAndroidVersionCode;
}
public void setMinIos(final String minIos) {
this.minIos = minIos;
}
}
public static class Client {
public static class Ssl {
private File trustStore;
private String trustStorePassword;
public File getTrustStore() {
return trustStore;
}
public String getTrustStorePassword() {
return trustStorePassword;
}
public void setTrustStore(final File trustStore) {
this.trustStore = trustStore;
}
public void setTrustStorePassword(final String trustStorePassword) {
this.trustStorePassword = trustStorePassword;
}
}
private String publicKey;
private String baseUrl;
private Ssl ssl;
private int retryPeriod;
private int maxRetryPeriod;
private int maxRetryAttempts;
public String getBaseUrl() {
return baseUrl;
}
public int getMaxRetryAttempts() {
return maxRetryAttempts;
}
public int getMaxRetryPeriod() {
return maxRetryPeriod;
}
public String getPublicKey() {
return publicKey;
}
public int getRetryPeriod() {
return retryPeriod;
}
public Ssl getSsl() {
return ssl;
}
public void setBaseUrl(final String baseUrl) {
this.baseUrl = baseUrl;
}
public void setMaxRetryAttempts(final int maxRetryAttempts) {
this.maxRetryAttempts = maxRetryAttempts;
}
public void setMaxRetryPeriod(final int maxRetryPeriod) {
this.maxRetryPeriod = maxRetryPeriod;
}
public void setPublicKey(final String publicKey) {
this.publicKey = publicKey;
}
public void setRetryPeriod(final int retryPeriod) {
this.retryPeriod = retryPeriod;
}
public void setSsl(final Ssl ssl) {
this.ssl = ssl;
}
}
public static class DccRevocation {
private Client client;
private String certificate;
private String dccListPath;
private String dccRevocationDirectory;
public String getCertificate() {
return certificate;
}
public Client getClient() {
return client;
}
public String getDccListPath() {
return dccListPath;
}
public String getDccRevocationDirectory() {
return dccRevocationDirectory;
}
public void setCertificate(final String certificate) {
this.certificate = certificate;
}
public void setClient(final Client client) {
this.client = client;
}
public void setDccListPath(final String dccListPath) {
this.dccListPath = dccListPath;
}
public void setDccRevocationDirectory(final String dccRevocationDirectory) {
this.dccRevocationDirectory = dccRevocationDirectory;
}
}
public static class DigitalGreenCertificate {
@Pattern(regexp = RESOURCE_OR_EMPTY_REGEX)
private String mahJsonPath;
@Pattern(regexp = RESOURCE_OR_EMPTY_REGEX)
private String prophylaxisJsonPath;
@Pattern(regexp = RESOURCE_OR_EMPTY_REGEX)
private String medicinalProductsJsonPath;
@Pattern(regexp = RESOURCE_OR_EMPTY_REGEX)
private String diseaseAgentTargetedJsonPath;
@Pattern(regexp = RESOURCE_OR_EMPTY_REGEX)
private String testManfJsonPath;
@Pattern(regexp = RESOURCE_OR_EMPTY_REGEX)
private String testResultJsonPath;
@Pattern(regexp = RESOURCE_OR_EMPTY_REGEX)
private String testTypeJsonPath;
@NotNull
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String dgcDirectory;
@NotNull
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String boosterNotification;
@NotNull
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String valuesetsFileName;
private String cclDirectory;
private String[] cclAllowList;
private String allowList;
private String allowListSignature;
private String allowListCertificate;
private String[] supportedLanguages;
private String exportArchiveName;
private Client client;
private Client dscClient;
/**
* getAllowList.
*
* @return AllowList
*/
public AllowList getAllowList() {
return SerializationUtils.deserializeJson(allowList,
typeFactory -> typeFactory
.constructType(AllowList.class));
}
public String getAllowListAsString() {
return allowList;
}
public String getAllowListCertificate() {
return allowListCertificate;
}
public byte[] getAllowListSignature() {
return Hex.decode(allowListSignature);
}
public String getBoosterNotification() {
return boosterNotification;
}
public String[] getCclAllowList() {
return cclAllowList;
}
public String getCclDirectory() {
return cclDirectory;
}
public Client getClient() {
return client;
}
public String getDgcDirectory() {
return dgcDirectory;
}
public String getDiseaseAgentTargetedJsonPath() {
return diseaseAgentTargetedJsonPath;
}
public Client getDscClient() {
return dscClient;
}
public String getExportArchiveName() {
return exportArchiveName;
}
public String getMahJsonPath() {
return mahJsonPath;
}
public String getMedicinalProductsJsonPath() {
return medicinalProductsJsonPath;
}
public String getProphylaxisJsonPath() {
return prophylaxisJsonPath;
}
public String[] getSupportedLanguages() {
return supportedLanguages;
}
public String getTestManfJsonPath() {
return testManfJsonPath;
}
public String getTestResultJsonPath() {
return testResultJsonPath;
}
public String getTestTypeJsonPath() {
return testTypeJsonPath;
}
public String getValuesetsFileName() {
return valuesetsFileName;
}
public void setAllowList(final String allowList) {
this.allowList = allowList;
}
public void setAllowListCertificate(final String allowListCertificate) {
this.allowListCertificate = allowListCertificate;
}
public void setAllowListSignature(final String allowListSignature) {
this.allowListSignature = allowListSignature;
}
public void setBoosterNotification(final String boosterNotification) {
this.boosterNotification = boosterNotification;
}
public void setCclAllowList(final String[] cclAllowList) {
this.cclAllowList = cclAllowList;
}
public void setCclDirectory(final String cclDirectory) {
this.cclDirectory = cclDirectory;
}
public void setClient(final Client client) {
this.client = client;
}
public void setDgcDirectory(final String dgcDirectory) {
this.dgcDirectory = dgcDirectory;
}
public void setDiseaseAgentTargetedJsonPath(final String diseaseAgentTargetedJsonPath) {
this.diseaseAgentTargetedJsonPath = diseaseAgentTargetedJsonPath;
}
public void setDscClient(final Client dscClient) {
this.dscClient = dscClient;
}
public void setExportArchiveName(final String exportArchiveName) {
this.exportArchiveName = exportArchiveName;
}
public void setMahJsonPath(final String mahJsonPath) {
this.mahJsonPath = mahJsonPath;
}
public void setMedicinalProductsJsonPath(final String medicinalProductsJsonPath) {
this.medicinalProductsJsonPath = medicinalProductsJsonPath;
}
public void setProphylaxisJsonPath(final String prophylaxisJsonPath) {
this.prophylaxisJsonPath = prophylaxisJsonPath;
}
public void setSupportedLanguages(final String[] supportedLanguages) {
this.supportedLanguages = supportedLanguages;
}
public void setTestManfJsonPath(final String testManfJsonPath) {
this.testManfJsonPath = testManfJsonPath;
}
public void setTestResultJsonPath(final String testResultJsonPath) {
this.testResultJsonPath = testResultJsonPath;
}
public void setTestTypeJsonPath(final String testTypeJsonPath) {
this.testTypeJsonPath = testTypeJsonPath;
}
public void setValuesetsFileName(final String valuesetsFileName) {
this.valuesetsFileName = valuesetsFileName;
}
}
public static class ObjectStore {
@Pattern(regexp = NO_WHITESPACE_REGEX)
private String accessKey;
@Pattern(regexp = NO_WHITESPACE_REGEX)
private String secretKey;
@Pattern(regexp = URL_REGEX)
private String endpoint;
@Min(1)
@Max(65535)
private Integer port;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String bucket;
private Boolean setPublicReadAclOnPutObject;
@Min(1)
@Max(64)
private Integer maxNumberOfFailedOperations;
@Min(1)
@Max(64)
private Integer maxNumberOfS3Threads;
private Boolean forceUpdateKeyfiles;
@Max(Integer.MAX_VALUE)
private Integer hourFileRetentionDays;
public String getAccessKey() {
return accessKey;
}
public String getBucket() {
return bucket;
}
public String getEndpoint() {
return endpoint;
}
public Boolean getForceUpdateKeyfiles() {
return forceUpdateKeyfiles;
}
public Integer getHourFileRetentionDays() {
return hourFileRetentionDays;
}
public Integer getMaxNumberOfFailedOperations() {
return maxNumberOfFailedOperations;
}
public Integer getMaxNumberOfS3Threads() {
return maxNumberOfS3Threads;
}
public Integer getPort() {
return port;
}
public String getSecretKey() {
return secretKey;
}
public Boolean isSetPublicReadAclOnPutObject() {
return setPublicReadAclOnPutObject;
}
public void setAccessKey(final String accessKey) {
this.accessKey = accessKey;
}
public void setBucket(final String bucket) {
this.bucket = bucket;
}
public void setEndpoint(final String endpoint) {
this.endpoint = endpoint;
}
public void setForceUpdateKeyfiles(final Boolean forceUpdateKeyfiles) {
this.forceUpdateKeyfiles = forceUpdateKeyfiles;
}
public void setHourFileRetentionDays(final Integer hourFileRetentionDays) {
this.hourFileRetentionDays = hourFileRetentionDays;
}
public void setMaxNumberOfFailedOperations(final Integer maxNumberOfFailedOperations) {
this.maxNumberOfFailedOperations = maxNumberOfFailedOperations;
}
public void setMaxNumberOfS3Threads(final Integer maxNumberOfS3Threads) {
this.maxNumberOfS3Threads = maxNumberOfS3Threads;
}
public void setPort(final Integer port) {
this.port = port;
}
public void setSecretKey(final String secretKey) {
this.secretKey = secretKey;
}
public void setSetPublicReadAclOnPutObject(final Boolean setPublicReadAclOnPutObject) {
this.setPublicReadAclOnPutObject = setPublicReadAclOnPutObject;
}
}
public static class Paths {
@Pattern(regexp = PRIVATE_KEY_REGEX)
private String privateKey;
@Pattern(regexp = PATH_REGEX)
private String output;
public String getOutput() {
return output;
}
public String getPrivateKey() {
return privateKey;
}
public void setOutput(final String output) {
this.output = output;
}
public void setPrivateKey(final String privateKey) {
this.privateKey = privateKey;
}
}
public static class PresenceTracingParameters {
public static class PlausibleDeniabilityParameters {
private double probabilityToFakeCheckInsIfNoCheckIns;
private double probabilityToFakeCheckInsIfSomeCheckIns;
public double getProbabilityToFakeCheckInsIfNoCheckIns() {
return probabilityToFakeCheckInsIfNoCheckIns;
}
public double getProbabilityToFakeCheckInsIfSomeCheckIns() {
return probabilityToFakeCheckInsIfSomeCheckIns;
}
public void setProbabilityToFakeCheckInsIfNoCheckIns(final double probabilityToFakeCheckInsIfNoCheckIns) {
this.probabilityToFakeCheckInsIfNoCheckIns = probabilityToFakeCheckInsIfNoCheckIns;
}
public void setProbabilityToFakeCheckInsIfSomeCheckIns(final double probabilityToFakeCheckInsIfSomeCheckIns) {
this.probabilityToFakeCheckInsIfSomeCheckIns = probabilityToFakeCheckInsIfSomeCheckIns;
}
}
private int qrCodeErrorCorrectionLevel;
private PlausibleDeniabilityParameters plausibleDeniabilityParameters;
public PlausibleDeniabilityParameters getPlausibleDeniabilityParameters() {
return plausibleDeniabilityParameters;
}
public int getQrCodeErrorCorrectionLevel() {
return qrCodeErrorCorrectionLevel;
}
public void setPlausibleDeniabilityParameters(final PlausibleDeniabilityParameters plausibleDeniabilityParameters) {
this.plausibleDeniabilityParameters = plausibleDeniabilityParameters;
}
public void setQrCodeErrorCorrectionLevel(final int qrCodeErrorCorrectionLevel) {
this.qrCodeErrorCorrectionLevel = qrCodeErrorCorrectionLevel;
}
}
public static class QrCodePosterTemplate {
public static class DescriptionTextBox {
@NotNull
private Double offsetX;
@NotNull
private Double offsetY;
@NotNull
private Integer width;
@NotNull
private Integer height;
@NotNull
private Integer fontSize;
@NotNull
private String fontColor;
public String getFontColor() {
return fontColor;
}
public Integer getFontSize() {
return fontSize;
}
public Integer getHeight() {
return height;
}
public Double getOffsetX() {
return offsetX;
}
public Double getOffsetY() {
return offsetY;
}
public Integer getWidth() {
return width;
}
public void setFontColor(final String fontColor) {
this.fontColor = fontColor;
}
public void setFontSize(final Integer fontSize) {
this.fontSize = fontSize;
}
public void setHeight(final Integer height) {
this.height = height;
}
public void setOffsetX(final Double offsetX) {
this.offsetX = offsetX;
}
public void setOffsetY(final Double offsetY) {
this.offsetY = offsetY;
}
public void setWidth(final Integer width) {
this.width = width;
}
}
private String template;
@NotNull
private Double offsetX;
@NotNull
private Double offsetY;
@NotNull
private Integer qrCodeSideLength;
@NotEmpty
private String publishedArchiveName;
private DescriptionTextBox descriptionTextBox;
private DescriptionTextBox addressTextBox;
public DescriptionTextBox getAddressTextBox() {
return addressTextBox;
}
public DescriptionTextBox getDescriptionTextBox() {
return descriptionTextBox;
}
public Double getOffsetX() {
return offsetX;
}
public Double getOffsetY() {
return offsetY;
}
public String getPublishedArchiveName() {
return publishedArchiveName;
}
public Integer getQrCodeSideLength() {
return qrCodeSideLength;
}
public String getTemplate() {
return template;
}
public void setAddressTextBox(final DescriptionTextBox addressTextBox) {
this.addressTextBox = addressTextBox;
}
public void setDescriptionTextBox(final DescriptionTextBox descriptionTextBox) {
this.descriptionTextBox = descriptionTextBox;
}
public void setOffsetX(final Double offsetX) {
this.offsetX = offsetX;
}
public void setOffsetY(final Double offsetY) {
this.offsetY = offsetY;
}
public void setPublishedArchiveName(final String publishedArchiveName) {
this.publishedArchiveName = publishedArchiveName;
}
public void setQrCodeSideLength(final Integer qrCodeSideLength) {
this.qrCodeSideLength = qrCodeSideLength;
}
public void setTemplate(final String template) {
this.template = template;
}
}
public static class Signature {
@Pattern(regexp = BUNDLE_REGEX)
private String appBundleId;
private String androidPackage;
@Pattern(regexp = NUMBER_REGEX)
private String verificationKeyId;
@Pattern(regexp = VERSION_REGEX)
private String verificationKeyVersion;
@Pattern(regexp = ALGORITHM_OID_REGEX)
private String algorithmOid;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String algorithmName;
@Pattern(regexp = FILE_NAME_WITH_TYPE_REGEX)
private String fileName;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String securityProvider;
public String getAlgorithmName() {
return algorithmName;
}
public String getAlgorithmOid() {
return algorithmOid;
}
public String getAndroidPackage() {
return androidPackage;
}
public String getAppBundleId() {
return appBundleId;
}
public String getFileName() {
return fileName;
}
public String getSecurityProvider() {
return securityProvider;
}
/**
* Returns the static {@link SignatureInfo} configured in the application properties.
*
* @return SignatureInfo
*/
public SignatureInfo getSignatureInfo() {
return SignatureInfo.newBuilder()
.setAppBundleId(getAppBundleId())
.setVerificationKeyVersion(getVerificationKeyVersion())
.setVerificationKeyId(getVerificationKeyId())
.setSignatureAlgorithm(getAlgorithmOid())
.build();
}
public String getVerificationKeyId() {
return verificationKeyId;
}
public String getVerificationKeyVersion() {
return verificationKeyVersion;
}
public void setAlgorithmName(final String algorithmName) {
this.algorithmName = algorithmName;
}
public void setAlgorithmOid(final String algorithmOid) {
this.algorithmOid = algorithmOid;
}
public void setAndroidPackage(final String androidPackage) {
this.androidPackage = androidPackage;
}
public void setAppBundleId(final String appBundleId) {
this.appBundleId = appBundleId;
}
public void setFileName(final String fileName) {
this.fileName = fileName;
}
public void setSecurityProvider(final String securityProvider) {
this.securityProvider = securityProvider;
}
public void setVerificationKeyId(final String verificationKeyId) {
this.verificationKeyId = verificationKeyId;
}
public void setVerificationKeyVersion(final String verificationKeyVersion) {
this.verificationKeyVersion = verificationKeyVersion;
}
}
public static class StatisticsConfig {
private String statisticPath;
private String localStatisticPath;
private String accessKey;
private String secretKey;
private String endpoint;
private String bucket;
private String pandemicRadarUrl;
private String pandemicRadarBmgUrl;
public String getAccessKey() {
return accessKey;
}
public String getBucket() {
return bucket;
}
public String getEndpoint() {
return endpoint;
}
public String getLocalStatisticPath() {
return localStatisticPath;
}
public String getPandemicRadarBmgUrl() {
return pandemicRadarBmgUrl;
}
public String getPandemicRadarUrl() {
return pandemicRadarUrl;
}
public String getSecretKey() {
return secretKey;
}
public String getStatisticPath() {
return statisticPath;
}
public void setAccessKey(final String accessKey) {
this.accessKey = accessKey;
}
public void setBucket(final String bucket) {
this.bucket = bucket;
}
public void setEndpoint(final String endpoint) {
this.endpoint = endpoint;
}
public void setLocalStatisticPath(final String localStatisticPath) {
this.localStatisticPath = localStatisticPath;
}
public void setPandemicRadarBmgUrl(final String pandemicRadarBmgUrl) {
this.pandemicRadarBmgUrl = pandemicRadarBmgUrl;
}
public void setPandemicRadarUrl(final String pandemicRadarUrl) {
this.pandemicRadarUrl = pandemicRadarUrl;
}
public void setSecretKey(final String secretKey) {
this.secretKey = secretKey;
}
public void setStatisticPath(final String statisticPath) {
this.statisticPath = statisticPath;
}
}
public static class TekExport {
@Pattern(regexp = FILE_NAME_WITH_TYPE_REGEX)
private String fileName;
@Pattern(regexp = CHAR_NUMBER_AND_SPACE_REGEX)
private String fileHeader;
@Min(0)
@Max(32)
private Integer fileHeaderWidth;
public String getFileHeader() {
return fileHeader;
}
public Integer getFileHeaderWidth() {
return fileHeaderWidth;
}
public String getFileName() {
return fileName;
}
public void setFileHeader(final String fileHeader) {
this.fileHeader = fileHeader;
}
public void setFileHeaderWidth(final Integer fileHeaderWidth) {
this.fileHeaderWidth = fileHeaderWidth;
}
public void setFileName(final String fileName) {
this.fileName = fileName;
}
}
public static class TestData {
private Integer seed;
private Integer exposuresPerHour;
private boolean distributionTestdataConsentToFederation;
public boolean getDistributionTestdataConsentToFederation() {
return distributionTestdataConsentToFederation;
}
public Integer getExposuresPerHour() {
return exposuresPerHour;
}
public Integer getSeed() {
return seed;
}
public void setDistributionTestdataConsentToFederation(final boolean distributionTestdataConsentToFederation) {
this.distributionTestdataConsentToFederation = distributionTestdataConsentToFederation;
}
public void setExposuresPerHour(final Integer exposuresPerHour) {
this.exposuresPerHour = exposuresPerHour;
}
public void setSeed(final Integer seed) {
this.seed = seed;
}
}
private static final String PATH_REGEX = "^[/]?[a-zA-Z0-9_]{1,1024}(/[a-zA-Z0-9_]{1,1024}){0,256}[/]?$";
private static final String RESOURCE_REGEX = "^(classpath:|file:[/]{1,3})?([a-zA-Z0-9_/\\.]{1,1010})$";
private static final String RESOURCE_OR_EMPTY_REGEX = "(" + RESOURCE_REGEX + ")?";
private static final String FILE_NAME_REGEX = "^[a-zA-Z0-9_-]{1,1024}$";
private static final String FILE_NAME_WITH_TYPE_REGEX = "^[a-zA-Z0-9_-]{1,1024}\\.[a-z]{1,64}$";
private static final String CHAR_AND_NUMBER_REGEX = "^[a-zA-Z0-9_-]{1,1024}$";
private static final String CHAR_NUMBER_AND_SPACE_REGEX = "^[a-zA-Z0-9_\\s]{1,32}$";
private static final String NO_WHITESPACE_REGEX = "^[\\S]+$";
private static final String URL_REGEX = "^http[s]?://[a-zA-Z0-9-_]{1,1024}([\\./][a-zA-Z0-9-_]{1,1024}){0,256}[/]?$";
private static final String NUMBER_REGEX = "^[0-9]{1,256}$";
private static final String VERSION_REGEX = "^v[0-9]{1,256}$";
private static final String ALGORITHM_OID_REGEX = "^[0-9]{1,256}[\\.[0-9]{1,256}]{0,256}$";
private static final String BUNDLE_REGEX = "^[a-z-]{1,256}[\\.[a-z-]{1,256}]{0,256}$";
private static final String PRIVATE_KEY_REGEX =
"^(classpath:|file:\\.?[/]{1,8})[a-zA-Z0-9_-]{1,256}:?[/[a-zA-Z0-9_-]{1,256}]{0,256}(.pem)?$";
private Paths paths;
private TestData testData;
@Min(0)
@Max(28)
private Integer retentionDays;
@Min(0)
@Max(4000)
private int srsTypeStatisticsDays;
@Min(120)
@Max(720)
private Integer expiryPolicyMinutes;
@Min(0)
@Max(200)
private Integer shiftingPolicyThreshold;
@Min(600000)
@Max(750000)
private Integer maximumNumberOfKeysPerBundle;
@Pattern(regexp = FILE_NAME_REGEX)
private String outputFileName;
@Pattern(regexp = FILE_NAME_REGEX)
private String outputFileNameV2;
private Boolean includeIncompleteDays;
private Boolean includeIncompleteHours;
private String euPackageName;
private Boolean applyPoliciesForAllCountries;
private String cardIdSequence;
private TekExport tekExport;
private Signature signature;
private Api api;
private ObjectStore objectStore;
private List<AppFeature> appFeatures;
@NotEmpty
private String[] supportedCountries;
private AppVersions appVersions;
private AppConfigParameters appConfigParameters;
private StatisticsConfig statistics;
private QrCodePosterTemplate iosQrCodePosterTemplate;
private QrCodePosterTemplate androidQrCodePosterTemplate;
private PresenceTracingParameters presenceTracingParameters;
private DigitalGreenCertificate digitalGreenCertificate;
private Integer connectionPoolSize;
private String defaultArchiveName;
private Integer minimumTrlValueAllowed;
private Integer daysToPublish;
private DccRevocation dccRevocation;
@Min(0)
@Max(100)
private int infectionThreshold;
public QrCodePosterTemplate getAndroidQrCodePosterTemplate() {
return androidQrCodePosterTemplate;
}
public Api getApi() {
return api;
}
public AppConfigParameters getAppConfigParameters() {
return appConfigParameters;
}
public List<AppFeature> getAppFeatures() {
return appFeatures;
}
/**
* Get app features as list of protobuf objects.
*
* @return list of {@link app.coronawarn.server.common.protocols.internal.AppFeature}
*/
public List<app.coronawarn.server.common.protocols.internal.AppFeature> getAppFeaturesProto() {
return getAppFeatures().stream()
.map(appFeature -> app.coronawarn.server.common.protocols.internal.AppFeature.newBuilder()
.setLabel(appFeature.getLabel())
.setValue(appFeature.getValue()).build())
.collect(Collectors.toList());
}
public Boolean getApplyPoliciesForAllCountries() {
return applyPoliciesForAllCountries;
}
public AppVersions getAppVersions() {
return appVersions;
}
public String getCardIdSequence() {
return cardIdSequence;
}
public Integer getConnectionPoolSize() {
return connectionPoolSize;
}
public Integer getDaysToPublish() {
return daysToPublish == null ? retentionDays : daysToPublish;
}
public DccRevocation getDccRevocation() {
return dccRevocation;
}
public String getDefaultArchiveName() {
return defaultArchiveName;
}
public DigitalGreenCertificate getDigitalGreenCertificate() {
return digitalGreenCertificate;
}
public String getEuPackageName() {
return euPackageName;
}
public Integer getExpiryPolicyMinutes() {
return expiryPolicyMinutes;
}
public Boolean getIncludeIncompleteDays() {
return includeIncompleteDays;
}
public Boolean getIncludeIncompleteHours() {
return includeIncompleteHours;
}
public int getInfectionThreshold() {
return infectionThreshold;
}
public QrCodePosterTemplate getIosQrCodePosterTemplate() {
return iosQrCodePosterTemplate;
}
public Integer getMaximumNumberOfKeysPerBundle() {
return maximumNumberOfKeysPerBundle;
}
public Integer getMinimumTrlValueAllowed() {
return minimumTrlValueAllowed;
}
public ObjectStore getObjectStore() {
return objectStore;
}
public String getOutputFileName() {
return outputFileName;
}
public String getOutputFileNameV2() {
return outputFileNameV2;
}
public Paths getPaths() {
return paths;
}
public PresenceTracingParameters getPresenceTracingParameters() {
return presenceTracingParameters;
}
public Integer getRetentionDays() {
return retentionDays;
}
public Integer getShiftingPolicyThreshold() {
return shiftingPolicyThreshold;
}
public Signature getSignature() {
return signature;
}
public int getSrsTypeStatisticsDays() {
return srsTypeStatisticsDays;
}
public StatisticsConfig getStatistics() {
return statistics;
}
public String[] getSupportedCountries() {
return supportedCountries;
}
public TekExport getTekExport() {
return tekExport;
}
public TestData getTestData() {
return testData;
}
public void setAndroidQrCodePosterTemplate(final QrCodePosterTemplate androidQrCodePosterTemplate) {
this.androidQrCodePosterTemplate = androidQrCodePosterTemplate;
}
public void setApi(final Api api) {
this.api = api;
}
public void setAppConfigParameters(final AppConfigParameters appConfigParameters) {
this.appConfigParameters = appConfigParameters;
}
public void setAppFeatures(final List<AppFeature> appFeatures) {
this.appFeatures = appFeatures;
}
public void setApplyPoliciesForAllCountries(final Boolean applyPoliciesForAllCountries) {
this.applyPoliciesForAllCountries = applyPoliciesForAllCountries;
}
public void setAppVersions(final AppVersions appVersions) {
this.appVersions = appVersions;
}
public void setCardIdSequence(final String cardIdSequence) {
this.cardIdSequence = cardIdSequence;
}
public void setConnectionPoolSize(final Integer connectionPoolSize) {
this.connectionPoolSize = connectionPoolSize;
}
public void setDaysToPublish(final Integer daysToPublish) {
this.daysToPublish = daysToPublish;
}
public void setDccRevocation(final DccRevocation dccRevocation) {
this.dccRevocation = dccRevocation;
}
public void setDefaultArchiveName(final String defaultArchiveName) {
this.defaultArchiveName = defaultArchiveName;
}
public void setDigitalGreenCertificate(final DigitalGreenCertificate digitalGreenCertificate) {
this.digitalGreenCertificate = digitalGreenCertificate;
}
public void setEuPackageName(final String euPackageName) {
this.euPackageName = euPackageName;
}
public void setExpiryPolicyMinutes(final Integer expiryPolicyMinutes) {
this.expiryPolicyMinutes = expiryPolicyMinutes;
}
public void setIncludeIncompleteDays(final Boolean includeIncompleteDays) {
this.includeIncompleteDays = includeIncompleteDays;
}
public void setIncludeIncompleteHours(final Boolean includeIncompleteHours) {
this.includeIncompleteHours = includeIncompleteHours;
}
public void setInfectionThreshold(final int infectionThreshold) {
this.infectionThreshold = infectionThreshold;
}
public void setIosQrCodePosterTemplate(final QrCodePosterTemplate iosQrCodePosterTemplate) {
this.iosQrCodePosterTemplate = iosQrCodePosterTemplate;
}
public void setMaximumNumberOfKeysPerBundle(final Integer maximumNumberOfKeysPerBundle) {
this.maximumNumberOfKeysPerBundle = maximumNumberOfKeysPerBundle;
}
public void setMinimumTrlValueAllowed(final Integer minimumTrlValueAllowed) {
this.minimumTrlValueAllowed = minimumTrlValueAllowed;
}
public void setObjectStore(
final ObjectStore objectStore) {
this.objectStore = objectStore;
}
public void setOutputFileName(final String outputFileName) {
this.outputFileName = outputFileName;
}
public void setOutputFileNameV2(final String outputFileNameV2) {
this.outputFileNameV2 = outputFileNameV2;
}
public void setPaths(final Paths paths) {
this.paths = paths;
}
public void setPresenceTracingParameters(
final PresenceTracingParameters presenceTracingParameters) {
this.presenceTracingParameters = presenceTracingParameters;
}
public void setRetentionDays(final Integer retentionDays) {
this.retentionDays = retentionDays;
}
public void setShiftingPolicyThreshold(final Integer shiftingPolicyThreshold) {
this.shiftingPolicyThreshold = shiftingPolicyThreshold;
}
public void setSignature(final Signature signature) {
this.signature = signature;
}
public void setSrsTypeStatisticsDays(final int srsTypeStatisticsDays) {
this.srsTypeStatisticsDays = srsTypeStatisticsDays;
}
public void setStatistics(final StatisticsConfig statistics) {
this.statistics = statistics;
}
public void setSupportedCountries(final String[] supportedCountries) {
this.supportedCountries = supportedCountries;
}
public void setTekExport(final TekExport tekExport) {
this.tekExport = tekExport;
}
public void setTestData(final TestData testData) {
this.testData = testData;
}
}
| UTF-8 | Java | 64,671 | java | DistributionServiceConfig.java | Java | [] | null | [] | package app.coronawarn.server.services.distribution.config;
import app.coronawarn.server.common.protocols.external.exposurenotification.SignatureInfo;
import app.coronawarn.server.common.shared.util.SerializationUtils;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.File;
import java.util.List;
import java.util.stream.Collectors;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.PositiveOrZero;
import javax.validation.constraints.Size;
import org.bouncycastle.util.encoders.Hex;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;
@ConfigurationProperties(prefix = "services.distribution")
@Validated
public class DistributionServiceConfig {
public static class AllowList {
@JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public static class CertificateAllowList {
private String serviceProvider;
private String hostname;
private String fingerprint256;
@JsonProperty("serviceProviderAllowlistEndpoint")
private String serviceProviderAllowlistEndpoint;
public String getFingerprint256() {
return fingerprint256;
}
public String getHostname() {
return hostname;
}
public String getServiceProvider() {
return serviceProvider;
}
public String getServiceProviderAllowlistEndpoint() {
return serviceProviderAllowlistEndpoint;
}
@JsonProperty("fingerprint256")
public void setFingerprint256(final String fingerprint256) {
this.fingerprint256 = fingerprint256;
}
@JsonProperty("hostname")
public void setHostname(final String hostname) {
this.hostname = hostname;
}
@JsonProperty("serviceProvider")
public void setServiceProvider(final String serviceProvider) {
this.serviceProvider = serviceProvider;
}
public void setServiceProviderAllowlistEndpoint(final String serviceProviderAllowlistEndpoint) {
this.serviceProviderAllowlistEndpoint = serviceProviderAllowlistEndpoint;
}
}
@JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public static class ServiceProvider {
@JsonProperty("serviceProviderAllowlistEndpoint")
private String serviceProviderAllowlistEndpoint;
@JsonProperty("fingerprint256")
private String fingerprint256;
public String getFingerprint256() {
return fingerprint256;
}
public String getServiceProviderAllowlistEndpoint() {
return serviceProviderAllowlistEndpoint;
}
public void setFingerprint256(final String fingerprint256) {
this.fingerprint256 = fingerprint256;
}
public void setServiceProviderAllowlistEndpoint(final String serviceProviderAllowlistEndpoint) {
this.serviceProviderAllowlistEndpoint = serviceProviderAllowlistEndpoint;
}
}
private List<CertificateAllowList> certificates;
private List<ServiceProvider> serviceProviders;
public List<CertificateAllowList> getCertificates() {
return certificates;
}
public List<ServiceProvider> getServiceProviders() {
return serviceProviders;
}
@JsonProperty("certificates")
public void setCertificates(final List<CertificateAllowList> certificates) {
this.certificates = certificates;
}
@JsonProperty("serviceProviders")
public void setServiceProviders(final List<ServiceProvider> serviceProviders) {
this.serviceProviders = serviceProviders;
}
}
public static class Api {
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String versionPath;
@Pattern(regexp = VERSION_REGEX)
private String versionV1;
@Pattern(regexp = VERSION_REGEX)
private String versionV2;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String countryPath;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String originCountry;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String datePath;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String hourPath;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String diagnosisKeysPath;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String parametersPath;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String appConfigFileName;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String appConfigV2IosFileName;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String appConfigV2AndroidFileName;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String statisticsFileName;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String localStatisticsFileName;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String traceWarningsPath;
public String getAppConfigFileName() {
return appConfigFileName;
}
public String getAppConfigV2AndroidFileName() {
return appConfigV2AndroidFileName;
}
public String getAppConfigV2IosFileName() {
return appConfigV2IosFileName;
}
public String getCountryPath() {
return countryPath;
}
public String getDatePath() {
return datePath;
}
public String getDiagnosisKeysPath() {
return diagnosisKeysPath;
}
public String getHourPath() {
return hourPath;
}
public String getLocalStatisticsFileName() {
return localStatisticsFileName;
}
public String getOriginCountry() {
return originCountry;
}
public String getParametersPath() {
return parametersPath;
}
public String getStatisticsFileName() {
return statisticsFileName;
}
public String getTraceWarningsPath() {
return traceWarningsPath;
}
public String getVersionPath() {
return versionPath;
}
public String getVersionV1() {
return versionV1;
}
public String getVersionV2() {
return versionV2;
}
public void setAppConfigFileName(final String appConfigFileName) {
this.appConfigFileName = appConfigFileName;
}
public void setAppConfigV2AndroidFileName(final String appConfigV2AndroidFileName) {
this.appConfigV2AndroidFileName = appConfigV2AndroidFileName;
}
public void setAppConfigV2IosFileName(final String appConfigV2IosFileName) {
this.appConfigV2IosFileName = appConfigV2IosFileName;
}
public void setCountryPath(final String countryPath) {
this.countryPath = countryPath;
}
public void setDatePath(final String datePath) {
this.datePath = datePath;
}
public void setDiagnosisKeysPath(final String diagnosisKeysPath) {
this.diagnosisKeysPath = diagnosisKeysPath;
}
public void setHourPath(final String hourPath) {
this.hourPath = hourPath;
}
public void setLocalStatisticsFileName(final String localStatisticsFileName) {
this.localStatisticsFileName = localStatisticsFileName;
}
public void setOriginCountry(final String originCountry) {
this.originCountry = originCountry;
}
public void setParametersPath(final String parametersPath) {
this.parametersPath = parametersPath;
}
public void setStatisticsFileName(final String statisticsFileName) {
this.statisticsFileName = statisticsFileName;
}
public void setTraceWarningsPath(final String traceWarningsPath) {
this.traceWarningsPath = traceWarningsPath;
}
public void setVersionPath(final String versionPath) {
this.versionPath = versionPath;
}
public void setVersionV1(final String versionV1) {
this.versionV1 = versionV1;
}
public void setVersionV2(final String versionV2) {
this.versionV2 = versionV2;
}
}
public static class AppConfigParameters {
public static class AndroidEventDrivenUserSurveyParameters extends CommonEdusParameters {
@NotNull
private Boolean requireBasicIntegrity;
@NotNull
private Boolean requireCtsProfileMatch;
@NotNull
private Boolean requireEvaluationTypeBasic;
@NotNull
private Boolean requireEvaluationTypeHardwareBacked;
public Boolean getRequireBasicIntegrity() {
return requireBasicIntegrity;
}
public Boolean getRequireCtsProfileMatch() {
return requireCtsProfileMatch;
}
public Boolean getRequireEvaluationTypeBasic() {
return requireEvaluationTypeBasic;
}
public Boolean getRequireEvaluationTypeHardwareBacked() {
return requireEvaluationTypeHardwareBacked;
}
public void setRequireBasicIntegrity(final Boolean requireBasicIntegrity) {
this.requireBasicIntegrity = requireBasicIntegrity;
}
public void setRequireCtsProfileMatch(final Boolean requireCtsProfileMatch) {
this.requireCtsProfileMatch = requireCtsProfileMatch;
}
public void setRequireEvaluationTypeBasic(final Boolean requireEvaluationTypeBasic) {
this.requireEvaluationTypeBasic = requireEvaluationTypeBasic;
}
public void setRequireEvaluationTypeHardwareBacked(final Boolean requireEvaluationTypeHardwareBacked) {
this.requireEvaluationTypeHardwareBacked = requireEvaluationTypeHardwareBacked;
}
}
public static class AndroidExposureDetectionParameters {
private static final int LOWER_BOUNDARY_OVERALL_TIMEOUT = 0;
public static final String MIN_VALUE_ERROR_MESSAGE_OVERALL_TIMEOUT =
"Android Exposure Detection: overall timeout in seconds must be greater than or equal to "
+ LOWER_BOUNDARY_OVERALL_TIMEOUT;
private static final int UPPER_BOUNDARY_OVERALL_TIMEOUT = 3600;
public static final String MAX_VALUE_ERROR_MESSAGE_OVERALL_TIMEOUT =
"Android Exposure Detection: overall timeout in seconds must be lower than or equal to "
+ UPPER_BOUNDARY_OVERALL_TIMEOUT;
private static final int LOWER_BOUNDARY_MAX_EXPOSURE_DETECTIONS = 0;
public static final String MIN_VALUE_ERROR_MESSAGE_MAX_EXPOSURE_DETECTIONS =
"Android Exposure Detection: max exposure detections per interval must be greater than or equal to "
+ LOWER_BOUNDARY_MAX_EXPOSURE_DETECTIONS;
private static final int UPPER_BOUNDARY_MAX_EXPOSURE_DETECTIONS = 6;
public static final String MAX_VALUE_ERROR_MESSAGE_MAX_EXPOSURE_DETECTIONS =
"Android Exposure Detection: max exposure detections per interval must be lower than or equal to "
+ UPPER_BOUNDARY_MAX_EXPOSURE_DETECTIONS;
@Min(value = LOWER_BOUNDARY_MAX_EXPOSURE_DETECTIONS, message = MIN_VALUE_ERROR_MESSAGE_MAX_EXPOSURE_DETECTIONS)
@Max(value = UPPER_BOUNDARY_MAX_EXPOSURE_DETECTIONS, message = MAX_VALUE_ERROR_MESSAGE_MAX_EXPOSURE_DETECTIONS)
private Integer maxExposureDetectionsPerInterval;
@Min(value = LOWER_BOUNDARY_OVERALL_TIMEOUT, message = MIN_VALUE_ERROR_MESSAGE_OVERALL_TIMEOUT)
@Max(value = UPPER_BOUNDARY_OVERALL_TIMEOUT, message = MAX_VALUE_ERROR_MESSAGE_OVERALL_TIMEOUT)
private Integer overallTimeoutInSeconds;
public Integer getMaxExposureDetectionsPerInterval() {
return maxExposureDetectionsPerInterval;
}
public Integer getOverallTimeoutInSeconds() {
return overallTimeoutInSeconds;
}
public void setMaxExposureDetectionsPerInterval(final Integer maxExposureDetectionsPerInterval) {
this.maxExposureDetectionsPerInterval = maxExposureDetectionsPerInterval;
}
public void setOverallTimeoutInSeconds(final Integer overallTimeoutInSeconds) {
this.overallTimeoutInSeconds = overallTimeoutInSeconds;
}
}
public static class AndroidKeyDownloadParameters extends CommonKeyDownloadParameters {
private static final int LOWER_BOUNDARY_DOWNLOAD_TIMEOUT = 0;
public static final String MIN_VALUE_ERROR_MESSAGE_DOWNLOAD_TIMEOUT =
"Download timeout in seconds must be greater than or equal to " + LOWER_BOUNDARY_DOWNLOAD_TIMEOUT;
private static final int UPPER_BOUNDARY_DOWNLOAD_TIMEOUT = 1800;
public static final String MAX_VALUE_ERROR_MESSAGE_DOWNLOAD_TIMEOUT =
"Download timeout in seconds must be lower than or equal to " + UPPER_BOUNDARY_DOWNLOAD_TIMEOUT;
private static final int LOWER_BOUNDARY_OVERALL_TIMEOUT = 0;
public static final String MIN_VALUE_ERROR_MESSAGE_OVERALL_TIMEOUT =
"Android Key Download: overall timeout in seconds must be greater than or equal to "
+ LOWER_BOUNDARY_OVERALL_TIMEOUT;
private static final int UPPER_BOUNDARY_OVERALL_TIMEOUT = 1800;
public static final String MAX_VALUE_ERROR_MESSAGE_OVERALL_TIMEOUT =
"Android Key Download: overall timeout in seconds must be lower than or equal to "
+ UPPER_BOUNDARY_OVERALL_TIMEOUT;
@Min(value = LOWER_BOUNDARY_DOWNLOAD_TIMEOUT, message = MIN_VALUE_ERROR_MESSAGE_DOWNLOAD_TIMEOUT)
@Max(value = UPPER_BOUNDARY_DOWNLOAD_TIMEOUT, message = MAX_VALUE_ERROR_MESSAGE_DOWNLOAD_TIMEOUT)
private Integer downloadTimeoutInSeconds;
@Min(value = LOWER_BOUNDARY_OVERALL_TIMEOUT, message = MIN_VALUE_ERROR_MESSAGE_OVERALL_TIMEOUT)
@Max(value = UPPER_BOUNDARY_OVERALL_TIMEOUT, message = MAX_VALUE_ERROR_MESSAGE_OVERALL_TIMEOUT)
private Integer overallTimeoutInSeconds;
public Integer getDownloadTimeoutInSeconds() {
return downloadTimeoutInSeconds;
}
public Integer getOverallTimeoutInSeconds() {
return overallTimeoutInSeconds;
}
public void setDownloadTimeoutInSeconds(final Integer downloadTimeoutInSeconds) {
this.downloadTimeoutInSeconds = downloadTimeoutInSeconds;
}
public void setOverallTimeoutInSeconds(final Integer overallTimeoutInSeconds) {
this.overallTimeoutInSeconds = overallTimeoutInSeconds;
}
}
public static class AndroidPrivacyPreservingAnalyticsParameters extends CommonPpaParameters {
@NotNull
private Boolean requireBasicIntegrity;
@NotNull
private Boolean requireCtsProfileMatch;
@NotNull
private Boolean requireEvaluationTypeBasic;
@NotNull
private Boolean requireEvaluationTypeHardwareBacked;
public Boolean getRequireBasicIntegrity() {
return requireBasicIntegrity;
}
public Boolean getRequireCtsProfileMatch() {
return requireCtsProfileMatch;
}
public Boolean getRequireEvaluationTypeBasic() {
return requireEvaluationTypeBasic;
}
public Boolean getRequireEvaluationTypeHardwareBacked() {
return requireEvaluationTypeHardwareBacked;
}
public void setRequireBasicIntegrity(final Boolean requireBasicIntegrity) {
this.requireBasicIntegrity = requireBasicIntegrity;
}
public void setRequireCtsProfileMatch(final Boolean requireCtsProfileMatch) {
this.requireCtsProfileMatch = requireCtsProfileMatch;
}
public void setRequireEvaluationTypeBasic(final Boolean requireEvaluationTypeBasic) {
this.requireEvaluationTypeBasic = requireEvaluationTypeBasic;
}
public void setRequireEvaluationTypeHardwareBacked(final Boolean requireEvaluationTypeHardwareBacked) {
this.requireEvaluationTypeHardwareBacked = requireEvaluationTypeHardwareBacked;
}
}
public static class AndroidSrsPpacParameters extends AndroidPrivacyPreservingAnalyticsParameters {
}
private static class CommonEdusParameters {
@Size(min = 1, max = 30)
private String otpQueryParameterName;
@NotNull
private Boolean surveyOnHighRiskEnabled;
@Pattern(regexp = URL_REGEX)
private String surveyOnHighRiskUrl;
public String getOtpQueryParameterName() {
return otpQueryParameterName;
}
public Boolean getSurveyOnHighRiskEnabled() {
return surveyOnHighRiskEnabled;
}
public String getSurveyOnHighRiskUrl() {
return surveyOnHighRiskUrl;
}
public void setOtpQueryParameterName(final String otpQueryParameterName) {
this.otpQueryParameterName = otpQueryParameterName;
}
public void setSurveyOnHighRiskEnabled(final Boolean surveyOnHighRiskEnabled) {
this.surveyOnHighRiskEnabled = surveyOnHighRiskEnabled;
}
public void setSurveyOnHighRiskUrl(final String surveyOnHighRiskUrl) {
this.surveyOnHighRiskUrl = surveyOnHighRiskUrl;
}
}
private abstract static class CommonKeyDownloadParameters {
private String revokedDayPackages;
private String revokedHourPackages;
public List<DeserializedDayPackageMetadata> getRevokedDayPackages() {
return SerializationUtils.deserializeJson(revokedDayPackages,
typeFactory -> typeFactory.constructCollectionType(List.class, DeserializedDayPackageMetadata.class));
}
public List<DeserializedHourPackageMetadata> getRevokedHourPackages() {
return SerializationUtils.deserializeJson(revokedHourPackages,
typeFactory -> typeFactory
.constructCollectionType(List.class, DeserializedHourPackageMetadata.class));
}
public void setRevokedDayPackages(final String revokedDayPackages) {
this.revokedDayPackages = revokedDayPackages;
}
public void setRevokedHourPackages(final String revokedHourPackages) {
this.revokedHourPackages = revokedHourPackages;
}
}
private static class CommonPpaParameters {
private Double probabilityToSubmit;
private Double probabilityToSubmitExposureWindows;
@PositiveOrZero
private Integer hoursSinceTestRegistrationToSubmitTestResultMetadata;
@PositiveOrZero
private Integer hoursSinceTestToSubmitKeySubmissionMetadata;
public Integer getHoursSinceTestRegistrationToSubmitTestResultMetadata() {
return hoursSinceTestRegistrationToSubmitTestResultMetadata;
}
public Integer getHoursSinceTestToSubmitKeySubmissionMetadata() {
return hoursSinceTestToSubmitKeySubmissionMetadata;
}
public Double getProbabilityToSubmit() {
return probabilityToSubmit;
}
public Double getProbabilityToSubmitExposureWindows() {
return probabilityToSubmitExposureWindows;
}
public void setHoursSinceTestRegistrationToSubmitTestResultMetadata(final Integer integer) {
this.hoursSinceTestRegistrationToSubmitTestResultMetadata = integer;
}
public void setHoursSinceTestToSubmitKeySubmissionMetadata(
final Integer hoursSinceTestToSubmitKeySubmissionMetadata) {
this.hoursSinceTestToSubmitKeySubmissionMetadata = hoursSinceTestToSubmitKeySubmissionMetadata;
}
public void setProbabilityToSubmit(final Double probabilityToSubmit) {
this.probabilityToSubmit = probabilityToSubmit;
}
public void setProbabilityToSubmitExposureWindows(final Double probabilityToSubmitExposureWindows) {
this.probabilityToSubmitExposureWindows = probabilityToSubmitExposureWindows;
}
}
public static class DeserializedDayPackageMetadata {
private String region;
private String date;
private String etag;
public String getDate() {
return date;
}
public String getEtag() {
return etag;
}
public String getRegion() {
return region;
}
}
public static class DeserializedHourPackageMetadata extends DeserializedDayPackageMetadata {
private Integer hour;
public Integer getHour() {
return hour;
}
}
public static class DgcParameters {
public static class DgcBlocklistParameters {
public static class DgcBlockedUvciChunk {
List<Integer> indices;
String hash;
Integer validFrom;
public byte[] getHash() {
return Hex.decode(hash);
}
public List<Integer> getIndices() {
return indices;
}
public Integer getValidFrom() {
return validFrom;
}
public void setHash(final String hash) {
this.hash = hash;
}
public void setIndices(final List<Integer> indices) {
this.indices = indices;
}
public void setValidFrom(final Integer validFrom) {
this.validFrom = validFrom;
}
}
private String blockedUvciChunks;
/**
* Parse String from application.yaml parameter.
*
* @return parsed string in a list of DgcBlockedUvciChunk.
*/
public List<DgcBlockedUvciChunk> getBlockedUvciChunks() {
return SerializationUtils.deserializeJson(blockedUvciChunks,
typeFactory -> typeFactory
.constructCollectionType(List.class, DgcBlockedUvciChunk.class));
}
public void setBlockedUvciChunks(final String blockedUvciChunks) {
this.blockedUvciChunks = blockedUvciChunks;
}
}
public static class DgcTestCertificateParameters {
@Min(0)
@Max(60)
private Integer waitAfterPublicKeyRegistrationInSeconds;
@Min(0)
@Max(60)
private Integer waitForRetryInSeconds;
public Integer getWaitAfterPublicKeyRegistrationInSeconds() {
return waitAfterPublicKeyRegistrationInSeconds;
}
public Integer getWaitForRetryInSeconds() {
return waitForRetryInSeconds;
}
public void setWaitAfterPublicKeyRegistrationInSeconds(final Integer waitAfterPublicKeyRegistrationInSeconds) {
this.waitAfterPublicKeyRegistrationInSeconds = waitAfterPublicKeyRegistrationInSeconds;
}
public void setWaitForRetryInSeconds(final Integer waitForRetryInSeconds) {
this.waitForRetryInSeconds = waitForRetryInSeconds;
}
}
private DgcTestCertificateParameters dgcTestCertificateParameters;
@Min(0)
@Max(100)
private Integer expirationThresholdInDays;
private DgcBlocklistParameters blockListParameters;
private String iosDgcReissueServicePublicKeyDigest;
private String androidDgcReissueServicePublicKeyDigest;
public byte[] getAndroidDgcReissueServicePublicKeyDigest() {
return Hex.decode(androidDgcReissueServicePublicKeyDigest);
}
public DgcBlocklistParameters getBlockListParameters() {
return blockListParameters;
}
public Integer getExpirationThresholdInDays() {
return expirationThresholdInDays;
}
public byte[] getIosDgcReissueServicePublicKeyDigest() {
return Hex.decode(iosDgcReissueServicePublicKeyDigest);
}
public DgcTestCertificateParameters getTestCertificateParameters() {
return dgcTestCertificateParameters;
}
public void setAndroidDgcReissueServicePublicKeyDigest(final String androidDgcReissueServicePublicKeyDigest) {
this.androidDgcReissueServicePublicKeyDigest = androidDgcReissueServicePublicKeyDigest;
}
public void setBlockListParameters(final DgcBlocklistParameters blockListParameters) {
this.blockListParameters = blockListParameters;
}
public void setExpirationThresholdInDays(final Integer expirationThresholdInDays) {
this.expirationThresholdInDays = expirationThresholdInDays;
}
public void setIosDgcReissueServicePublicKeyDigest(final String iosDgcReissueServicePublicKeyDigest) {
this.iosDgcReissueServicePublicKeyDigest = iosDgcReissueServicePublicKeyDigest;
}
public void setTestCertificateParameters(final DgcTestCertificateParameters dgcTestCertificateParameters) {
this.dgcTestCertificateParameters = dgcTestCertificateParameters;
}
}
public static class IosEventDrivenUserSurveyParameters extends CommonEdusParameters {
}
public static class IosExposureDetectionParameters {
private static final int MIN_VALUE_MAX_EXPOSURE_DETECTIONS = 0;
public static final String MIN_VALUE_ERROR_MESSAGE_MAX_EXPOSURE_DETECTIONS =
"IOS Exposure Detection: max exposure detections per interval must be greater than or equal to "
+ MIN_VALUE_MAX_EXPOSURE_DETECTIONS;
private static final int MAX_VALUE_MAX_EXPOSURE_DETECTIONS = 6;
public static final String MAX_VALUE_ERROR_MESSAGE_MAX_EXPOSURE_DETECTIONS =
"IOS Exposure Detection: max exposure detections per interval must be lower than or equal to "
+ MAX_VALUE_MAX_EXPOSURE_DETECTIONS;
@Min(value = MIN_VALUE_MAX_EXPOSURE_DETECTIONS, message = MIN_VALUE_ERROR_MESSAGE_MAX_EXPOSURE_DETECTIONS)
@Max(value = MAX_VALUE_MAX_EXPOSURE_DETECTIONS, message = MAX_VALUE_ERROR_MESSAGE_MAX_EXPOSURE_DETECTIONS)
private Integer maxExposureDetectionsPerInterval;
public Integer getMaxExposureDetectionsPerInterval() {
return maxExposureDetectionsPerInterval;
}
public void setMaxExposureDetectionsPerInterval(final Integer maxExposureDetectionsPerInterval) {
this.maxExposureDetectionsPerInterval = maxExposureDetectionsPerInterval;
}
}
public static class IosKeyDownloadParameters extends CommonKeyDownloadParameters {
}
public static class IosPrivacyPreservingAnalyticsParameters extends CommonPpaParameters {
}
private IosKeyDownloadParameters iosKeyDownloadParameters;
private AndroidKeyDownloadParameters androidKeyDownloadParameters;
private IosExposureDetectionParameters iosExposureDetectionParameters;
private AndroidExposureDetectionParameters androidExposureDetectionParameters;
private IosEventDrivenUserSurveyParameters iosEventDrivenUserSurveyParameters;
private AndroidEventDrivenUserSurveyParameters androidEventDrivenUserSurveyParameters;
private IosPrivacyPreservingAnalyticsParameters iosPrivacyPreservingAnalyticsParameters;
private AndroidPrivacyPreservingAnalyticsParameters androidPrivacyPreservingAnalyticsParameters;
private AndroidSrsPpacParameters androidSrsPpacParameters;
private DgcParameters dgcParameters;
@Min(1)
@Max(1000)
private int srsTimeSinceOnboardingInHours;
@Min(1)
@Max(1000)
private int srsTimeBetweenSubmissionsInDays;
public AndroidEventDrivenUserSurveyParameters getAndroidEventDrivenUserSurveyParameters() {
return androidEventDrivenUserSurveyParameters;
}
public AndroidExposureDetectionParameters getAndroidExposureDetectionParameters() {
return androidExposureDetectionParameters;
}
public AndroidKeyDownloadParameters getAndroidKeyDownloadParameters() {
return androidKeyDownloadParameters;
}
public AndroidPrivacyPreservingAnalyticsParameters getAndroidPrivacyPreservingAnalyticsParameters() {
return androidPrivacyPreservingAnalyticsParameters;
}
public AndroidSrsPpacParameters getAndroidSrsPpacParameters() {
return androidSrsPpacParameters;
}
public DgcParameters getDgcParameters() {
return dgcParameters;
}
public IosEventDrivenUserSurveyParameters getIosEventDrivenUserSurveyParameters() {
return iosEventDrivenUserSurveyParameters;
}
public IosExposureDetectionParameters getIosExposureDetectionParameters() {
return iosExposureDetectionParameters;
}
public IosKeyDownloadParameters getIosKeyDownloadParameters() {
return iosKeyDownloadParameters;
}
public IosPrivacyPreservingAnalyticsParameters getIosPrivacyPreservingAnalyticsParameters() {
return iosPrivacyPreservingAnalyticsParameters;
}
public int getSrsTimeBetweenSubmissionsInDays() {
return srsTimeBetweenSubmissionsInDays;
}
public int getSrsTimeSinceOnboardingInHours() {
return srsTimeSinceOnboardingInHours;
}
public void setAndroidEventDrivenUserSurveyParameters(
final AndroidEventDrivenUserSurveyParameters androidEventDrivenUserSurveyParameters) {
this.androidEventDrivenUserSurveyParameters = androidEventDrivenUserSurveyParameters;
}
public void setAndroidExposureDetectionParameters(
final AndroidExposureDetectionParameters androidExposureDetectionParameters) {
this.androidExposureDetectionParameters = androidExposureDetectionParameters;
}
public void setAndroidKeyDownloadParameters(final AndroidKeyDownloadParameters androidKeyDownloadParameters) {
this.androidKeyDownloadParameters = androidKeyDownloadParameters;
}
public void setAndroidPrivacyPreservingAnalyticsParameters(
final AndroidPrivacyPreservingAnalyticsParameters androidPrivacyPreservingAnalyticsParameters) {
this.androidPrivacyPreservingAnalyticsParameters = androidPrivacyPreservingAnalyticsParameters;
}
public void setAndroidSrsPpacParameters(final AndroidSrsPpacParameters androidSrsPpacParameters) {
this.androidSrsPpacParameters = androidSrsPpacParameters;
}
public void setDgcParameters(final DgcParameters dgcParameters) {
this.dgcParameters = dgcParameters;
}
public void setIosEventDrivenUserSurveyParameters(
final IosEventDrivenUserSurveyParameters iosEventDrivenUserSurveyParameters) {
this.iosEventDrivenUserSurveyParameters = iosEventDrivenUserSurveyParameters;
}
public void setIosExposureDetectionParameters(final IosExposureDetectionParameters iosExposureDetectionParameters) {
this.iosExposureDetectionParameters = iosExposureDetectionParameters;
}
public void setIosKeyDownloadParameters(final IosKeyDownloadParameters iosKeyDownloadParameters) {
this.iosKeyDownloadParameters = iosKeyDownloadParameters;
}
public void setIosPrivacyPreservingAnalyticsParameters(
final IosPrivacyPreservingAnalyticsParameters iosPrivacyPreservingAnalyticsParameters) {
this.iosPrivacyPreservingAnalyticsParameters = iosPrivacyPreservingAnalyticsParameters;
}
public void setSrsTimeBetweenSubmissionsInDays(final int srsTimeBetweenSubmissionsInDays) {
this.srsTimeBetweenSubmissionsInDays = srsTimeBetweenSubmissionsInDays;
}
public void setSrsTimeSinceOnboardingInHours(final int srsTimeSinceOnboardingInHours) {
this.srsTimeSinceOnboardingInHours = srsTimeSinceOnboardingInHours;
}
}
public static class AppFeature {
private String label;
private Integer value;
public String getLabel() {
return label;
}
public Integer getValue() {
return value;
}
public void setLabel(final String label) {
this.label = label;
}
public void setValue(final Integer value) {
this.value = value;
}
}
public static class AppVersions {
private String latestIos;
private String minIos;
private String latestAndroid;
private String minAndroid;
@PositiveOrZero
private Integer latestAndroidVersionCode;
@PositiveOrZero
private Integer minAndroidVersionCode;
public String getLatestAndroid() {
return latestAndroid;
}
public Integer getLatestAndroidVersionCode() {
return latestAndroidVersionCode;
}
public String getLatestIos() {
return latestIos;
}
public String getMinAndroid() {
return minAndroid;
}
public Integer getMinAndroidVersionCode() {
return minAndroidVersionCode;
}
public String getMinIos() {
return minIos;
}
public void setLatestAndroid(final String latestAndroid) {
this.latestAndroid = latestAndroid;
}
public void setLatestAndroidVersionCode(final Integer latestAndroidVersionCode) {
this.latestAndroidVersionCode = latestAndroidVersionCode;
}
public void setLatestIos(final String latestIos) {
this.latestIos = latestIos;
}
public void setMinAndroid(final String minAndroid) {
this.minAndroid = minAndroid;
}
public void setMinAndroidVersionCode(final Integer minAndroidVersionCode) {
this.minAndroidVersionCode = minAndroidVersionCode;
}
public void setMinIos(final String minIos) {
this.minIos = minIos;
}
}
public static class Client {
public static class Ssl {
private File trustStore;
private String trustStorePassword;
public File getTrustStore() {
return trustStore;
}
public String getTrustStorePassword() {
return trustStorePassword;
}
public void setTrustStore(final File trustStore) {
this.trustStore = trustStore;
}
public void setTrustStorePassword(final String trustStorePassword) {
this.trustStorePassword = trustStorePassword;
}
}
private String publicKey;
private String baseUrl;
private Ssl ssl;
private int retryPeriod;
private int maxRetryPeriod;
private int maxRetryAttempts;
public String getBaseUrl() {
return baseUrl;
}
public int getMaxRetryAttempts() {
return maxRetryAttempts;
}
public int getMaxRetryPeriod() {
return maxRetryPeriod;
}
public String getPublicKey() {
return publicKey;
}
public int getRetryPeriod() {
return retryPeriod;
}
public Ssl getSsl() {
return ssl;
}
public void setBaseUrl(final String baseUrl) {
this.baseUrl = baseUrl;
}
public void setMaxRetryAttempts(final int maxRetryAttempts) {
this.maxRetryAttempts = maxRetryAttempts;
}
public void setMaxRetryPeriod(final int maxRetryPeriod) {
this.maxRetryPeriod = maxRetryPeriod;
}
public void setPublicKey(final String publicKey) {
this.publicKey = publicKey;
}
public void setRetryPeriod(final int retryPeriod) {
this.retryPeriod = retryPeriod;
}
public void setSsl(final Ssl ssl) {
this.ssl = ssl;
}
}
public static class DccRevocation {
private Client client;
private String certificate;
private String dccListPath;
private String dccRevocationDirectory;
public String getCertificate() {
return certificate;
}
public Client getClient() {
return client;
}
public String getDccListPath() {
return dccListPath;
}
public String getDccRevocationDirectory() {
return dccRevocationDirectory;
}
public void setCertificate(final String certificate) {
this.certificate = certificate;
}
public void setClient(final Client client) {
this.client = client;
}
public void setDccListPath(final String dccListPath) {
this.dccListPath = dccListPath;
}
public void setDccRevocationDirectory(final String dccRevocationDirectory) {
this.dccRevocationDirectory = dccRevocationDirectory;
}
}
public static class DigitalGreenCertificate {
@Pattern(regexp = RESOURCE_OR_EMPTY_REGEX)
private String mahJsonPath;
@Pattern(regexp = RESOURCE_OR_EMPTY_REGEX)
private String prophylaxisJsonPath;
@Pattern(regexp = RESOURCE_OR_EMPTY_REGEX)
private String medicinalProductsJsonPath;
@Pattern(regexp = RESOURCE_OR_EMPTY_REGEX)
private String diseaseAgentTargetedJsonPath;
@Pattern(regexp = RESOURCE_OR_EMPTY_REGEX)
private String testManfJsonPath;
@Pattern(regexp = RESOURCE_OR_EMPTY_REGEX)
private String testResultJsonPath;
@Pattern(regexp = RESOURCE_OR_EMPTY_REGEX)
private String testTypeJsonPath;
@NotNull
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String dgcDirectory;
@NotNull
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String boosterNotification;
@NotNull
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String valuesetsFileName;
private String cclDirectory;
private String[] cclAllowList;
private String allowList;
private String allowListSignature;
private String allowListCertificate;
private String[] supportedLanguages;
private String exportArchiveName;
private Client client;
private Client dscClient;
/**
* getAllowList.
*
* @return AllowList
*/
public AllowList getAllowList() {
return SerializationUtils.deserializeJson(allowList,
typeFactory -> typeFactory
.constructType(AllowList.class));
}
public String getAllowListAsString() {
return allowList;
}
public String getAllowListCertificate() {
return allowListCertificate;
}
public byte[] getAllowListSignature() {
return Hex.decode(allowListSignature);
}
public String getBoosterNotification() {
return boosterNotification;
}
public String[] getCclAllowList() {
return cclAllowList;
}
public String getCclDirectory() {
return cclDirectory;
}
public Client getClient() {
return client;
}
public String getDgcDirectory() {
return dgcDirectory;
}
public String getDiseaseAgentTargetedJsonPath() {
return diseaseAgentTargetedJsonPath;
}
public Client getDscClient() {
return dscClient;
}
public String getExportArchiveName() {
return exportArchiveName;
}
public String getMahJsonPath() {
return mahJsonPath;
}
public String getMedicinalProductsJsonPath() {
return medicinalProductsJsonPath;
}
public String getProphylaxisJsonPath() {
return prophylaxisJsonPath;
}
public String[] getSupportedLanguages() {
return supportedLanguages;
}
public String getTestManfJsonPath() {
return testManfJsonPath;
}
public String getTestResultJsonPath() {
return testResultJsonPath;
}
public String getTestTypeJsonPath() {
return testTypeJsonPath;
}
public String getValuesetsFileName() {
return valuesetsFileName;
}
public void setAllowList(final String allowList) {
this.allowList = allowList;
}
public void setAllowListCertificate(final String allowListCertificate) {
this.allowListCertificate = allowListCertificate;
}
public void setAllowListSignature(final String allowListSignature) {
this.allowListSignature = allowListSignature;
}
public void setBoosterNotification(final String boosterNotification) {
this.boosterNotification = boosterNotification;
}
public void setCclAllowList(final String[] cclAllowList) {
this.cclAllowList = cclAllowList;
}
public void setCclDirectory(final String cclDirectory) {
this.cclDirectory = cclDirectory;
}
public void setClient(final Client client) {
this.client = client;
}
public void setDgcDirectory(final String dgcDirectory) {
this.dgcDirectory = dgcDirectory;
}
public void setDiseaseAgentTargetedJsonPath(final String diseaseAgentTargetedJsonPath) {
this.diseaseAgentTargetedJsonPath = diseaseAgentTargetedJsonPath;
}
public void setDscClient(final Client dscClient) {
this.dscClient = dscClient;
}
public void setExportArchiveName(final String exportArchiveName) {
this.exportArchiveName = exportArchiveName;
}
public void setMahJsonPath(final String mahJsonPath) {
this.mahJsonPath = mahJsonPath;
}
public void setMedicinalProductsJsonPath(final String medicinalProductsJsonPath) {
this.medicinalProductsJsonPath = medicinalProductsJsonPath;
}
public void setProphylaxisJsonPath(final String prophylaxisJsonPath) {
this.prophylaxisJsonPath = prophylaxisJsonPath;
}
public void setSupportedLanguages(final String[] supportedLanguages) {
this.supportedLanguages = supportedLanguages;
}
public void setTestManfJsonPath(final String testManfJsonPath) {
this.testManfJsonPath = testManfJsonPath;
}
public void setTestResultJsonPath(final String testResultJsonPath) {
this.testResultJsonPath = testResultJsonPath;
}
public void setTestTypeJsonPath(final String testTypeJsonPath) {
this.testTypeJsonPath = testTypeJsonPath;
}
public void setValuesetsFileName(final String valuesetsFileName) {
this.valuesetsFileName = valuesetsFileName;
}
}
public static class ObjectStore {
@Pattern(regexp = NO_WHITESPACE_REGEX)
private String accessKey;
@Pattern(regexp = NO_WHITESPACE_REGEX)
private String secretKey;
@Pattern(regexp = URL_REGEX)
private String endpoint;
@Min(1)
@Max(65535)
private Integer port;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String bucket;
private Boolean setPublicReadAclOnPutObject;
@Min(1)
@Max(64)
private Integer maxNumberOfFailedOperations;
@Min(1)
@Max(64)
private Integer maxNumberOfS3Threads;
private Boolean forceUpdateKeyfiles;
@Max(Integer.MAX_VALUE)
private Integer hourFileRetentionDays;
public String getAccessKey() {
return accessKey;
}
public String getBucket() {
return bucket;
}
public String getEndpoint() {
return endpoint;
}
public Boolean getForceUpdateKeyfiles() {
return forceUpdateKeyfiles;
}
public Integer getHourFileRetentionDays() {
return hourFileRetentionDays;
}
public Integer getMaxNumberOfFailedOperations() {
return maxNumberOfFailedOperations;
}
public Integer getMaxNumberOfS3Threads() {
return maxNumberOfS3Threads;
}
public Integer getPort() {
return port;
}
public String getSecretKey() {
return secretKey;
}
public Boolean isSetPublicReadAclOnPutObject() {
return setPublicReadAclOnPutObject;
}
public void setAccessKey(final String accessKey) {
this.accessKey = accessKey;
}
public void setBucket(final String bucket) {
this.bucket = bucket;
}
public void setEndpoint(final String endpoint) {
this.endpoint = endpoint;
}
public void setForceUpdateKeyfiles(final Boolean forceUpdateKeyfiles) {
this.forceUpdateKeyfiles = forceUpdateKeyfiles;
}
public void setHourFileRetentionDays(final Integer hourFileRetentionDays) {
this.hourFileRetentionDays = hourFileRetentionDays;
}
public void setMaxNumberOfFailedOperations(final Integer maxNumberOfFailedOperations) {
this.maxNumberOfFailedOperations = maxNumberOfFailedOperations;
}
public void setMaxNumberOfS3Threads(final Integer maxNumberOfS3Threads) {
this.maxNumberOfS3Threads = maxNumberOfS3Threads;
}
public void setPort(final Integer port) {
this.port = port;
}
public void setSecretKey(final String secretKey) {
this.secretKey = secretKey;
}
public void setSetPublicReadAclOnPutObject(final Boolean setPublicReadAclOnPutObject) {
this.setPublicReadAclOnPutObject = setPublicReadAclOnPutObject;
}
}
public static class Paths {
@Pattern(regexp = PRIVATE_KEY_REGEX)
private String privateKey;
@Pattern(regexp = PATH_REGEX)
private String output;
public String getOutput() {
return output;
}
public String getPrivateKey() {
return privateKey;
}
public void setOutput(final String output) {
this.output = output;
}
public void setPrivateKey(final String privateKey) {
this.privateKey = privateKey;
}
}
public static class PresenceTracingParameters {
public static class PlausibleDeniabilityParameters {
private double probabilityToFakeCheckInsIfNoCheckIns;
private double probabilityToFakeCheckInsIfSomeCheckIns;
public double getProbabilityToFakeCheckInsIfNoCheckIns() {
return probabilityToFakeCheckInsIfNoCheckIns;
}
public double getProbabilityToFakeCheckInsIfSomeCheckIns() {
return probabilityToFakeCheckInsIfSomeCheckIns;
}
public void setProbabilityToFakeCheckInsIfNoCheckIns(final double probabilityToFakeCheckInsIfNoCheckIns) {
this.probabilityToFakeCheckInsIfNoCheckIns = probabilityToFakeCheckInsIfNoCheckIns;
}
public void setProbabilityToFakeCheckInsIfSomeCheckIns(final double probabilityToFakeCheckInsIfSomeCheckIns) {
this.probabilityToFakeCheckInsIfSomeCheckIns = probabilityToFakeCheckInsIfSomeCheckIns;
}
}
private int qrCodeErrorCorrectionLevel;
private PlausibleDeniabilityParameters plausibleDeniabilityParameters;
public PlausibleDeniabilityParameters getPlausibleDeniabilityParameters() {
return plausibleDeniabilityParameters;
}
public int getQrCodeErrorCorrectionLevel() {
return qrCodeErrorCorrectionLevel;
}
public void setPlausibleDeniabilityParameters(final PlausibleDeniabilityParameters plausibleDeniabilityParameters) {
this.plausibleDeniabilityParameters = plausibleDeniabilityParameters;
}
public void setQrCodeErrorCorrectionLevel(final int qrCodeErrorCorrectionLevel) {
this.qrCodeErrorCorrectionLevel = qrCodeErrorCorrectionLevel;
}
}
public static class QrCodePosterTemplate {
public static class DescriptionTextBox {
@NotNull
private Double offsetX;
@NotNull
private Double offsetY;
@NotNull
private Integer width;
@NotNull
private Integer height;
@NotNull
private Integer fontSize;
@NotNull
private String fontColor;
public String getFontColor() {
return fontColor;
}
public Integer getFontSize() {
return fontSize;
}
public Integer getHeight() {
return height;
}
public Double getOffsetX() {
return offsetX;
}
public Double getOffsetY() {
return offsetY;
}
public Integer getWidth() {
return width;
}
public void setFontColor(final String fontColor) {
this.fontColor = fontColor;
}
public void setFontSize(final Integer fontSize) {
this.fontSize = fontSize;
}
public void setHeight(final Integer height) {
this.height = height;
}
public void setOffsetX(final Double offsetX) {
this.offsetX = offsetX;
}
public void setOffsetY(final Double offsetY) {
this.offsetY = offsetY;
}
public void setWidth(final Integer width) {
this.width = width;
}
}
private String template;
@NotNull
private Double offsetX;
@NotNull
private Double offsetY;
@NotNull
private Integer qrCodeSideLength;
@NotEmpty
private String publishedArchiveName;
private DescriptionTextBox descriptionTextBox;
private DescriptionTextBox addressTextBox;
public DescriptionTextBox getAddressTextBox() {
return addressTextBox;
}
public DescriptionTextBox getDescriptionTextBox() {
return descriptionTextBox;
}
public Double getOffsetX() {
return offsetX;
}
public Double getOffsetY() {
return offsetY;
}
public String getPublishedArchiveName() {
return publishedArchiveName;
}
public Integer getQrCodeSideLength() {
return qrCodeSideLength;
}
public String getTemplate() {
return template;
}
public void setAddressTextBox(final DescriptionTextBox addressTextBox) {
this.addressTextBox = addressTextBox;
}
public void setDescriptionTextBox(final DescriptionTextBox descriptionTextBox) {
this.descriptionTextBox = descriptionTextBox;
}
public void setOffsetX(final Double offsetX) {
this.offsetX = offsetX;
}
public void setOffsetY(final Double offsetY) {
this.offsetY = offsetY;
}
public void setPublishedArchiveName(final String publishedArchiveName) {
this.publishedArchiveName = publishedArchiveName;
}
public void setQrCodeSideLength(final Integer qrCodeSideLength) {
this.qrCodeSideLength = qrCodeSideLength;
}
public void setTemplate(final String template) {
this.template = template;
}
}
public static class Signature {
@Pattern(regexp = BUNDLE_REGEX)
private String appBundleId;
private String androidPackage;
@Pattern(regexp = NUMBER_REGEX)
private String verificationKeyId;
@Pattern(regexp = VERSION_REGEX)
private String verificationKeyVersion;
@Pattern(regexp = ALGORITHM_OID_REGEX)
private String algorithmOid;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String algorithmName;
@Pattern(regexp = FILE_NAME_WITH_TYPE_REGEX)
private String fileName;
@Pattern(regexp = CHAR_AND_NUMBER_REGEX)
private String securityProvider;
public String getAlgorithmName() {
return algorithmName;
}
public String getAlgorithmOid() {
return algorithmOid;
}
public String getAndroidPackage() {
return androidPackage;
}
public String getAppBundleId() {
return appBundleId;
}
public String getFileName() {
return fileName;
}
public String getSecurityProvider() {
return securityProvider;
}
/**
* Returns the static {@link SignatureInfo} configured in the application properties.
*
* @return SignatureInfo
*/
public SignatureInfo getSignatureInfo() {
return SignatureInfo.newBuilder()
.setAppBundleId(getAppBundleId())
.setVerificationKeyVersion(getVerificationKeyVersion())
.setVerificationKeyId(getVerificationKeyId())
.setSignatureAlgorithm(getAlgorithmOid())
.build();
}
public String getVerificationKeyId() {
return verificationKeyId;
}
public String getVerificationKeyVersion() {
return verificationKeyVersion;
}
public void setAlgorithmName(final String algorithmName) {
this.algorithmName = algorithmName;
}
public void setAlgorithmOid(final String algorithmOid) {
this.algorithmOid = algorithmOid;
}
public void setAndroidPackage(final String androidPackage) {
this.androidPackage = androidPackage;
}
public void setAppBundleId(final String appBundleId) {
this.appBundleId = appBundleId;
}
public void setFileName(final String fileName) {
this.fileName = fileName;
}
public void setSecurityProvider(final String securityProvider) {
this.securityProvider = securityProvider;
}
public void setVerificationKeyId(final String verificationKeyId) {
this.verificationKeyId = verificationKeyId;
}
public void setVerificationKeyVersion(final String verificationKeyVersion) {
this.verificationKeyVersion = verificationKeyVersion;
}
}
public static class StatisticsConfig {
private String statisticPath;
private String localStatisticPath;
private String accessKey;
private String secretKey;
private String endpoint;
private String bucket;
private String pandemicRadarUrl;
private String pandemicRadarBmgUrl;
public String getAccessKey() {
return accessKey;
}
public String getBucket() {
return bucket;
}
public String getEndpoint() {
return endpoint;
}
public String getLocalStatisticPath() {
return localStatisticPath;
}
public String getPandemicRadarBmgUrl() {
return pandemicRadarBmgUrl;
}
public String getPandemicRadarUrl() {
return pandemicRadarUrl;
}
public String getSecretKey() {
return secretKey;
}
public String getStatisticPath() {
return statisticPath;
}
public void setAccessKey(final String accessKey) {
this.accessKey = accessKey;
}
public void setBucket(final String bucket) {
this.bucket = bucket;
}
public void setEndpoint(final String endpoint) {
this.endpoint = endpoint;
}
public void setLocalStatisticPath(final String localStatisticPath) {
this.localStatisticPath = localStatisticPath;
}
public void setPandemicRadarBmgUrl(final String pandemicRadarBmgUrl) {
this.pandemicRadarBmgUrl = pandemicRadarBmgUrl;
}
public void setPandemicRadarUrl(final String pandemicRadarUrl) {
this.pandemicRadarUrl = pandemicRadarUrl;
}
public void setSecretKey(final String secretKey) {
this.secretKey = secretKey;
}
public void setStatisticPath(final String statisticPath) {
this.statisticPath = statisticPath;
}
}
public static class TekExport {
@Pattern(regexp = FILE_NAME_WITH_TYPE_REGEX)
private String fileName;
@Pattern(regexp = CHAR_NUMBER_AND_SPACE_REGEX)
private String fileHeader;
@Min(0)
@Max(32)
private Integer fileHeaderWidth;
public String getFileHeader() {
return fileHeader;
}
public Integer getFileHeaderWidth() {
return fileHeaderWidth;
}
public String getFileName() {
return fileName;
}
public void setFileHeader(final String fileHeader) {
this.fileHeader = fileHeader;
}
public void setFileHeaderWidth(final Integer fileHeaderWidth) {
this.fileHeaderWidth = fileHeaderWidth;
}
public void setFileName(final String fileName) {
this.fileName = fileName;
}
}
public static class TestData {
private Integer seed;
private Integer exposuresPerHour;
private boolean distributionTestdataConsentToFederation;
public boolean getDistributionTestdataConsentToFederation() {
return distributionTestdataConsentToFederation;
}
public Integer getExposuresPerHour() {
return exposuresPerHour;
}
public Integer getSeed() {
return seed;
}
public void setDistributionTestdataConsentToFederation(final boolean distributionTestdataConsentToFederation) {
this.distributionTestdataConsentToFederation = distributionTestdataConsentToFederation;
}
public void setExposuresPerHour(final Integer exposuresPerHour) {
this.exposuresPerHour = exposuresPerHour;
}
public void setSeed(final Integer seed) {
this.seed = seed;
}
}
private static final String PATH_REGEX = "^[/]?[a-zA-Z0-9_]{1,1024}(/[a-zA-Z0-9_]{1,1024}){0,256}[/]?$";
private static final String RESOURCE_REGEX = "^(classpath:|file:[/]{1,3})?([a-zA-Z0-9_/\\.]{1,1010})$";
private static final String RESOURCE_OR_EMPTY_REGEX = "(" + RESOURCE_REGEX + ")?";
private static final String FILE_NAME_REGEX = "^[a-zA-Z0-9_-]{1,1024}$";
private static final String FILE_NAME_WITH_TYPE_REGEX = "^[a-zA-Z0-9_-]{1,1024}\\.[a-z]{1,64}$";
private static final String CHAR_AND_NUMBER_REGEX = "^[a-zA-Z0-9_-]{1,1024}$";
private static final String CHAR_NUMBER_AND_SPACE_REGEX = "^[a-zA-Z0-9_\\s]{1,32}$";
private static final String NO_WHITESPACE_REGEX = "^[\\S]+$";
private static final String URL_REGEX = "^http[s]?://[a-zA-Z0-9-_]{1,1024}([\\./][a-zA-Z0-9-_]{1,1024}){0,256}[/]?$";
private static final String NUMBER_REGEX = "^[0-9]{1,256}$";
private static final String VERSION_REGEX = "^v[0-9]{1,256}$";
private static final String ALGORITHM_OID_REGEX = "^[0-9]{1,256}[\\.[0-9]{1,256}]{0,256}$";
private static final String BUNDLE_REGEX = "^[a-z-]{1,256}[\\.[a-z-]{1,256}]{0,256}$";
private static final String PRIVATE_KEY_REGEX =
"^(classpath:|file:\\.?[/]{1,8})[a-zA-Z0-9_-]{1,256}:?[/[a-zA-Z0-9_-]{1,256}]{0,256}(.pem)?$";
private Paths paths;
private TestData testData;
@Min(0)
@Max(28)
private Integer retentionDays;
@Min(0)
@Max(4000)
private int srsTypeStatisticsDays;
@Min(120)
@Max(720)
private Integer expiryPolicyMinutes;
@Min(0)
@Max(200)
private Integer shiftingPolicyThreshold;
@Min(600000)
@Max(750000)
private Integer maximumNumberOfKeysPerBundle;
@Pattern(regexp = FILE_NAME_REGEX)
private String outputFileName;
@Pattern(regexp = FILE_NAME_REGEX)
private String outputFileNameV2;
private Boolean includeIncompleteDays;
private Boolean includeIncompleteHours;
private String euPackageName;
private Boolean applyPoliciesForAllCountries;
private String cardIdSequence;
private TekExport tekExport;
private Signature signature;
private Api api;
private ObjectStore objectStore;
private List<AppFeature> appFeatures;
@NotEmpty
private String[] supportedCountries;
private AppVersions appVersions;
private AppConfigParameters appConfigParameters;
private StatisticsConfig statistics;
private QrCodePosterTemplate iosQrCodePosterTemplate;
private QrCodePosterTemplate androidQrCodePosterTemplate;
private PresenceTracingParameters presenceTracingParameters;
private DigitalGreenCertificate digitalGreenCertificate;
private Integer connectionPoolSize;
private String defaultArchiveName;
private Integer minimumTrlValueAllowed;
private Integer daysToPublish;
private DccRevocation dccRevocation;
@Min(0)
@Max(100)
private int infectionThreshold;
public QrCodePosterTemplate getAndroidQrCodePosterTemplate() {
return androidQrCodePosterTemplate;
}
public Api getApi() {
return api;
}
public AppConfigParameters getAppConfigParameters() {
return appConfigParameters;
}
public List<AppFeature> getAppFeatures() {
return appFeatures;
}
/**
* Get app features as list of protobuf objects.
*
* @return list of {@link app.coronawarn.server.common.protocols.internal.AppFeature}
*/
public List<app.coronawarn.server.common.protocols.internal.AppFeature> getAppFeaturesProto() {
return getAppFeatures().stream()
.map(appFeature -> app.coronawarn.server.common.protocols.internal.AppFeature.newBuilder()
.setLabel(appFeature.getLabel())
.setValue(appFeature.getValue()).build())
.collect(Collectors.toList());
}
public Boolean getApplyPoliciesForAllCountries() {
return applyPoliciesForAllCountries;
}
public AppVersions getAppVersions() {
return appVersions;
}
public String getCardIdSequence() {
return cardIdSequence;
}
public Integer getConnectionPoolSize() {
return connectionPoolSize;
}
public Integer getDaysToPublish() {
return daysToPublish == null ? retentionDays : daysToPublish;
}
public DccRevocation getDccRevocation() {
return dccRevocation;
}
public String getDefaultArchiveName() {
return defaultArchiveName;
}
public DigitalGreenCertificate getDigitalGreenCertificate() {
return digitalGreenCertificate;
}
public String getEuPackageName() {
return euPackageName;
}
public Integer getExpiryPolicyMinutes() {
return expiryPolicyMinutes;
}
public Boolean getIncludeIncompleteDays() {
return includeIncompleteDays;
}
public Boolean getIncludeIncompleteHours() {
return includeIncompleteHours;
}
public int getInfectionThreshold() {
return infectionThreshold;
}
public QrCodePosterTemplate getIosQrCodePosterTemplate() {
return iosQrCodePosterTemplate;
}
public Integer getMaximumNumberOfKeysPerBundle() {
return maximumNumberOfKeysPerBundle;
}
public Integer getMinimumTrlValueAllowed() {
return minimumTrlValueAllowed;
}
public ObjectStore getObjectStore() {
return objectStore;
}
public String getOutputFileName() {
return outputFileName;
}
public String getOutputFileNameV2() {
return outputFileNameV2;
}
public Paths getPaths() {
return paths;
}
public PresenceTracingParameters getPresenceTracingParameters() {
return presenceTracingParameters;
}
public Integer getRetentionDays() {
return retentionDays;
}
public Integer getShiftingPolicyThreshold() {
return shiftingPolicyThreshold;
}
public Signature getSignature() {
return signature;
}
public int getSrsTypeStatisticsDays() {
return srsTypeStatisticsDays;
}
public StatisticsConfig getStatistics() {
return statistics;
}
public String[] getSupportedCountries() {
return supportedCountries;
}
public TekExport getTekExport() {
return tekExport;
}
public TestData getTestData() {
return testData;
}
public void setAndroidQrCodePosterTemplate(final QrCodePosterTemplate androidQrCodePosterTemplate) {
this.androidQrCodePosterTemplate = androidQrCodePosterTemplate;
}
public void setApi(final Api api) {
this.api = api;
}
public void setAppConfigParameters(final AppConfigParameters appConfigParameters) {
this.appConfigParameters = appConfigParameters;
}
public void setAppFeatures(final List<AppFeature> appFeatures) {
this.appFeatures = appFeatures;
}
public void setApplyPoliciesForAllCountries(final Boolean applyPoliciesForAllCountries) {
this.applyPoliciesForAllCountries = applyPoliciesForAllCountries;
}
public void setAppVersions(final AppVersions appVersions) {
this.appVersions = appVersions;
}
public void setCardIdSequence(final String cardIdSequence) {
this.cardIdSequence = cardIdSequence;
}
public void setConnectionPoolSize(final Integer connectionPoolSize) {
this.connectionPoolSize = connectionPoolSize;
}
public void setDaysToPublish(final Integer daysToPublish) {
this.daysToPublish = daysToPublish;
}
public void setDccRevocation(final DccRevocation dccRevocation) {
this.dccRevocation = dccRevocation;
}
public void setDefaultArchiveName(final String defaultArchiveName) {
this.defaultArchiveName = defaultArchiveName;
}
public void setDigitalGreenCertificate(final DigitalGreenCertificate digitalGreenCertificate) {
this.digitalGreenCertificate = digitalGreenCertificate;
}
public void setEuPackageName(final String euPackageName) {
this.euPackageName = euPackageName;
}
public void setExpiryPolicyMinutes(final Integer expiryPolicyMinutes) {
this.expiryPolicyMinutes = expiryPolicyMinutes;
}
public void setIncludeIncompleteDays(final Boolean includeIncompleteDays) {
this.includeIncompleteDays = includeIncompleteDays;
}
public void setIncludeIncompleteHours(final Boolean includeIncompleteHours) {
this.includeIncompleteHours = includeIncompleteHours;
}
public void setInfectionThreshold(final int infectionThreshold) {
this.infectionThreshold = infectionThreshold;
}
public void setIosQrCodePosterTemplate(final QrCodePosterTemplate iosQrCodePosterTemplate) {
this.iosQrCodePosterTemplate = iosQrCodePosterTemplate;
}
public void setMaximumNumberOfKeysPerBundle(final Integer maximumNumberOfKeysPerBundle) {
this.maximumNumberOfKeysPerBundle = maximumNumberOfKeysPerBundle;
}
public void setMinimumTrlValueAllowed(final Integer minimumTrlValueAllowed) {
this.minimumTrlValueAllowed = minimumTrlValueAllowed;
}
public void setObjectStore(
final ObjectStore objectStore) {
this.objectStore = objectStore;
}
public void setOutputFileName(final String outputFileName) {
this.outputFileName = outputFileName;
}
public void setOutputFileNameV2(final String outputFileNameV2) {
this.outputFileNameV2 = outputFileNameV2;
}
public void setPaths(final Paths paths) {
this.paths = paths;
}
public void setPresenceTracingParameters(
final PresenceTracingParameters presenceTracingParameters) {
this.presenceTracingParameters = presenceTracingParameters;
}
public void setRetentionDays(final Integer retentionDays) {
this.retentionDays = retentionDays;
}
public void setShiftingPolicyThreshold(final Integer shiftingPolicyThreshold) {
this.shiftingPolicyThreshold = shiftingPolicyThreshold;
}
public void setSignature(final Signature signature) {
this.signature = signature;
}
public void setSrsTypeStatisticsDays(final int srsTypeStatisticsDays) {
this.srsTypeStatisticsDays = srsTypeStatisticsDays;
}
public void setStatistics(final StatisticsConfig statistics) {
this.statistics = statistics;
}
public void setSupportedCountries(final String[] supportedCountries) {
this.supportedCountries = supportedCountries;
}
public void setTekExport(final TekExport tekExport) {
this.tekExport = tekExport;
}
public void setTestData(final TestData testData) {
this.testData = testData;
}
}
| 64,671 | 0.725487 | 0.720648 | 2,224 | 28.078688 | 28.463842 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.307104 | false | false | 9 |
70e5d6b7370400e74e2b7e41c007f103afbce402 | 25,675,314,506,368 | 764d198a5d3329dc5da9de4dc44344300f07de35 | /src/main/java/com/ruisi/ext/engine/view/context/form/CheckBoxContext.java | 0ba951f9602665de0e91cde1b2a72e5afdc17196 | [] | no_license | DarrickAZ/rsbi | https://github.com/DarrickAZ/rsbi | a403cd93b034dde11370026e80e68e31d0670c7f | c82cd481d86e0f2ba4fd08f53b824b60bfd3170f | refs/heads/master | 2020-04-26T17:32:35.928000 | 2019-03-14T06:35:31 | 2019-03-14T06:35:31 | 173,717,187 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | //
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.ruisi.ext.engine.view.context.form;
import com.ruisi.ext.engine.view.context.face.MoreValue;
import com.ruisi.ext.engine.view.context.face.OptionsLoader;
import com.ruisi.ext.engine.view.context.face.Template;
public interface CheckBoxContext extends MoreValue, OptionsLoader, Template, InputField {
String getDataId();
void setDataId(String var1);
void setTarget(String[] var1);
String[] getTarget();
String getRefDsource();
void setRefDsource(String var1);
Boolean getShowSpan();
void setShowSpan(Boolean var1);
String getCheckboxStyle();
void setCheckboxStyle(String var1);
}
| UTF-8 | Java | 748 | java | CheckBoxContext.java | Java | [] | null | [] | //
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.ruisi.ext.engine.view.context.form;
import com.ruisi.ext.engine.view.context.face.MoreValue;
import com.ruisi.ext.engine.view.context.face.OptionsLoader;
import com.ruisi.ext.engine.view.context.face.Template;
public interface CheckBoxContext extends MoreValue, OptionsLoader, Template, InputField {
String getDataId();
void setDataId(String var1);
void setTarget(String[] var1);
String[] getTarget();
String getRefDsource();
void setRefDsource(String var1);
Boolean getShowSpan();
void setShowSpan(Boolean var1);
String getCheckboxStyle();
void setCheckboxStyle(String var1);
}
| 748 | 0.740642 | 0.733957 | 32 | 22.375 | 24.063393 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.53125 | false | false | 9 |
2b1b880b8414361088fff66715834713fe3a9494 | 12,893,491,861,767 | 2b8ec3d51fbcb61de5db4553fba3028359db0eed | /app/src/test/java/com/example/jenson/cs2340_team24_project/SearchDonationResultActivityTest.java | 43dd926eac5f8032720a5b169c1d68232e1039a6 | [] | no_license | xyang383/Donation-Tracker | https://github.com/xyang383/Donation-Tracker | 3d201cadc795f0f64a3ed32fabf9f5d0de19ea4a | 7d28d4735da541828296cf8b467539fd72604b5e | refs/heads/master | 2020-04-15T18:35:18.706000 | 2019-01-09T18:38:47 | 2019-01-09T18:38:47 | 164,917,606 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.jenson.cs2340_team24_project;
import com.example.jenson.cs2340_team24_project.UI.Controllers.SearchDonationResultActivity;
import org.junit.Test;
import java.util.ArrayList;
import static org.junit.Assert.*;
public class SearchDonationResultActivityTest {
private final ArrayList<String> donations = new ArrayList<>();
private final ArrayList<String> result = new ArrayList<>();
@Test
public void fuzzySearch() {
String name = "afd";
SearchDonationResultActivity s = new SearchDonationResultActivity();
result.add("AFDtest333");
result.add("AFDtest111");
result.add("afdtest3");
result.add("afdtest4");
result.add("afdtest5");
donations.add("AFDtest333");
donations.add("AFDtest111");
donations.add("afdtest3");
donations.add("afdtest4");
donations.add("afdtest5");
donations.add("sample1");
donations.add("sample2");
donations.add("sample3");
donations.add("sample4");
s.fuzzySearch(name, donations);
for (int i = 0; i < 5; i++) {
assertEquals(result.get(i), donations.get(i));
}
}
} | UTF-8 | Java | 1,197 | java | SearchDonationResultActivityTest.java | Java | [
{
"context": "package com.example.jenson.cs2340_team24_project;\n\nimport com.example.jenson",
"end": 26,
"score": 0.9120271801948547,
"start": 23,
"tag": "USERNAME",
"value": "son"
},
{
"context": "jenson.cs2340_team24_project;\n\nimport com.example.jenson.cs2340_team24_project.UI.C... | null | [] | package com.example.jenson.cs2340_team24_project;
import com.example.jenson.cs2340_team24_project.UI.Controllers.SearchDonationResultActivity;
import org.junit.Test;
import java.util.ArrayList;
import static org.junit.Assert.*;
public class SearchDonationResultActivityTest {
private final ArrayList<String> donations = new ArrayList<>();
private final ArrayList<String> result = new ArrayList<>();
@Test
public void fuzzySearch() {
String name = "afd";
SearchDonationResultActivity s = new SearchDonationResultActivity();
result.add("AFDtest333");
result.add("AFDtest111");
result.add("afdtest3");
result.add("afdtest4");
result.add("afdtest5");
donations.add("AFDtest333");
donations.add("AFDtest111");
donations.add("afdtest3");
donations.add("afdtest4");
donations.add("afdtest5");
donations.add("sample1");
donations.add("sample2");
donations.add("sample3");
donations.add("sample4");
s.fuzzySearch(name, donations);
for (int i = 0; i < 5; i++) {
assertEquals(result.get(i), donations.get(i));
}
}
} | 1,197 | 0.639098 | 0.609023 | 41 | 28.219513 | 22.355783 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.707317 | false | false | 9 |
857e98fcf60a28d1f1d12e56e348431b8c070dd1 | 27,590,869,927,245 | 2d51c9bcbc8f667599f829703aab00dc155515ee | /src/main/java/pl/pietrzyk/parking/application/DriverFacade.java | 9db8169bcd3b983b7235a6f923a032d6f5ad5a09 | [] | no_license | pietrzykp/parking | https://github.com/pietrzykp/parking | 67472f8c86f15072eef03b8b08975d45e851356a | bb87142375d41b7fa69003dd544552dba7c7cff6 | refs/heads/master | 2021-09-13T03:55:26.062000 | 2018-04-24T17:52:45 | 2018-04-24T17:52:45 | 109,173,374 | 0 | 0 | null | false | 2018-04-24T17:52:47 | 2017-11-01T19:17:30 | 2017-11-02T11:14:48 | 2018-04-24T17:52:47 | 27 | 0 | 0 | 0 | Java | false | null | package pl.pietrzyk.parking.application;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import pl.pietrzyk.parking.application.dto.ParkingMeterForm;
import pl.pietrzyk.parking.application.dto.PaymentAmount;
import pl.pietrzyk.parking.application.exception.DriverNotFoundException;
import pl.pietrzyk.parking.application.exception.ParkingMeterNotFoundException;
import pl.pietrzyk.parking.application.exception.ParkingSlotStateException;
import pl.pietrzyk.parking.domain.driver.Driver;
import pl.pietrzyk.parking.domain.driver.DriverRepository;
import pl.pietrzyk.parking.domain.history.History;
import pl.pietrzyk.parking.domain.history.HistoryRepository;
import pl.pietrzyk.parking.domain.history.PaymentSummary;
import pl.pietrzyk.parking.domain.parkingmeter.ParkingMeter;
import pl.pietrzyk.parking.domain.parkingmeter.ParkingMeterRepository;
import pl.pietrzyk.parking.domain.rateplan.RatePlan;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
@Component
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class DriverFacade {
private final DriverRepository driverRepository;
private final HistoryRepository historyRepository;
private final ParkingMeterRepository parkingMeterRepository;
private final static int MIN_STARTED_HOURS = 1;
@Transactional(isolation = Isolation.SERIALIZABLE, propagation = Propagation.REQUIRES_NEW)
public void startParkingMeter(ParkingMeterForm parkingMeterForm) {
Driver driver = driverRepository.findById(parkingMeterForm.getDriverId()).orElseThrow(DriverNotFoundException::new);
ParkingMeter parkingMeter = parkingMeterRepository.findById(parkingMeterForm.getParkingMeterId())
.orElseThrow(ParkingMeterNotFoundException::new);
if(parkingMeter.isTaken()) {
throw ParkingSlotStateException.slotTakenException();
}
parkingMeter.setDriver(driver);
parkingMeter.setStartDateTime(LocalDateTime.now());
parkingMeter.setTaken(true);
parkingMeterRepository.save(parkingMeter);
}
@Transactional(isolation = Isolation.SERIALIZABLE, propagation = Propagation.REQUIRES_NEW)
public PaymentAmount stopParkingMeter(ParkingMeterForm parkingMeterForm) {
Driver driver = driverRepository.findById(parkingMeterForm.getDriverId()).orElseThrow(DriverNotFoundException::new);
ParkingMeter parkingMeter = parkingMeterRepository.findById(parkingMeterForm.getParkingMeterId())
.orElseThrow(ParkingMeterNotFoundException::new);
if(!parkingMeter.isTaken()) {
throw ParkingSlotStateException.slotEmptyException();
}
if(!driver.equals(parkingMeter.getDriver())) {
throw ParkingSlotStateException.driverNotMatchingSlotException();
}
LocalDateTime parkingEndTime = LocalDateTime.now();
BigDecimal payment = calculatePayment(parkingMeter.getStartDateTime(), parkingEndTime, driver.getRatePlan());
historyRepository.save(History.builder()
.currency(driver.getRatePlan().getCurrency())
.driver(driver)
.startDateTime(parkingMeter.getStartDateTime())
.endDateTime(parkingEndTime)
.paymentAmount(payment).build());
parkingMeter.setEndDateTime(parkingEndTime);
parkingMeterRepository.save(parkingMeter);
return new PaymentAmount(payment);
}
public List<PaymentSummary> getHistorySummary(Long driverId) {
Driver driver = driverRepository.findById(driverId).orElseThrow(DriverNotFoundException::new);
return historyRepository.getDriverPaymentSummary(driver);
}
BigDecimal calculatePayment(LocalDateTime start, LocalDateTime end, RatePlan ratePlan) {
long startedHours = Duration.between(start, end).toHours() + 1;
if(startedHours < MIN_STARTED_HOURS)
return new BigDecimal(0);
BigDecimal paymentAmount = ratePlan.getFirstHourRate();
BigDecimal stepsAmount = new BigDecimal(startedHours - 1);
if(stepsAmount.intValue() > 0) {
BigDecimal paymentAfterFirsthour = countSumOfGeometricSeries(ratePlan.getSecondHourRate(),
ratePlan.getAfterThirdHourMultiplier(), stepsAmount);
paymentAmount = paymentAmount.add(paymentAfterFirsthour);
}
return paymentAmount.setScale(2, RoundingMode.HALF_UP);
}
/**
* Counts sum of geometric series, according to formula:
*
* a(1-r^n) / (1-r), where a = base, r = common ratio, n = number of steps
*/
private BigDecimal countSumOfGeometricSeries(BigDecimal base, BigDecimal commonRatio, BigDecimal numberOfSteps) {
BigDecimal one = BigDecimal.ONE;
BigDecimal numerator = base.multiply(one.subtract(commonRatio.pow(numberOfSteps.intValue())));
BigDecimal denominator = BigDecimal.ONE.subtract(commonRatio);
return numerator.divide(denominator);
}
}
| UTF-8 | Java | 5,290 | java | DriverFacade.java | Java | [] | null | [] | package pl.pietrzyk.parking.application;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import pl.pietrzyk.parking.application.dto.ParkingMeterForm;
import pl.pietrzyk.parking.application.dto.PaymentAmount;
import pl.pietrzyk.parking.application.exception.DriverNotFoundException;
import pl.pietrzyk.parking.application.exception.ParkingMeterNotFoundException;
import pl.pietrzyk.parking.application.exception.ParkingSlotStateException;
import pl.pietrzyk.parking.domain.driver.Driver;
import pl.pietrzyk.parking.domain.driver.DriverRepository;
import pl.pietrzyk.parking.domain.history.History;
import pl.pietrzyk.parking.domain.history.HistoryRepository;
import pl.pietrzyk.parking.domain.history.PaymentSummary;
import pl.pietrzyk.parking.domain.parkingmeter.ParkingMeter;
import pl.pietrzyk.parking.domain.parkingmeter.ParkingMeterRepository;
import pl.pietrzyk.parking.domain.rateplan.RatePlan;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
@Component
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class DriverFacade {
private final DriverRepository driverRepository;
private final HistoryRepository historyRepository;
private final ParkingMeterRepository parkingMeterRepository;
private final static int MIN_STARTED_HOURS = 1;
@Transactional(isolation = Isolation.SERIALIZABLE, propagation = Propagation.REQUIRES_NEW)
public void startParkingMeter(ParkingMeterForm parkingMeterForm) {
Driver driver = driverRepository.findById(parkingMeterForm.getDriverId()).orElseThrow(DriverNotFoundException::new);
ParkingMeter parkingMeter = parkingMeterRepository.findById(parkingMeterForm.getParkingMeterId())
.orElseThrow(ParkingMeterNotFoundException::new);
if(parkingMeter.isTaken()) {
throw ParkingSlotStateException.slotTakenException();
}
parkingMeter.setDriver(driver);
parkingMeter.setStartDateTime(LocalDateTime.now());
parkingMeter.setTaken(true);
parkingMeterRepository.save(parkingMeter);
}
@Transactional(isolation = Isolation.SERIALIZABLE, propagation = Propagation.REQUIRES_NEW)
public PaymentAmount stopParkingMeter(ParkingMeterForm parkingMeterForm) {
Driver driver = driverRepository.findById(parkingMeterForm.getDriverId()).orElseThrow(DriverNotFoundException::new);
ParkingMeter parkingMeter = parkingMeterRepository.findById(parkingMeterForm.getParkingMeterId())
.orElseThrow(ParkingMeterNotFoundException::new);
if(!parkingMeter.isTaken()) {
throw ParkingSlotStateException.slotEmptyException();
}
if(!driver.equals(parkingMeter.getDriver())) {
throw ParkingSlotStateException.driverNotMatchingSlotException();
}
LocalDateTime parkingEndTime = LocalDateTime.now();
BigDecimal payment = calculatePayment(parkingMeter.getStartDateTime(), parkingEndTime, driver.getRatePlan());
historyRepository.save(History.builder()
.currency(driver.getRatePlan().getCurrency())
.driver(driver)
.startDateTime(parkingMeter.getStartDateTime())
.endDateTime(parkingEndTime)
.paymentAmount(payment).build());
parkingMeter.setEndDateTime(parkingEndTime);
parkingMeterRepository.save(parkingMeter);
return new PaymentAmount(payment);
}
public List<PaymentSummary> getHistorySummary(Long driverId) {
Driver driver = driverRepository.findById(driverId).orElseThrow(DriverNotFoundException::new);
return historyRepository.getDriverPaymentSummary(driver);
}
BigDecimal calculatePayment(LocalDateTime start, LocalDateTime end, RatePlan ratePlan) {
long startedHours = Duration.between(start, end).toHours() + 1;
if(startedHours < MIN_STARTED_HOURS)
return new BigDecimal(0);
BigDecimal paymentAmount = ratePlan.getFirstHourRate();
BigDecimal stepsAmount = new BigDecimal(startedHours - 1);
if(stepsAmount.intValue() > 0) {
BigDecimal paymentAfterFirsthour = countSumOfGeometricSeries(ratePlan.getSecondHourRate(),
ratePlan.getAfterThirdHourMultiplier(), stepsAmount);
paymentAmount = paymentAmount.add(paymentAfterFirsthour);
}
return paymentAmount.setScale(2, RoundingMode.HALF_UP);
}
/**
* Counts sum of geometric series, according to formula:
*
* a(1-r^n) / (1-r), where a = base, r = common ratio, n = number of steps
*/
private BigDecimal countSumOfGeometricSeries(BigDecimal base, BigDecimal commonRatio, BigDecimal numberOfSteps) {
BigDecimal one = BigDecimal.ONE;
BigDecimal numerator = base.multiply(one.subtract(commonRatio.pow(numberOfSteps.intValue())));
BigDecimal denominator = BigDecimal.ONE.subtract(commonRatio);
return numerator.divide(denominator);
}
}
| 5,290 | 0.748582 | 0.74707 | 124 | 41.661289 | 33.7906 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.596774 | false | false | 9 |
8b302709c1fd4f34d86df34b4170b01147c6f494 | 19,267,223,294,991 | d879182690848ba747620b2e216c0c9a34cfd649 | /app/src/main/java/com/apuritobokuto/healmane/TimerReceiver.java | 4d8771542a887eeecde8ea61fdf0298959acd91e | [] | no_license | apuritobokuto/healmane | https://github.com/apuritobokuto/healmane | 182b1e1e8fc291a617bfef571058ac43174833bc | 5e67fc8353e8550b57d41ed3b0458f099f154769 | refs/heads/master | 2020-06-11T05:07:36.950000 | 2017-01-28T17:51:17 | 2017-01-28T17:51:17 | 75,898,128 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.apuritobokuto.healmane;
/**
* Created by rusiddo1011 on 2017/01/20.
*/
//package jp.classmethod.android.sample.dialogonhome;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class TimerReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent data) {
Intent intent = new Intent(context, AlertDialogActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
try {
pendingIntent.send();
} catch (PendingIntent.CanceledException e) {
e.printStackTrace();
}
}
} | UTF-8 | Java | 724 | java | TimerReceiver.java | Java | [
{
"context": "age com.apuritobokuto.healmane;\n\n/**\n * Created by rusiddo1011 on 2017/01/20.\n */\n\n//package jp.classmethod.andr",
"end": 66,
"score": 0.9994680881500244,
"start": 55,
"tag": "USERNAME",
"value": "rusiddo1011"
}
] | null | [] | package com.apuritobokuto.healmane;
/**
* Created by rusiddo1011 on 2017/01/20.
*/
//package jp.classmethod.android.sample.dialogonhome;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class TimerReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent data) {
Intent intent = new Intent(context, AlertDialogActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
try {
pendingIntent.send();
} catch (PendingIntent.CanceledException e) {
e.printStackTrace();
}
}
} | 724 | 0.708564 | 0.689227 | 26 | 26.884615 | 24.795048 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.576923 | false | false | 9 |
e8922b03946b638e77a9dd0c393bdbc559341b48 | 18,408,229,847,034 | 876b5420afb4ecd15f875058d9f9b1d4e39dbcb3 | /smartcheck-android-sdk-develop/smartcheck-android-sdk-develop/app/src/main/java/com/alltrustnetworks/smartcheck/RegulaActivity.java | 89bea036d0094d7c94098d217291d0971053d790 | [] | no_license | phatLam/Navigation | https://github.com/phatLam/Navigation | 33d706347bc42a902c98dd7d85888babec390f28 | e42de27255640f0c3f5757e0fa1fac763d17921b | refs/heads/master | 2020-07-26T07:17:07.278000 | 2020-04-25T09:55:52 | 2020-04-25T09:57:13 | 208,575,513 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.alltrustnetworks.smartcheck;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.alltrustnetworks.smartcheck.models.CheckType;
import com.alltrustnetworks.smartcheck.models.DocId;
import com.alltrustnetworks.smartcheck.util.Util;
import com.regula.documentreader.api.DocumentReader;
import com.regula.documentreader.api.enums.DocReaderAction;
import com.regula.documentreader.api.enums.DocReaderFrame;
import com.regula.documentreader.api.enums.LCID;
import com.regula.documentreader.api.enums.eGraphicFieldType;
import com.regula.documentreader.api.enums.eRPRM_ResultType;
import com.regula.documentreader.api.enums.eVisualFieldType;
import com.regula.documentreader.api.results.DocumentReaderDocumentType;
import com.regula.documentreader.api.results.DocumentReaderResults;
import com.regula.documentreader.api.results.DocumentReaderTextField;
import org.parceler.Parcels;
import java.io.ByteArrayOutputStream;
public class RegulaActivity extends AppCompatActivity {
private DocId dl;
private boolean firstPage = true;
private MediaPlayer mPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_regula);
mPlayer = MediaPlayer.create(this, R.raw.pictureshutter);
mPlayer.setOnCompletionListener(mediaPlayer -> {
mediaPlayer.stop();
mediaPlayer.release();
});
if (savedInstanceState == null) {
dl = new DocId();
if (DocumentReader.Instance().getDocumentReaderIsReady()) {
try {
DocumentReader.Instance().showScanner(onFrontComplete);
firstPage = true;
updateStatus();
}catch (Exception e) {
Log.e("SmartCheck", "exception 2");
e.printStackTrace();
Toast.makeText(RegulaActivity.this, "Scanning was error", Toast.LENGTH_LONG).show();
DocumentReader.Instance().stopScanner();
setResult(RESULT_CANCELED, new Intent());
finish();
}
}
else{
reInitDocumentReader();
}
}
}
private void reInitDocumentReader() {
RegulaApi.getInstance().initDocumentReader(this, () -> {
try{
DocumentReader.Instance().showScanner(onFrontComplete);
firstPage = true;
updateStatus();
}catch (Exception e) {
e.printStackTrace();
Toast.makeText(RegulaActivity.this, "Scanning was error", Toast.LENGTH_LONG).show();
DocumentReader.Instance().stopScanner();
setResult(RESULT_CANCELED, new Intent());
finish();
}
});
}
//DocumentReader processing callback
private static final String TAG = "RegularActivity";
private DocumentReader.DocumentReaderCompletion onFrontComplete = new DocumentReader.DocumentReaderCompletion() {
@Override
public void onCompleted(int action, DocumentReaderResults results, String error) {
try {
//processing is finished, all results are ready
if (action == DocReaderAction.COMPLETE) {
// Log.i("SmartCheck", " Scan Passport COMPLETE = " + results.documentType.name);
setPlayAudio();
processFrontResults(results);
Intent intent = new Intent();
intent.putExtra(SmartCheckActivity.DOC_ID, Parcels.wrap(dl));
setResult(RESULT_OK, intent);
finish();
} else {
//something happened before all results were ready
if (action == DocReaderAction.CANCEL) {
DocumentReader.Instance().stopScanner();
Toast.makeText(RegulaActivity.this, "Scanning was cancelled", Toast.LENGTH_LONG).show();
Intent i = new Intent();
setResult(RESULT_CANCELED, i);
finish();
} else if (action == DocReaderAction.ERROR) {
DocumentReader.Instance().stopScanner();
Toast.makeText(RegulaActivity.this, "Error:" + error, Toast.LENGTH_LONG).show();
Intent i = new Intent();
setResult(RESULT_CANCELED, i);
finish();
} else if (action == DocReaderAction.MORE_PAGES_AVAILABLE) {
// Log.i("SmartCheck", " Scan Passport successfully = " + results.documentType.dType);
// Log.i("SmartCheck", " Scan Passport successfully = " + results.documentType.name);
setPlayAudio();
// if (results.documentType.dType == 12) { // ID 1998
// returnResult(results);
// }
// if (results.documentType.. == 11 || results.documentType.name.contains("Passport")) {//ePassport
// returnResult(results);
// }
firstPage = false;
updateStatus();
}
if (action == DocReaderAction.PROCESS) {
if (results != null) {
if (results.jsonResult != null && results.documentPosition != null && results.jsonResult.results.size() > 0) {
DocumentReader.Instance().customization().setStatus("Your ID is being scanned. \nPlease hold it within the frame");
} else {
updateStatus();
}
}
}
}
} catch (Exception e) {
Log.e("SmartCheck", "exception 1");
e.printStackTrace();
Toast.makeText(RegulaActivity.this, "Scanning was error", Toast.LENGTH_LONG).show();
DocumentReader.Instance().stopScanner();
RegulaActivity.this.setResult(RESULT_CANCELED, new Intent());
RegulaActivity.this.finish();
}
}
};
private void returnResult(DocumentReaderResults results) {
DocumentReader.Instance().stopScanner();
processFrontResults(results);
Intent intent = new Intent();
intent.putExtra(SmartCheckActivity.DOC_ID, Parcels.wrap(dl));
setResult(RESULT_OK, intent);
finish();
}
private void updateStatus() {
if (firstPage) {
DocumentReader.Instance().customization().setStatus("Please scan the front side of your ID.\nMake sure it is inside the white frame");
} else {
DocumentReader.Instance().customization().setStatus("Please scan the back side of your ID.\nMake sure it is inside the white frame");
}
}
private AlertDialog showDialog(String msg) {
AlertDialog.Builder dialog = new AlertDialog.Builder(RegulaActivity.this);
View dialogView = getLayoutInflater().inflate(R.layout.simple_dialog, null);
dialog.setTitle(msg);
dialog.setView(dialogView);
dialog.setCancelable(false);
return dialog.show();
}
//show received results on the UI
private void processFrontResults(DocumentReaderResults results) {
if (results != null) {
Log.i("SmartCheck", "found results");
try {
String middleName = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_MIDDLE_NAME), " ");
dl.setMiddleName(middleName);
String firstName = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_GIVEN_NAMES), " ");
dl.setFirstName(firstName);
String lastName = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_SURNAME), " ");
dl.setLastName(lastName);
String address = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_ADDRESS_STREET), " ");
dl.setAddress(address);
String city = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_ADDRESS_CITY), " ");
dl.setCity(city);
String zipCode = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_ADDRESS_POSTAL_CODE), " ");
try{
//sometimes zipcode return "...;;"
if (zipCode != null) {
Double.parseDouble(zipCode);
dl.setZipcode(zipCode);
}
}catch (NumberFormatException e){
dl.setZipcode("");
}
String state = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_ADDRESS_JURISDICTION_CODE), " ");
dl.setState(state.toUpperCase());
// String birthDate = Util.convertRegulaDate(results.getTextFieldValueByType(eVisualFieldType.FT_DATE_OF_BIRTH));
String birthDate = results.getTextFieldValueByType(eVisualFieldType.FT_DATE_OF_BIRTH);
dl.setBirthDate(birthDate);
String placeOfBirth = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_PLACE_OF_BIRTH), " ");
dl.setPlaceOfBirth(placeOfBirth);
String issuer = results.getTextFieldValueByType(eVisualFieldType.FT_ADDRESS_JURISDICTION_CODE);
dl.setIssuer(issuer);
String IdNumber = results.getTextFieldValueByType(eVisualFieldType.FT_DOCUMENT_NUMBER);
dl.setIdNumber(IdNumber);
String idPassport = results.getTextFieldValueByType(eVisualFieldType.FT_PASSPORT_NUMBER);
if (idPassport != null && !idPassport.isEmpty()) {
dl.setIdNumber(idPassport);
}
// String issueDate = Util.convertRegulaDate(results.getTextFieldValueByType(eVisualFieldType.FT_DATE_OF_ISSUE));
String issueDate = results.getTextFieldValueByType(eVisualFieldType.FT_DATE_OF_ISSUE);
dl.setIssueDate(issueDate);
// String expirationDate = Util.convertRegulaDate(results.getTextFieldValueByType(eVisualFieldType.FT_DATE_OF_EXPIRY));
String expirationDate = results.getTextFieldValueByType(eVisualFieldType.FT_DATE_OF_EXPIRY);
dl.setExpirationDate(expirationDate);
String nationality = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_NATIONALITY), " ");
dl.setNationality(nationality);
String authority = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_AUTHORITY), " ");
dl.setAuthority(authority);
String gender = results.getTextFieldValueByType(eVisualFieldType.FT_SEX);
if (gender != null) {
switch (gender) {
case "M":
dl.setGender("Male");
break;
case "F":
dl.setGender("Female");
break;
default:
dl.setGender("Unknown");
break;
}
}
else{
dl.setGender("Unknown");
}
if(results.textResult != null && results.textResult.fields != null) {
for (DocumentReaderTextField textField : results.textResult.fields) {
String value = results.getTextFieldValueByType(textField.fieldType, textField.lcid);
Log.d("MainActivity", "textfield = "+ textField.fieldName+ value + "\n");
}
}
// barcode
// String firstNameBc = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_GIVEN_NAMES, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA), " ");
// if (firstNameBc != null && !firstNameBc.isEmpty()) {
// dl.setFirstName(firstNameBc);
// }
//
// String lastNameBc = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_SURNAME, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA), " ");
// if (lastNameBc != null && !lastNameBc.isEmpty()) {
// dl.setLastName(lastNameBc);
// }
//
// String addressBc = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_ADDRESS_STREET, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA), " ");
// if (addressBc != null && !addressBc.isEmpty()) {
// dl.setAddress(addressBc);
// }
//
// String cityBc = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_ADDRESS_CITY, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA), " ");
// if (cityBc != null && !cityBc.isEmpty()) {
// dl.setCity(cityBc);
// }
//
// String zipCodeBc = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_ADDRESS_POSTAL_CODE, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA), " ");
// if (zipCodeBc != null && !zipCodeBc.isEmpty()) {
// try{
// Double.parseDouble(zipCodeBc);
// dl.setZipcode(zipCodeBc);
// }catch (NumberFormatException e){
// dl.setZipcode("");
// }
//
// }
//
// String stateBc = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_ADDRESS_JURISDICTION_CODE, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA), " ");
// if (stateBc != null && !stateBc.isEmpty()) {
// dl.setState(stateBc.toUpperCase());
// }
//
// String birthDateBc = Util.convertRegulaDate(results.getTextFieldValueByType(eVisualFieldType.FT_DATE_OF_BIRTH, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA));
// if (birthDateBc != null && !birthDateBc.isEmpty()) {
// dl.setBirthDate(birthDateBc);
// }
//
// String placeOfBirthBc = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_PLACE_OF_BIRTH, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA), " ");
// if (placeOfBirthBc != null && !placeOfBirthBc.isEmpty()) {
// dl.setPlaceOfBirth(placeOfBirthBc);
// }
//
// String issuerBc = results.getTextFieldValueByType(eVisualFieldType.FT_ADDRESS_JURISDICTION_CODE, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA);
// if (issuerBc != null && !issuerBc.isEmpty()) {
// dl.setIssuer(issuerBc);
// }
//
// String idNumberBc = results.getTextFieldValueByType(eVisualFieldType.FT_DOCUMENT_NUMBER, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA);
// if (idNumberBc != null && !idNumberBc.isEmpty()) {
// dl.setIdNumber(idNumberBc);
// }
//
// String idPassportBc = results.getTextFieldValueByType(eVisualFieldType.FT_PASSPORT_NUMBER, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA);
// if (idPassportBc != null && !idPassportBc.isEmpty()) {
// dl.setIdNumber(idPassportBc);
// }
//
// String issueDateBc = Util.convertRegulaDate(results.getTextFieldValueByType(eVisualFieldType.FT_DATE_OF_ISSUE, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA));
// if (issueDateBc != null && !issueDateBc.isEmpty()) {
// dl.setIssueDate(issueDateBc);
// }
//
// String expirationDateBc = Util.convertRegulaDate(results.getTextFieldValueByType(eVisualFieldType.FT_DATE_OF_EXPIRY, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA));
// if (expirationDateBc != null && !expirationDateBc.isEmpty()) {
// dl.setExpirationDate(expirationDateBc);
// }
//
// String nationalityBc = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_NATIONALITY, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA), " ");
// if (nationalityBc != null && !nationalityBc.isEmpty()) {
// dl.setNationality(nationalityBc);
// }
//
// String authorityBc = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_AUTHORITY, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA), " ");
// if (authorityBc != null && !authorityBc.isEmpty()) {
// dl.setAuthority(authorityBc);
// }
// if (results.documentType != null) {
// if (results.documentType.dType == 12) {
// dl.setIdType("ID Card");
// } else if (results.documentType.name.toLowerCase().contains("passport")) {
// dl.setIssuer(results.getTextFieldValueByType(eVisualFieldType.FT_ISSUING_STATE_CODE));
// dl.setIdType("Passport");
// } else if (results.documentType.dType == 49) {
// dl.setIdType("Driver's License");
// }
//// else if (results.documentType.dType != 49 &&
//// (idPassport != null && idPassport.isEmpty()) || (idPassportBc != null && !idPassportBc.isEmpty())) {
//// if (results.documentType.name.toLowerCase().contains("states")) {
//// dl.setIdType("US Passport");
//// } else if (results.documentType.name.toLowerCase().contains("mexico")) {
//// dl.setIdType("Mexico Passport");
//// } else {
//// dl.setIdType("Passport");
//// }
//// }
// else {
// dl.setIdType("Other");
// }
// }
ByteArrayOutputStream stream;
Bitmap frontImage = results.getGraphicFieldImageByType(eGraphicFieldType.GF_DOCUMENT_IMAGE);
if (frontImage != null) {
stream = new ByteArrayOutputStream();
frontImage.compress(Bitmap.CompressFormat.JPEG, 70, stream);
DocId.frontProcessedImage = stream.toByteArray();
frontImage.recycle();
} else {
Log.i("SmartCheck", "front image not present");
}
// Bitmap rearImage = results.getGraphicFieldImageByType(eGraphicFieldType.GT_DOCUMENT_REAR);
//
// if (rearImage != null) {
// stream = new ByteArrayOutputStream();
// rearImage.compress(Bitmap.CompressFormat.JPEG, 70, stream);
// DocId.rearProcessedImage = stream.toByteArray();
// rearImage.recycle();
// } else {
// DocId.rearProcessedImage = null;
// Log.i("SmartCheck", "back image not present");
// }
dl.setStatus("success");
for (DocumentReaderTextField textField : results.textResult.fields) {
String value = results.getTextFieldValueByType(textField.fieldType, textField.lcid);
Log.d("MainActivity", "field type = " + textField.fieldType + "," + "field type name= " + textField.fieldName + "," + value + "\n");
}
} catch (Exception e) {
Log.i("SmartCheck", "error front");
Log.i("SmartCheck", e.getMessage());
dl.setStatus("error");
}
} else {
Log.i("SmartCheck", "error front");
dl.setStatus("error");
}
}
public void setPlayAudio() {
mPlayer = MediaPlayer.create(this, R.raw.pictureshutter);
mPlayer.start();
mPlayer.setLooping(false);
}
}
| UTF-8 | Java | 21,111 | java | RegulaActivity.java | Java | [] | null | [] | package com.alltrustnetworks.smartcheck;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.alltrustnetworks.smartcheck.models.CheckType;
import com.alltrustnetworks.smartcheck.models.DocId;
import com.alltrustnetworks.smartcheck.util.Util;
import com.regula.documentreader.api.DocumentReader;
import com.regula.documentreader.api.enums.DocReaderAction;
import com.regula.documentreader.api.enums.DocReaderFrame;
import com.regula.documentreader.api.enums.LCID;
import com.regula.documentreader.api.enums.eGraphicFieldType;
import com.regula.documentreader.api.enums.eRPRM_ResultType;
import com.regula.documentreader.api.enums.eVisualFieldType;
import com.regula.documentreader.api.results.DocumentReaderDocumentType;
import com.regula.documentreader.api.results.DocumentReaderResults;
import com.regula.documentreader.api.results.DocumentReaderTextField;
import org.parceler.Parcels;
import java.io.ByteArrayOutputStream;
public class RegulaActivity extends AppCompatActivity {
private DocId dl;
private boolean firstPage = true;
private MediaPlayer mPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_regula);
mPlayer = MediaPlayer.create(this, R.raw.pictureshutter);
mPlayer.setOnCompletionListener(mediaPlayer -> {
mediaPlayer.stop();
mediaPlayer.release();
});
if (savedInstanceState == null) {
dl = new DocId();
if (DocumentReader.Instance().getDocumentReaderIsReady()) {
try {
DocumentReader.Instance().showScanner(onFrontComplete);
firstPage = true;
updateStatus();
}catch (Exception e) {
Log.e("SmartCheck", "exception 2");
e.printStackTrace();
Toast.makeText(RegulaActivity.this, "Scanning was error", Toast.LENGTH_LONG).show();
DocumentReader.Instance().stopScanner();
setResult(RESULT_CANCELED, new Intent());
finish();
}
}
else{
reInitDocumentReader();
}
}
}
private void reInitDocumentReader() {
RegulaApi.getInstance().initDocumentReader(this, () -> {
try{
DocumentReader.Instance().showScanner(onFrontComplete);
firstPage = true;
updateStatus();
}catch (Exception e) {
e.printStackTrace();
Toast.makeText(RegulaActivity.this, "Scanning was error", Toast.LENGTH_LONG).show();
DocumentReader.Instance().stopScanner();
setResult(RESULT_CANCELED, new Intent());
finish();
}
});
}
//DocumentReader processing callback
private static final String TAG = "RegularActivity";
private DocumentReader.DocumentReaderCompletion onFrontComplete = new DocumentReader.DocumentReaderCompletion() {
@Override
public void onCompleted(int action, DocumentReaderResults results, String error) {
try {
//processing is finished, all results are ready
if (action == DocReaderAction.COMPLETE) {
// Log.i("SmartCheck", " Scan Passport COMPLETE = " + results.documentType.name);
setPlayAudio();
processFrontResults(results);
Intent intent = new Intent();
intent.putExtra(SmartCheckActivity.DOC_ID, Parcels.wrap(dl));
setResult(RESULT_OK, intent);
finish();
} else {
//something happened before all results were ready
if (action == DocReaderAction.CANCEL) {
DocumentReader.Instance().stopScanner();
Toast.makeText(RegulaActivity.this, "Scanning was cancelled", Toast.LENGTH_LONG).show();
Intent i = new Intent();
setResult(RESULT_CANCELED, i);
finish();
} else if (action == DocReaderAction.ERROR) {
DocumentReader.Instance().stopScanner();
Toast.makeText(RegulaActivity.this, "Error:" + error, Toast.LENGTH_LONG).show();
Intent i = new Intent();
setResult(RESULT_CANCELED, i);
finish();
} else if (action == DocReaderAction.MORE_PAGES_AVAILABLE) {
// Log.i("SmartCheck", " Scan Passport successfully = " + results.documentType.dType);
// Log.i("SmartCheck", " Scan Passport successfully = " + results.documentType.name);
setPlayAudio();
// if (results.documentType.dType == 12) { // ID 1998
// returnResult(results);
// }
// if (results.documentType.. == 11 || results.documentType.name.contains("Passport")) {//ePassport
// returnResult(results);
// }
firstPage = false;
updateStatus();
}
if (action == DocReaderAction.PROCESS) {
if (results != null) {
if (results.jsonResult != null && results.documentPosition != null && results.jsonResult.results.size() > 0) {
DocumentReader.Instance().customization().setStatus("Your ID is being scanned. \nPlease hold it within the frame");
} else {
updateStatus();
}
}
}
}
} catch (Exception e) {
Log.e("SmartCheck", "exception 1");
e.printStackTrace();
Toast.makeText(RegulaActivity.this, "Scanning was error", Toast.LENGTH_LONG).show();
DocumentReader.Instance().stopScanner();
RegulaActivity.this.setResult(RESULT_CANCELED, new Intent());
RegulaActivity.this.finish();
}
}
};
private void returnResult(DocumentReaderResults results) {
DocumentReader.Instance().stopScanner();
processFrontResults(results);
Intent intent = new Intent();
intent.putExtra(SmartCheckActivity.DOC_ID, Parcels.wrap(dl));
setResult(RESULT_OK, intent);
finish();
}
private void updateStatus() {
if (firstPage) {
DocumentReader.Instance().customization().setStatus("Please scan the front side of your ID.\nMake sure it is inside the white frame");
} else {
DocumentReader.Instance().customization().setStatus("Please scan the back side of your ID.\nMake sure it is inside the white frame");
}
}
private AlertDialog showDialog(String msg) {
AlertDialog.Builder dialog = new AlertDialog.Builder(RegulaActivity.this);
View dialogView = getLayoutInflater().inflate(R.layout.simple_dialog, null);
dialog.setTitle(msg);
dialog.setView(dialogView);
dialog.setCancelable(false);
return dialog.show();
}
//show received results on the UI
private void processFrontResults(DocumentReaderResults results) {
if (results != null) {
Log.i("SmartCheck", "found results");
try {
String middleName = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_MIDDLE_NAME), " ");
dl.setMiddleName(middleName);
String firstName = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_GIVEN_NAMES), " ");
dl.setFirstName(firstName);
String lastName = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_SURNAME), " ");
dl.setLastName(lastName);
String address = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_ADDRESS_STREET), " ");
dl.setAddress(address);
String city = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_ADDRESS_CITY), " ");
dl.setCity(city);
String zipCode = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_ADDRESS_POSTAL_CODE), " ");
try{
//sometimes zipcode return "...;;"
if (zipCode != null) {
Double.parseDouble(zipCode);
dl.setZipcode(zipCode);
}
}catch (NumberFormatException e){
dl.setZipcode("");
}
String state = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_ADDRESS_JURISDICTION_CODE), " ");
dl.setState(state.toUpperCase());
// String birthDate = Util.convertRegulaDate(results.getTextFieldValueByType(eVisualFieldType.FT_DATE_OF_BIRTH));
String birthDate = results.getTextFieldValueByType(eVisualFieldType.FT_DATE_OF_BIRTH);
dl.setBirthDate(birthDate);
String placeOfBirth = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_PLACE_OF_BIRTH), " ");
dl.setPlaceOfBirth(placeOfBirth);
String issuer = results.getTextFieldValueByType(eVisualFieldType.FT_ADDRESS_JURISDICTION_CODE);
dl.setIssuer(issuer);
String IdNumber = results.getTextFieldValueByType(eVisualFieldType.FT_DOCUMENT_NUMBER);
dl.setIdNumber(IdNumber);
String idPassport = results.getTextFieldValueByType(eVisualFieldType.FT_PASSPORT_NUMBER);
if (idPassport != null && !idPassport.isEmpty()) {
dl.setIdNumber(idPassport);
}
// String issueDate = Util.convertRegulaDate(results.getTextFieldValueByType(eVisualFieldType.FT_DATE_OF_ISSUE));
String issueDate = results.getTextFieldValueByType(eVisualFieldType.FT_DATE_OF_ISSUE);
dl.setIssueDate(issueDate);
// String expirationDate = Util.convertRegulaDate(results.getTextFieldValueByType(eVisualFieldType.FT_DATE_OF_EXPIRY));
String expirationDate = results.getTextFieldValueByType(eVisualFieldType.FT_DATE_OF_EXPIRY);
dl.setExpirationDate(expirationDate);
String nationality = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_NATIONALITY), " ");
dl.setNationality(nationality);
String authority = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_AUTHORITY), " ");
dl.setAuthority(authority);
String gender = results.getTextFieldValueByType(eVisualFieldType.FT_SEX);
if (gender != null) {
switch (gender) {
case "M":
dl.setGender("Male");
break;
case "F":
dl.setGender("Female");
break;
default:
dl.setGender("Unknown");
break;
}
}
else{
dl.setGender("Unknown");
}
if(results.textResult != null && results.textResult.fields != null) {
for (DocumentReaderTextField textField : results.textResult.fields) {
String value = results.getTextFieldValueByType(textField.fieldType, textField.lcid);
Log.d("MainActivity", "textfield = "+ textField.fieldName+ value + "\n");
}
}
// barcode
// String firstNameBc = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_GIVEN_NAMES, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA), " ");
// if (firstNameBc != null && !firstNameBc.isEmpty()) {
// dl.setFirstName(firstNameBc);
// }
//
// String lastNameBc = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_SURNAME, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA), " ");
// if (lastNameBc != null && !lastNameBc.isEmpty()) {
// dl.setLastName(lastNameBc);
// }
//
// String addressBc = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_ADDRESS_STREET, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA), " ");
// if (addressBc != null && !addressBc.isEmpty()) {
// dl.setAddress(addressBc);
// }
//
// String cityBc = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_ADDRESS_CITY, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA), " ");
// if (cityBc != null && !cityBc.isEmpty()) {
// dl.setCity(cityBc);
// }
//
// String zipCodeBc = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_ADDRESS_POSTAL_CODE, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA), " ");
// if (zipCodeBc != null && !zipCodeBc.isEmpty()) {
// try{
// Double.parseDouble(zipCodeBc);
// dl.setZipcode(zipCodeBc);
// }catch (NumberFormatException e){
// dl.setZipcode("");
// }
//
// }
//
// String stateBc = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_ADDRESS_JURISDICTION_CODE, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA), " ");
// if (stateBc != null && !stateBc.isEmpty()) {
// dl.setState(stateBc.toUpperCase());
// }
//
// String birthDateBc = Util.convertRegulaDate(results.getTextFieldValueByType(eVisualFieldType.FT_DATE_OF_BIRTH, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA));
// if (birthDateBc != null && !birthDateBc.isEmpty()) {
// dl.setBirthDate(birthDateBc);
// }
//
// String placeOfBirthBc = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_PLACE_OF_BIRTH, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA), " ");
// if (placeOfBirthBc != null && !placeOfBirthBc.isEmpty()) {
// dl.setPlaceOfBirth(placeOfBirthBc);
// }
//
// String issuerBc = results.getTextFieldValueByType(eVisualFieldType.FT_ADDRESS_JURISDICTION_CODE, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA);
// if (issuerBc != null && !issuerBc.isEmpty()) {
// dl.setIssuer(issuerBc);
// }
//
// String idNumberBc = results.getTextFieldValueByType(eVisualFieldType.FT_DOCUMENT_NUMBER, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA);
// if (idNumberBc != null && !idNumberBc.isEmpty()) {
// dl.setIdNumber(idNumberBc);
// }
//
// String idPassportBc = results.getTextFieldValueByType(eVisualFieldType.FT_PASSPORT_NUMBER, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA);
// if (idPassportBc != null && !idPassportBc.isEmpty()) {
// dl.setIdNumber(idPassportBc);
// }
//
// String issueDateBc = Util.convertRegulaDate(results.getTextFieldValueByType(eVisualFieldType.FT_DATE_OF_ISSUE, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA));
// if (issueDateBc != null && !issueDateBc.isEmpty()) {
// dl.setIssueDate(issueDateBc);
// }
//
// String expirationDateBc = Util.convertRegulaDate(results.getTextFieldValueByType(eVisualFieldType.FT_DATE_OF_EXPIRY, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA));
// if (expirationDateBc != null && !expirationDateBc.isEmpty()) {
// dl.setExpirationDate(expirationDateBc);
// }
//
// String nationalityBc = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_NATIONALITY, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA), " ");
// if (nationalityBc != null && !nationalityBc.isEmpty()) {
// dl.setNationality(nationalityBc);
// }
//
// String authorityBc = Util.camelCase(results.getTextFieldValueByType(eVisualFieldType.FT_AUTHORITY, LCID.NONE, eRPRM_ResultType.RPRM_RESULT_TYPE_BAR_CODES_TEXT_DATA), " ");
// if (authorityBc != null && !authorityBc.isEmpty()) {
// dl.setAuthority(authorityBc);
// }
// if (results.documentType != null) {
// if (results.documentType.dType == 12) {
// dl.setIdType("ID Card");
// } else if (results.documentType.name.toLowerCase().contains("passport")) {
// dl.setIssuer(results.getTextFieldValueByType(eVisualFieldType.FT_ISSUING_STATE_CODE));
// dl.setIdType("Passport");
// } else if (results.documentType.dType == 49) {
// dl.setIdType("Driver's License");
// }
//// else if (results.documentType.dType != 49 &&
//// (idPassport != null && idPassport.isEmpty()) || (idPassportBc != null && !idPassportBc.isEmpty())) {
//// if (results.documentType.name.toLowerCase().contains("states")) {
//// dl.setIdType("US Passport");
//// } else if (results.documentType.name.toLowerCase().contains("mexico")) {
//// dl.setIdType("Mexico Passport");
//// } else {
//// dl.setIdType("Passport");
//// }
//// }
// else {
// dl.setIdType("Other");
// }
// }
ByteArrayOutputStream stream;
Bitmap frontImage = results.getGraphicFieldImageByType(eGraphicFieldType.GF_DOCUMENT_IMAGE);
if (frontImage != null) {
stream = new ByteArrayOutputStream();
frontImage.compress(Bitmap.CompressFormat.JPEG, 70, stream);
DocId.frontProcessedImage = stream.toByteArray();
frontImage.recycle();
} else {
Log.i("SmartCheck", "front image not present");
}
// Bitmap rearImage = results.getGraphicFieldImageByType(eGraphicFieldType.GT_DOCUMENT_REAR);
//
// if (rearImage != null) {
// stream = new ByteArrayOutputStream();
// rearImage.compress(Bitmap.CompressFormat.JPEG, 70, stream);
// DocId.rearProcessedImage = stream.toByteArray();
// rearImage.recycle();
// } else {
// DocId.rearProcessedImage = null;
// Log.i("SmartCheck", "back image not present");
// }
dl.setStatus("success");
for (DocumentReaderTextField textField : results.textResult.fields) {
String value = results.getTextFieldValueByType(textField.fieldType, textField.lcid);
Log.d("MainActivity", "field type = " + textField.fieldType + "," + "field type name= " + textField.fieldName + "," + value + "\n");
}
} catch (Exception e) {
Log.i("SmartCheck", "error front");
Log.i("SmartCheck", e.getMessage());
dl.setStatus("error");
}
} else {
Log.i("SmartCheck", "error front");
dl.setStatus("error");
}
}
public void setPlayAudio() {
mPlayer = MediaPlayer.create(this, R.raw.pictureshutter);
mPlayer.start();
mPlayer.setLooping(false);
}
}
| 21,111 | 0.562124 | 0.561035 | 431 | 47.981438 | 43.224762 | 202 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.735499 | false | false | 9 |
d610cb176ad650e5e7c4af56763c020036ac57b0 | 2,121,713,865,209 | 9f17ba9014a5eae581f8ab8e3a520c20e4b7cccf | /src/main/java/es/bisite/usal/bullytect/rest/hal/ISonHAL.java | f0e6d5fd99414b7916b6f1c32eeb564a777ae18b | [] | no_license | gspandy/spring-integration-sample | https://github.com/gspandy/spring-integration-sample | 770fe8017359f7a4d37c8e95270918ad1b47ab18 | 41a5c88857ad6c9ea53d4a73608a5113d5e3196c | refs/heads/master | 2023-08-10T01:41:30.605000 | 2017-09-18T17:33:20 | 2017-09-18T17:33:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package es.bisite.usal.bullytect.rest.hal;
import org.springframework.data.domain.Page;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.PagedResources;
import org.springframework.hateoas.Resource;
import org.springframework.http.ResponseEntity;
import es.bisite.usal.bullytect.dto.response.CommentDTO;
import es.bisite.usal.bullytect.dto.response.SocialMediaDTO;
import es.bisite.usal.bullytect.dto.response.SonDTO;
import es.bisite.usal.bullytect.rest.controller.ChildrenController;
import es.bisite.usal.bullytect.rest.response.APIResponse;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
/**
*
* @author sergio
*/
public interface ISonHAL {
default SonDTO addLinksToSon(final SonDTO sonResource) {
Link selfLink = linkTo(ChildrenController.class).slash(sonResource.getIdentity()).withSelfRel();
sonResource.add(selfLink);
try {
ResponseEntity<APIResponse<PagedResources<Resource<CommentDTO>>>> methodLinkBuilder = methodOn(ChildrenController.class)
.getCommentsBySonId(null, null, sonResource.getIdentity());
Link commentsLink = linkTo(methodLinkBuilder).withRel("comments");
sonResource.add(commentsLink);
ResponseEntity<APIResponse<Iterable<SocialMediaDTO>>> socialMediasLinkBuilder = methodOn(ChildrenController.class)
.getSocialMediaBySonId(sonResource.getIdentity());
Link socialMediaLink = linkTo(socialMediasLinkBuilder).withRel("socialMedia");
sonResource.add(socialMediaLink);
} catch (Throwable ex) {
throw new RuntimeException(ex);
}
return sonResource;
}
default Iterable<SonDTO> addLinksToChildren(final Iterable<SonDTO> sonsResources) {
for (SonDTO sonResource : sonsResources) {
addLinksToSon(sonResource);
}
return sonsResources;
}
default Page<SonDTO> addLinksToChildren(final Page<SonDTO> sonsPage) {
for (SonDTO sonResource : sonsPage.getContent()) {
addLinksToSon(sonResource);
}
return sonsPage;
}
}
| UTF-8 | Java | 2,309 | java | ISonHAL.java | Java | [
{
"context": "ControllerLinkBuilder.methodOn;\n\n/**\n *\n * @author sergio\n */\npublic interface ISonHAL {\n \n default S",
"end": 753,
"score": 0.8785603046417236,
"start": 747,
"tag": "USERNAME",
"value": "sergio"
}
] | null | [] | package es.bisite.usal.bullytect.rest.hal;
import org.springframework.data.domain.Page;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.PagedResources;
import org.springframework.hateoas.Resource;
import org.springframework.http.ResponseEntity;
import es.bisite.usal.bullytect.dto.response.CommentDTO;
import es.bisite.usal.bullytect.dto.response.SocialMediaDTO;
import es.bisite.usal.bullytect.dto.response.SonDTO;
import es.bisite.usal.bullytect.rest.controller.ChildrenController;
import es.bisite.usal.bullytect.rest.response.APIResponse;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
/**
*
* @author sergio
*/
public interface ISonHAL {
default SonDTO addLinksToSon(final SonDTO sonResource) {
Link selfLink = linkTo(ChildrenController.class).slash(sonResource.getIdentity()).withSelfRel();
sonResource.add(selfLink);
try {
ResponseEntity<APIResponse<PagedResources<Resource<CommentDTO>>>> methodLinkBuilder = methodOn(ChildrenController.class)
.getCommentsBySonId(null, null, sonResource.getIdentity());
Link commentsLink = linkTo(methodLinkBuilder).withRel("comments");
sonResource.add(commentsLink);
ResponseEntity<APIResponse<Iterable<SocialMediaDTO>>> socialMediasLinkBuilder = methodOn(ChildrenController.class)
.getSocialMediaBySonId(sonResource.getIdentity());
Link socialMediaLink = linkTo(socialMediasLinkBuilder).withRel("socialMedia");
sonResource.add(socialMediaLink);
} catch (Throwable ex) {
throw new RuntimeException(ex);
}
return sonResource;
}
default Iterable<SonDTO> addLinksToChildren(final Iterable<SonDTO> sonsResources) {
for (SonDTO sonResource : sonsResources) {
addLinksToSon(sonResource);
}
return sonsResources;
}
default Page<SonDTO> addLinksToChildren(final Page<SonDTO> sonsPage) {
for (SonDTO sonResource : sonsPage.getContent()) {
addLinksToSon(sonResource);
}
return sonsPage;
}
}
| 2,309 | 0.702035 | 0.702035 | 58 | 38.810345 | 33.727844 | 136 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.534483 | false | false | 9 |
754a7b594a2bc9e5cbdea2fb6937a21b44d5ae27 | 22,703,197,138,198 | 86fa27069bdecafafa74d58416a43ce5e26ec314 | /rxretrofitlib/src/main/java/com/allen/rxretrofitlib/download/HttpDownloadService.java | 269577deb6fa74224cbe02db7c20b4800c83caf9 | [] | no_license | zhuzhu2017/RxRetrofit | https://github.com/zhuzhu2017/RxRetrofit | 7233f8a8baaa677cf20111fc8347c27debf1a0fd | 78ed0339b9a77d41b54143bc02e4854daa98b61f | refs/heads/master | 2021-05-06T21:00:58.634000 | 2017-12-08T08:50:23 | 2017-12-08T08:50:23 | 112,453,808 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.allen.rxretrofitlib.download;
import okhttp3.ResponseBody;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Streaming;
import retrofit2.http.Url;
import rx.Observable;
/**
* service统一接口数据
* Created by allen on 2017/12/8.
*/
public interface HttpDownloadService {
/**
* 大文件断点续传
*
* @param start 起始下载点
* @param url 下载Url
* @return
*/
@Streaming
@GET
Observable<ResponseBody> breakpointDownload(@Header("RANGE") String start, @Url String url);
/**
* @param url 下载url
* @return
*/
@Streaming
@GET
Observable<ResponseBody> commonDownload(@Url String url);
}
| UTF-8 | Java | 726 | java | HttpDownloadService.java | Java | [
{
"context": "rx.Observable;\n\n/**\n * service统一接口数据\n * Created by allen on 2017/12/8.\n */\n\npublic interface HttpDownloadS",
"end": 252,
"score": 0.9977672100067139,
"start": 247,
"tag": "USERNAME",
"value": "allen"
}
] | null | [] | package com.allen.rxretrofitlib.download;
import okhttp3.ResponseBody;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Streaming;
import retrofit2.http.Url;
import rx.Observable;
/**
* service统一接口数据
* Created by allen on 2017/12/8.
*/
public interface HttpDownloadService {
/**
* 大文件断点续传
*
* @param start 起始下载点
* @param url 下载Url
* @return
*/
@Streaming
@GET
Observable<ResponseBody> breakpointDownload(@Header("RANGE") String start, @Url String url);
/**
* @param url 下载url
* @return
*/
@Streaming
@GET
Observable<ResponseBody> commonDownload(@Url String url);
}
| 726 | 0.662757 | 0.645161 | 35 | 18.485714 | 19.292295 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 9 |
2826fc279d99fc0d0e6f86d6c2546fb377bf131b | 31,190,052,523,961 | c69a36d7cfc443067fbb8502806fd0c1317e154e | /src/test/java/com/crawlerservice/util/ElementUtilTest.java | 89b20f4d6dcedd9f428238373f268f9f4ebc0cc8 | [] | no_license | gustavoSaboia97/crawlerwebservice | https://github.com/gustavoSaboia97/crawlerwebservice | c450c4ecbc2e2a2196ac35f954bb038dbd17b8ea | 8a052cde3283ac40e8964fbea4d45f2c4a3bee45 | refs/heads/master | 2020-04-16T00:44:53.073000 | 2019-01-26T02:05:08 | 2019-01-26T02:05:08 | 165,150,309 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.crawlerservice.util;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Before;
import org.junit.Test;
import static com.crawlerservice.component.XmlConstants.*;
import static org.mockito.Mockito.*;
public class ElementUtilTest {
private ElementUtil elementUtil;
private String content = "CONTENT";
@Before
public void setup(){
elementUtil = new ElementUtil();
}
@Test
public void shouldCreateAnUncompletedItem(){
Elements xmlElements = mock(Elements.class);
Element element = mock(Element.class);
when(element.select(TITLE)).thenReturn(xmlElements);
when(element.select(LINK)).thenReturn(xmlElements);
when(element.select(DESCRIPTION)).thenReturn(xmlElements);
when(xmlElements.text()).thenReturn(content);
elementUtil.getUncompleteItem(element);
verify(element).select(TITLE);
verify(element).select(LINK);
verify(element).select(DESCRIPTION);
verify(xmlElements, times(3)).text();
}
}
| UTF-8 | Java | 1,072 | java | ElementUtilTest.java | Java | [] | null | [] | package com.crawlerservice.util;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Before;
import org.junit.Test;
import static com.crawlerservice.component.XmlConstants.*;
import static org.mockito.Mockito.*;
public class ElementUtilTest {
private ElementUtil elementUtil;
private String content = "CONTENT";
@Before
public void setup(){
elementUtil = new ElementUtil();
}
@Test
public void shouldCreateAnUncompletedItem(){
Elements xmlElements = mock(Elements.class);
Element element = mock(Element.class);
when(element.select(TITLE)).thenReturn(xmlElements);
when(element.select(LINK)).thenReturn(xmlElements);
when(element.select(DESCRIPTION)).thenReturn(xmlElements);
when(xmlElements.text()).thenReturn(content);
elementUtil.getUncompleteItem(element);
verify(element).select(TITLE);
verify(element).select(LINK);
verify(element).select(DESCRIPTION);
verify(xmlElements, times(3)).text();
}
}
| 1,072 | 0.694963 | 0.69403 | 41 | 25.146341 | 21.734047 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.536585 | false | false | 9 |
2979b7bdb67f0e9ed6d3c3b0e4c0296fae9e37e4 | 33,028,298,574,887 | b04ace9fb4640cd0c3f13caeb7e15a411a35f990 | /Main.java | fa78bf08bd0aeeda093dbbacc3cb63a66be0b1dc | [] | no_license | michalmusial147/JavaEdu7.ClassInherit | https://github.com/michalmusial147/JavaEdu7.ClassInherit | 1b597c2f2d16b36d122d731c9c554580d58b7ade | d7b9166a6005282a650198f8b0b21713de1a2164 | refs/heads/master | 2020-05-09T14:38:43.697000 | 2019-04-13T17:13:07 | 2019-04-13T17:13:07 | 181,201,872 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.TreeMap;
import java.util.Collection;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
TreeMap TreeMap = new TreeMap<TelephoneNumber,Record>();
TreeMap.put(new TelephoneNumber("+48","123456789"),
new Person("Adam","Pierwszy","Przedecz","+48","123456789"));
TreeMap.put(new TelephoneNumber("+48","999999999"),
new Person("Adam","Drugi","Pieklo","+48","999999999"));
TreeMap.put(new TelephoneNumber("+48","969111960"),
new Person("Ewa","Pierwsza","Ziemia","+48","969111960"));
TreeMap.put(new TelephoneNumber("+48","2358_13_21"),
new Business("Gates of Eden","Center of the Milky Way","+11","2358_13_21"));
Collection collection = TreeMap.values();
Iterator itr = collection.iterator();
while(itr.hasNext()) {
((Record)itr.next()).description();
System.out.println("");
}
}
}
| UTF-8 | Java | 1,000 | java | Main.java | Java | [
{
"context": "r(\"+48\",\"123456789\"),\n new Person(\"Adam\",\"Pierwszy\",\"Przedecz\",\"+48\",\"123456789\"));\n ",
"end": 306,
"score": 0.9998675584793091,
"start": 302,
"tag": "NAME",
"value": "Adam"
},
{
"context": ",\"123456789\"),\n new Person... | null | [] | import java.util.TreeMap;
import java.util.Collection;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
TreeMap TreeMap = new TreeMap<TelephoneNumber,Record>();
TreeMap.put(new TelephoneNumber("+48","123456789"),
new Person("Adam","Pierwszy","Przedecz","+48","123456789"));
TreeMap.put(new TelephoneNumber("+48","999999999"),
new Person("Adam","Drugi","Pieklo","+48","999999999"));
TreeMap.put(new TelephoneNumber("+48","969111960"),
new Person("Ewa","Pierwsza","Ziemia","+48","969111960"));
TreeMap.put(new TelephoneNumber("+48","2358_13_21"),
new Business("Gates of Eden","Center of the Milky Way","+11","2358_13_21"));
Collection collection = TreeMap.values();
Iterator itr = collection.iterator();
while(itr.hasNext()) {
((Record)itr.next()).description();
System.out.println("");
}
}
}
| 1,000 | 0.592 | 0.506 | 24 | 40.666668 | 26.066689 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.5 | false | false | 9 |
79ce2dd5acc1ecd2f02cae13ed154633d28c89b6 | 20,770,461,850,517 | 742d2e9baf2ec9f0d8f2e4b3568b892f310a20f0 | /src/net/cooldude/escapists/reference/ObjectReference.java | 35b5e43fef2d60fbc92bd02bac02f1adde1229dc | [] | no_license | CoolDude9090/Escapists-Unofficial-Mapping-Tool | https://github.com/CoolDude9090/Escapists-Unofficial-Mapping-Tool | c2ed41beff18690cadfd936446f77aa9c719c7bd | 2ac4139f0c1dbea8f71a9887aaa5ec7da4537bed | refs/heads/master | 2015-07-11T15:35:33 | 2015-05-10T19:21:26 | 2015-05-10T19:21:26 | 35,367,973 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.cooldude.escapists.reference;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
public class ObjectReference {
public enum EnumObjectCategory {
Cell,
Doors,
Gym,
Jeep,
Jobs,
Misc,
Security,
Waypoints,
Zipline
}
public static class GameObject {
private String name;
private EnumObjectCategory category;
private String description;
private BufferedImage image;
private int width, height;
public GameObject(String name, EnumObjectCategory category, String description, String image, int width, int height) {
this.name = name;
this.category = category;
if(description == null) {
this.description = "This object has no description available";
} else {
this.description = description;
}
try{
this.image = ImageIO.read(ClassLoader.class.getResource("/res/objects/" + image + ".png"));
} catch(IOException e) {
try{
this.image = ImageIO.read(ClassLoader.class.getResource("/res/objects/Missing.png"));
} catch(IOException ex) {
System.exit(-1);
}
}
this.width = width;
this.height = height;
}
public GameObject(String name, EnumObjectCategory category, String description, String image) {
this.name = name;
this.category = category;
if(description == null) {
this.description = "This object has no description available";
} else {
this.description = description;
}
try{
this.image = ImageIO.read(ClassLoader.class.getResource("/res/objects/" + image + ".png"));
} catch(IOException e) {
try{
this.image = ImageIO.read(ClassLoader.class.getResource("/res/objects/Missing.png"));
} catch(IOException ex) {
System.exit(-1);
}
}
this.width = 1;
this.height = 1;
}
public String getName() {
return name;
}
public EnumObjectCategory getCategory() {
return category;
}
public BufferedImage getImage() {
return image;
}
}
public class WorldObject {
private final GameObject obj;
private final int x, y;
public WorldObject(GameObject obj, int x, int y) {
this.obj = obj;
this.x = x;
this.y = y;
}
public GameObject getObject() {
return obj;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
public static ArrayList<GameObject> objects;
public static void init() {
objects = new ArrayList<>();
}
private static void put(String name, String description, EnumObjectCategory cat, String image) {
objects.add(new GameObject(name, cat, description, image));
}
private static void put(String name, EnumObjectCategory cat, String image) {
objects.add(new GameObject(name, cat, null, image));
}
private static void put(String name, String description, EnumObjectCategory cat, String image, int width, int height) {
objects.add(new GameObject(name, cat, description, image, width, height));
}
private static void put(String name, EnumObjectCategory cat, String image, int width, int height) {
objects.add(new GameObject(name, cat, null, image, width, height));
}
}
| UTF-8 | Java | 4,090 | java | ObjectReference.java | Java | [] | null | [] | package net.cooldude.escapists.reference;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
public class ObjectReference {
public enum EnumObjectCategory {
Cell,
Doors,
Gym,
Jeep,
Jobs,
Misc,
Security,
Waypoints,
Zipline
}
public static class GameObject {
private String name;
private EnumObjectCategory category;
private String description;
private BufferedImage image;
private int width, height;
public GameObject(String name, EnumObjectCategory category, String description, String image, int width, int height) {
this.name = name;
this.category = category;
if(description == null) {
this.description = "This object has no description available";
} else {
this.description = description;
}
try{
this.image = ImageIO.read(ClassLoader.class.getResource("/res/objects/" + image + ".png"));
} catch(IOException e) {
try{
this.image = ImageIO.read(ClassLoader.class.getResource("/res/objects/Missing.png"));
} catch(IOException ex) {
System.exit(-1);
}
}
this.width = width;
this.height = height;
}
public GameObject(String name, EnumObjectCategory category, String description, String image) {
this.name = name;
this.category = category;
if(description == null) {
this.description = "This object has no description available";
} else {
this.description = description;
}
try{
this.image = ImageIO.read(ClassLoader.class.getResource("/res/objects/" + image + ".png"));
} catch(IOException e) {
try{
this.image = ImageIO.read(ClassLoader.class.getResource("/res/objects/Missing.png"));
} catch(IOException ex) {
System.exit(-1);
}
}
this.width = 1;
this.height = 1;
}
public String getName() {
return name;
}
public EnumObjectCategory getCategory() {
return category;
}
public BufferedImage getImage() {
return image;
}
}
public class WorldObject {
private final GameObject obj;
private final int x, y;
public WorldObject(GameObject obj, int x, int y) {
this.obj = obj;
this.x = x;
this.y = y;
}
public GameObject getObject() {
return obj;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
public static ArrayList<GameObject> objects;
public static void init() {
objects = new ArrayList<>();
}
private static void put(String name, String description, EnumObjectCategory cat, String image) {
objects.add(new GameObject(name, cat, description, image));
}
private static void put(String name, EnumObjectCategory cat, String image) {
objects.add(new GameObject(name, cat, null, image));
}
private static void put(String name, String description, EnumObjectCategory cat, String image, int width, int height) {
objects.add(new GameObject(name, cat, description, image, width, height));
}
private static void put(String name, EnumObjectCategory cat, String image, int width, int height) {
objects.add(new GameObject(name, cat, null, image, width, height));
}
}
| 4,090 | 0.528606 | 0.527628 | 139 | 28.424461 | 27.559217 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.690647 | false | false | 9 |
9703c5493a9b9567ebf587b939f84bd77fc4da4f | 21,595,095,572,261 | c5a493486c1a2dbe6b1fba196c98cbbb4c8b6def | /src/main/java/com/octo/jeuvideo/mud/positions/Foret.java | 0392d85b51f924b04c86190333148fc41ea5ad1c | [] | no_license | jak78/Octo-Sandbox-Object-Calisthenics | https://github.com/jak78/Octo-Sandbox-Object-Calisthenics | 6887cdd9812484653be55ced5434d7c56838eede | 596d4e052efbe5bca3533c386f5b0d2e4fac7cf2 | refs/heads/master | 2021-01-22T10:08:57.018000 | 2011-08-01T12:32:23 | 2011-08-01T12:32:23 | 2,066,063 | 1 | 1 | null | false | 2022-02-15T21:13:24 | 2011-07-18T12:15:46 | 2014-05-05T03:14:42 | 2022-02-15T21:13:23 | 99 | 2 | 1 | 0 | Java | false | false | package com.octo.jeuvideo.mud.positions;
public class Foret extends Position {
private static final String MESSAGE_FORET = "Je suis dans la forêt.";
@Override
public String decrire() {
return MESSAGE_FORET;
}
}
| UTF-8 | Java | 222 | java | Foret.java | Java | [] | null | [] | package com.octo.jeuvideo.mud.positions;
public class Foret extends Position {
private static final String MESSAGE_FORET = "Je suis dans la forêt.";
@Override
public String decrire() {
return MESSAGE_FORET;
}
}
| 222 | 0.737557 | 0.737557 | 12 | 17.416666 | 21.484329 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 9 |
fb5a627f611f5973b14b38eb0fc541fe7535a276 | 927,712,950,555 | f4360cbf8b479d686cc90482f11d72666113efef | /Saksi_application/app/src/main/java/com/chutikarn/saksi_application/UserProfileActivity.java | 7044d0e894574cea7ee67ecabc8cea8737f4bad9 | [] | no_license | klao99/Saksi_Application | https://github.com/klao99/Saksi_Application | 970e11a0fd0cd7140bd1680e4df382546f027684 | a5941a0f0e7aba93059c83178957cebe874858d2 | refs/heads/master | 2023-03-08T06:36:22.700000 | 2021-02-26T18:49:45 | 2021-02-26T18:49:45 | 336,257,411 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.chutikarn.saksi_application;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import com.chutikarn.saksi_application.loginRegis.LoginActivity;
import com.google.firebase.auth.FirebaseAuth;
public class UserProfileActivity extends AppCompatActivity {
Button btnLogout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
btnLogout = findViewById(R.id.btnLogout);
btnLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
finish();
}
});
}
} | UTF-8 | Java | 958 | java | UserProfileActivity.java | Java | [] | null | [] | package com.chutikarn.saksi_application;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import com.chutikarn.saksi_application.loginRegis.LoginActivity;
import com.google.firebase.auth.FirebaseAuth;
public class UserProfileActivity extends AppCompatActivity {
Button btnLogout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
btnLogout = findViewById(R.id.btnLogout);
btnLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
finish();
}
});
}
} | 958 | 0.69833 | 0.69833 | 33 | 28.060606 | 24.304806 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.515152 | false | false | 9 |
1bb30c78e7e30e52eb2ee731651b44b9390e0a9f | 23,751,169,208,766 | c7308fa83f1c6cb58b7a81a24f7f7fc59f324ce1 | /src/main/java/kr/or/btf/web/domain/web/GraphMaster.java | aa88f6a85ca1cd0cf1a4ddf2fe0a63b77024f431 | [] | no_license | KimJerryzz/btf | https://github.com/KimJerryzz/btf | 160cf000eb6decd8a9aa05b2ad48d804138cdc98 | de1001ef3d55822a513f19182bdca4295e26b835 | refs/heads/master | 2023-07-14T07:22:58.215000 | 2021-08-23T06:59:47 | 2021-08-23T06:59:47 | 392,517,044 | 0 | 0 | null | false | 2021-08-23T06:59:47 | 2021-08-04T02:10:12 | 2021-08-04T02:25:33 | 2021-08-23T06:59:47 | 64,937 | 0 | 0 | 0 | JavaScript | false | false | package kr.or.btf.web.domain.web;
import kr.or.btf.web.domain.web.enums.GraphDvType;
import kr.or.btf.web.domain.web.enums.UserRollType;
import lombok.*;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.*;
import java.time.LocalDateTime;
@Getter
@Setter
@EqualsAndHashCode(of = "id")
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "tbl_graph_master")
@DynamicUpdate
public class GraphMaster {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "graph_pid")
private Long id;
@Enumerated(EnumType.STRING)
@Column(name = "graph_dv_ty")
private GraphDvType graphDvTy;
@Column(name = "graph_nm")
private String graphNm;
@Column(name = "reg_ps_id")
private String regPsId;
@Column(name = "reg_dtm")
private LocalDateTime regDtm;
@Column(name = "upd_ps_id")
private String updPsId;
@Column(name = "upd_dtm")
private LocalDateTime updDtm;
@Column(name = "del_at")
private String delAt;
}
| UTF-8 | Java | 1,064 | java | GraphMaster.java | Java | [] | null | [] | package kr.or.btf.web.domain.web;
import kr.or.btf.web.domain.web.enums.GraphDvType;
import kr.or.btf.web.domain.web.enums.UserRollType;
import lombok.*;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.*;
import java.time.LocalDateTime;
@Getter
@Setter
@EqualsAndHashCode(of = "id")
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "tbl_graph_master")
@DynamicUpdate
public class GraphMaster {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "graph_pid")
private Long id;
@Enumerated(EnumType.STRING)
@Column(name = "graph_dv_ty")
private GraphDvType graphDvTy;
@Column(name = "graph_nm")
private String graphNm;
@Column(name = "reg_ps_id")
private String regPsId;
@Column(name = "reg_dtm")
private LocalDateTime regDtm;
@Column(name = "upd_ps_id")
private String updPsId;
@Column(name = "upd_dtm")
private LocalDateTime updDtm;
@Column(name = "del_at")
private String delAt;
}
| 1,064 | 0.675752 | 0.675752 | 43 | 22.744186 | 15.033441 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.348837 | false | false | 9 |
da1ea8484d5f77367adeae47331665196c754ea0 | 16,527,034,222,163 | 2675bb9dd8c2a10a8c8b390aec08de2fc4227b17 | /src/main/java/com/designpatterns/Pizzeria/ZananasemOrder.java | 211aa2fe808c16b1ef8e3c8a933cf5389587c957 | [] | no_license | PiotrKotynia/comdesignpatterns | https://github.com/PiotrKotynia/comdesignpatterns | a0e042c460de419c85da91ed0a58c62819930680 | da7eb03451c002d950f98ba1af5a027c7c2be6f9 | refs/heads/master | 2020-03-13T16:43:27.260000 | 2018-04-26T20:07:53 | 2018-04-26T20:07:53 | 131,204,699 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.designpatterns.Pizzeria;
public class ZananasemOrder implements OrderInterface {
public void makeOrder() {
System.out.println("Z ananasem to nie pizza!");
System.out.println("ERROR!");
}
}
| UTF-8 | Java | 226 | java | ZananasemOrder.java | Java | [] | null | [] | package com.designpatterns.Pizzeria;
public class ZananasemOrder implements OrderInterface {
public void makeOrder() {
System.out.println("Z ananasem to nie pizza!");
System.out.println("ERROR!");
}
}
| 226 | 0.690265 | 0.690265 | 8 | 27.25 | 21.335123 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 9 |
60aa3610c669a25027474db4c9fdd16a9685fb93 | 28,956,669,557,507 | 16eaad0e92222a3c160ac72a509c08e90f668500 | /GatewayApp/src/main/java/org/airavata/teamzenith/webmethods/CancelJob.java | 2545af8f3f27b524b0cafc37112348264c999084 | [] | no_license | a2l007/Science-Gateway | https://github.com/a2l007/Science-Gateway | ed12febeb2e9578f57d544133fa2cd6a21828a03 | 64558f23c9ae412e70c06f83f4345185cfd96fe0 | refs/heads/master | 2021-01-22T23:58:37.992000 | 2016-05-03T13:45:48 | 2016-05-03T13:45:48 | 58,399,061 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.airavata.teamzenith.webmethods;
import java.io.IOException;
import org.airavata.teamzenith.dao.UserDetails;
import org.airavata.teamzenith.drivers.JobManagementImpl;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import com.jcraft.jsch.JSchException;
public class CancelJob {
private static final Logger LOGGER = LogManager.getLogger(MonitorJob.class);
public String getCancelJob(UserDetails user, String jobNumber) throws IOException, JSchException{
UserSession getSession = UserSession.login(user);
JobManagementImpl job = new JobManagementImpl();
try{
job.getCancelJob(getSession.getUserSession(), jobNumber);
}catch(JSchException e){
LOGGER.error("SSH ERROR: SSH session invalid in Cancel job");
throw new JSchException("SSH ERROR: SSH session invalid in Cancel job",e);
}catch(IOException e){
LOGGER.error("I/O ERROR: Problem with I/O stream in cancel job ");
throw new IOException("I/O ERROR: Problem with I/O stream in cancel job ",e);
}
return null;
}
}
| UTF-8 | Java | 1,037 | java | CancelJob.java | Java | [] | null | [] | package org.airavata.teamzenith.webmethods;
import java.io.IOException;
import org.airavata.teamzenith.dao.UserDetails;
import org.airavata.teamzenith.drivers.JobManagementImpl;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import com.jcraft.jsch.JSchException;
public class CancelJob {
private static final Logger LOGGER = LogManager.getLogger(MonitorJob.class);
public String getCancelJob(UserDetails user, String jobNumber) throws IOException, JSchException{
UserSession getSession = UserSession.login(user);
JobManagementImpl job = new JobManagementImpl();
try{
job.getCancelJob(getSession.getUserSession(), jobNumber);
}catch(JSchException e){
LOGGER.error("SSH ERROR: SSH session invalid in Cancel job");
throw new JSchException("SSH ERROR: SSH session invalid in Cancel job",e);
}catch(IOException e){
LOGGER.error("I/O ERROR: Problem with I/O stream in cancel job ");
throw new IOException("I/O ERROR: Problem with I/O stream in cancel job ",e);
}
return null;
}
}
| 1,037 | 0.768563 | 0.766635 | 34 | 29.5 | 29.454102 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.558824 | false | false | 9 |
d6be4cd0a1432482ee85319e77f2205c7ebb3ee1 | 13,374,528,204,220 | 1934e95051cd1a5242ca7f9e9ffa1d3abcf8307f | /src/main/java/com/plp/propertymgt/business/App.java | f689e36e9f5913749e041be1b75fad08d8e12c02 | [] | no_license | rohanpa2000/plp-propertymgt | https://github.com/rohanpa2000/plp-propertymgt | 1c5825142ebe21ff8705f9d4650756fa114b5a42 | 4772c7cc6bf4dd66f0acf032126558cb86410eb9 | refs/heads/master | 2020-04-07T12:42:18.674000 | 2018-12-14T12:57:52 | 2018-12-14T12:57:52 | 158,377,670 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.plp.propertymgt.business;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.plp.propertymgt.data.mysql.BookingDataMySql;
import com.plp.propertymgt.business.BookingBusiness;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args ) throws ParseException
{
BookingDataMySql bookingdb = new BookingDataMySql();
BookingBusiness bookingBusiness = new BookingBusiness();
/*
//Date bookingDate = new SimpleDateFormat( "yyyyMMdd" ).parse( "20180212" );
//{id=8.0, courtName=court1, bookingDate=Feb 12, 2018 12:00:00 AM,
//startTime=Feb 12, 2018 01:00:00 AM, endTime=Feb 12, 2018 12:00:00 AM,
//customer=Chathurka, cost=100.0, isCompleted=false, isDeleted=false}
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a");
Booking booking = new Booking();
booking.setId(8);
booking.setCourtName("court1");
booking.setBookingDate(sdf.parse("Feb 12, 2018 12:00:00 AM"));
booking.setStartTime(sdf.parse("Feb 12, 2018 05:00:00 PM"));
booking.setEndTime(sdf.parse("Feb 14, 2018 06:00:00 PM"));
booking.setCustomerName("Obama");
booking.setCost(55);
booking.setCompleted(false);
bookingdb.addBooking(booking);
*/
try {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date startDate = df.parse("06/11/2018 00:00");
//System.out.println(bookingBusiness.getLastIncidents());
//System.out.println(bookingBusiness.getBookings(startDate));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println(bookings);
}
}
| UTF-8 | Java | 1,852 | java | App.java | Java | [
{
"context": "ndTime=Feb 12, 2018 12:00:00 AM, \n \t//customer=Chathurka, cost=100.0, isCompleted=false, isDeleted=",
"end": 781,
"score": 0.4326725900173187,
"start": 779,
"tag": "USERNAME",
"value": "Ch"
},
{
"context": "Time=Feb 12, 2018 12:00:00 AM, \n \t//customer=Chathurk... | null | [] | package com.plp.propertymgt.business;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.plp.propertymgt.data.mysql.BookingDataMySql;
import com.plp.propertymgt.business.BookingBusiness;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args ) throws ParseException
{
BookingDataMySql bookingdb = new BookingDataMySql();
BookingBusiness bookingBusiness = new BookingBusiness();
/*
//Date bookingDate = new SimpleDateFormat( "yyyyMMdd" ).parse( "20180212" );
//{id=8.0, courtName=court1, bookingDate=Feb 12, 2018 12:00:00 AM,
//startTime=Feb 12, 2018 01:00:00 AM, endTime=Feb 12, 2018 12:00:00 AM,
//customer=Chathurka, cost=100.0, isCompleted=false, isDeleted=false}
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a");
Booking booking = new Booking();
booking.setId(8);
booking.setCourtName("court1");
booking.setBookingDate(sdf.parse("Feb 12, 2018 12:00:00 AM"));
booking.setStartTime(sdf.parse("Feb 12, 2018 05:00:00 PM"));
booking.setEndTime(sdf.parse("Feb 14, 2018 06:00:00 PM"));
booking.setCustomerName("Obama");
booking.setCost(55);
booking.setCompleted(false);
bookingdb.addBooking(booking);
*/
try {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date startDate = df.parse("06/11/2018 00:00");
//System.out.println(bookingBusiness.getLastIncidents());
//System.out.println(bookingBusiness.getBookings(startDate));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println(bookings);
}
}
| 1,852 | 0.649568 | 0.593952 | 62 | 28.870968 | 25.88092 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.612903 | false | false | 9 |
e50107e0b3293765c831a1ae730dfdb3c8d66b12 | 29,661,044,197,114 | 6779df6bc93116639ea5c364090e8f3c1b607bc4 | /HUDIYS/src/main/java/hud/iys/view/TebligDataModel.java | d0fba92f3c95e4b8f5da5d6959b5cdf3e85e63a4 | [] | no_license | ironnow/HUD-IYS | https://github.com/ironnow/HUD-IYS | 689f03ded5a19aea36dcb4b778a4ad1fe8d72ab6 | e817306353707a2f02ffdb142fd81182882c20c3 | refs/heads/master | 2020-04-25T16:42:07.811000 | 2014-11-03T02:06:58 | 2014-11-03T02:06:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package hud.iys.view;
import java.util.List;
import javax.faces.model.ListDataModel;
import hud.iys.model.Teblig;
import org.primefaces.model.SelectableDataModel;
public class TebligDataModel extends ListDataModel<Teblig> implements SelectableDataModel<Teblig> {
public TebligDataModel() {
}
public TebligDataModel(List<Teblig> data) {
super(data);
}
@Override
public Teblig getRowData(String rowKey) {
List<Teblig> tebliglar = (List<Teblig>) getWrappedData();
for(Teblig teblig : tebliglar) {
if((Long.toString(teblig.getTebligId())).equals(rowKey))
return teblig;
}
return null;
}
@Override
public Object getRowKey(Teblig teblig) {
return teblig.getTebligId();
}
} | UTF-8 | Java | 862 | java | TebligDataModel.java | Java | [] | null | [] | package hud.iys.view;
import java.util.List;
import javax.faces.model.ListDataModel;
import hud.iys.model.Teblig;
import org.primefaces.model.SelectableDataModel;
public class TebligDataModel extends ListDataModel<Teblig> implements SelectableDataModel<Teblig> {
public TebligDataModel() {
}
public TebligDataModel(List<Teblig> data) {
super(data);
}
@Override
public Teblig getRowData(String rowKey) {
List<Teblig> tebliglar = (List<Teblig>) getWrappedData();
for(Teblig teblig : tebliglar) {
if((Long.toString(teblig.getTebligId())).equals(rowKey))
return teblig;
}
return null;
}
@Override
public Object getRowKey(Teblig teblig) {
return teblig.getTebligId();
}
} | 862 | 0.609049 | 0.609049 | 34 | 23.411764 | 23.267141 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.294118 | false | false | 9 |
cbca85b6f66ee03491df0ce4ef6ff621b73ca30d | 7,825,430,427,024 | 93cda2400214826c2f34a1e774e42d69487b1778 | /app/src/main/java/com/blks/adapter/ModeAdapter.java | 742d3145e725eb58f48df7ffc9d32883e9081f87 | [] | no_license | lmh-1290226509/aasb | https://github.com/lmh-1290226509/aasb | 2ccf4eaa02e80b21f61c08bcfe96733d58bedc49 | 1f5c06721d5b86131aeb08a322b90123e1b4ab6e | refs/heads/master | 2020-04-17T00:16:47.855000 | 2019-01-30T03:26:17 | 2019-01-30T03:26:17 | 166,043,877 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.blks.adapter;
import android.content.Context;
import android.view.View;
import com.ddadai.baseviewlibrary.adapter.BaseRecyclerAdapter;
public class ModeAdapter extends BaseRecyclerAdapter {
public ModeAdapter(Context c) {
super(c);
}
@Override
protected int getRootViewLayoutId(int itemType) {
return 0;
}
@Override
protected MyViewHolder newViewHolder(View rootView, int itemType) {
return new Holder(rootView);
}
@Override
protected void initViewHolder(MyViewHolder holder, int position, Object item) {
Holder h= (Holder) holder;
}
private class Holder extends MyViewHolder{
public Holder(View arg0) {
super(arg0);
}
@Override
protected void initView() {
}
}
}
| UTF-8 | Java | 822 | java | ModeAdapter.java | Java | [] | null | [] | package com.blks.adapter;
import android.content.Context;
import android.view.View;
import com.ddadai.baseviewlibrary.adapter.BaseRecyclerAdapter;
public class ModeAdapter extends BaseRecyclerAdapter {
public ModeAdapter(Context c) {
super(c);
}
@Override
protected int getRootViewLayoutId(int itemType) {
return 0;
}
@Override
protected MyViewHolder newViewHolder(View rootView, int itemType) {
return new Holder(rootView);
}
@Override
protected void initViewHolder(MyViewHolder holder, int position, Object item) {
Holder h= (Holder) holder;
}
private class Holder extends MyViewHolder{
public Holder(View arg0) {
super(arg0);
}
@Override
protected void initView() {
}
}
}
| 822 | 0.653285 | 0.649635 | 40 | 19.549999 | 21.69902 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false | 9 |
212ffba64d724599a0f52255b322853bbcb057fe | 2,731,599,223,757 | c26304a54824faa7c1b34bb7882ee7a335a8e7fb | /flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/job/JobExecutionResultResponseBody.java | e0a21595b5e47b9198e8b233d97295c3ae0983ba | [
"BSD-3-Clause",
"OFL-1.1",
"ISC",
"MIT",
"Apache-2.0"
] | permissive | apache/flink | https://github.com/apache/flink | 905e0709de6389fc9212a7c48a82669706c70b4a | fbef3c22757a2352145599487beb84e02aaeb389 | refs/heads/master | 2023-09-04T08:11:07.253000 | 2023-09-04T01:33:25 | 2023-09-04T01:33:25 | 20,587,599 | 23,573 | 14,781 | Apache-2.0 | false | 2023-09-14T21:49:04 | 2014-06-07T07:00:10 | 2023-09-14T11:23:39 | 2023-09-14T21:49:03 | 509,428 | 21,946 | 12,627 | 1,090 | Java | false | false | /*
* 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.flink.runtime.rest.messages.job;
import org.apache.flink.runtime.jobmaster.JobResult;
import org.apache.flink.runtime.rest.messages.ResponseBody;
import org.apache.flink.runtime.rest.messages.json.JobResultDeserializer;
import org.apache.flink.runtime.rest.messages.json.JobResultSerializer;
import org.apache.flink.runtime.rest.messages.queue.AsynchronouslyCreatedResource;
import org.apache.flink.runtime.rest.messages.queue.QueueStatus;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonCreator;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonInclude;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.annotation.JsonSerialize;
import javax.annotation.Nullable;
import static java.util.Objects.requireNonNull;
/**
* {@link ResponseBody} that carries a {@link QueueStatus} and a {@link JobResult}.
*
* @see org.apache.flink.runtime.rest.handler.job.JobExecutionResultHandler
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class JobExecutionResultResponseBody
implements ResponseBody, AsynchronouslyCreatedResource<JobResult> {
@JsonProperty(value = "status", required = true)
private final QueueStatus status;
@JsonProperty(value = "job-execution-result")
@JsonSerialize(using = JobResultSerializer.class)
@JsonDeserialize(using = JobResultDeserializer.class)
@Nullable
private final JobResult jobExecutionResult;
@JsonCreator
public JobExecutionResultResponseBody(
@JsonProperty(value = "status", required = true) final QueueStatus status,
@JsonProperty(value = "job-execution-result")
@JsonDeserialize(using = JobResultDeserializer.class)
@Nullable
final JobResult jobExecutionResult) {
this.status = requireNonNull(status);
this.jobExecutionResult = jobExecutionResult;
}
public static JobExecutionResultResponseBody inProgress() {
return new JobExecutionResultResponseBody(QueueStatus.inProgress(), null);
}
public static JobExecutionResultResponseBody created(final JobResult jobExecutionResult) {
return new JobExecutionResultResponseBody(QueueStatus.completed(), jobExecutionResult);
}
public QueueStatus getStatus() {
return status;
}
@Nullable
public JobResult getJobExecutionResult() {
return jobExecutionResult;
}
@Override
public QueueStatus queueStatus() {
return status;
}
@Override
public JobResult resource() {
return jobExecutionResult;
}
}
| UTF-8 | Java | 3,630 | java | JobExecutionResultResponseBody.java | Java | [] | null | [] | /*
* 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.flink.runtime.rest.messages.job;
import org.apache.flink.runtime.jobmaster.JobResult;
import org.apache.flink.runtime.rest.messages.ResponseBody;
import org.apache.flink.runtime.rest.messages.json.JobResultDeserializer;
import org.apache.flink.runtime.rest.messages.json.JobResultSerializer;
import org.apache.flink.runtime.rest.messages.queue.AsynchronouslyCreatedResource;
import org.apache.flink.runtime.rest.messages.queue.QueueStatus;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonCreator;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonInclude;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.annotation.JsonSerialize;
import javax.annotation.Nullable;
import static java.util.Objects.requireNonNull;
/**
* {@link ResponseBody} that carries a {@link QueueStatus} and a {@link JobResult}.
*
* @see org.apache.flink.runtime.rest.handler.job.JobExecutionResultHandler
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class JobExecutionResultResponseBody
implements ResponseBody, AsynchronouslyCreatedResource<JobResult> {
@JsonProperty(value = "status", required = true)
private final QueueStatus status;
@JsonProperty(value = "job-execution-result")
@JsonSerialize(using = JobResultSerializer.class)
@JsonDeserialize(using = JobResultDeserializer.class)
@Nullable
private final JobResult jobExecutionResult;
@JsonCreator
public JobExecutionResultResponseBody(
@JsonProperty(value = "status", required = true) final QueueStatus status,
@JsonProperty(value = "job-execution-result")
@JsonDeserialize(using = JobResultDeserializer.class)
@Nullable
final JobResult jobExecutionResult) {
this.status = requireNonNull(status);
this.jobExecutionResult = jobExecutionResult;
}
public static JobExecutionResultResponseBody inProgress() {
return new JobExecutionResultResponseBody(QueueStatus.inProgress(), null);
}
public static JobExecutionResultResponseBody created(final JobResult jobExecutionResult) {
return new JobExecutionResultResponseBody(QueueStatus.completed(), jobExecutionResult);
}
public QueueStatus getStatus() {
return status;
}
@Nullable
public JobResult getJobExecutionResult() {
return jobExecutionResult;
}
@Override
public QueueStatus queueStatus() {
return status;
}
@Override
public JobResult resource() {
return jobExecutionResult;
}
}
| 3,630 | 0.753444 | 0.750964 | 93 | 38.032257 | 31.063047 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.376344 | false | false | 9 |
42a83052fd9a2494fd67a23e75a18be7fe442fc4 | 2,731,599,224,380 | e3a080d90711183686684cd73d35f524b805f321 | /code/app/SmartHome-Android/Home/SmartHome/src/cn/fuego/smart/home/service/SensorDataCache.java | 2255bbb02dbc0ad7ecf1b8671ed3c6eff8e0eb73 | [] | no_license | dalinhuang/SmartHome | https://github.com/dalinhuang/SmartHome | 6195520d808f4d7cf59eba47da03317463ee5510 | 5ea211a3779249cf2e8d6eac487dbbdabb8509aa | HEAD | 2018-01-16T12:28:21.502000 | 2015-10-08T00:36:38 | 2015-10-08T00:36:38 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.fuego.smart.home.service;
import java.util.ArrayList;
import java.util.List;
import cn.fuego.common.log.FuegoLog;
import cn.fuego.common.util.validate.ValidatorUtil;
import cn.fuego.misp.service.http.HttpListener;
import cn.fuego.misp.service.http.MispHttpHandler;
import cn.fuego.misp.service.http.MispHttpMessage;
import cn.fuego.smart.home.constant.SensorKindEunm;
import cn.fuego.smart.home.ui.model.SpinnerDataModel;
import cn.fuego.smart.home.webservice.up.model.GetSensorListReq;
import cn.fuego.smart.home.webservice.up.model.GetSensorListRsp;
import cn.fuego.smart.home.webservice.up.model.GetUserMarkListReq;
import cn.fuego.smart.home.webservice.up.model.GetUserMarkListRsp;
import cn.fuego.smart.home.webservice.up.model.base.HomeSensorJson;
import cn.fuego.smart.home.webservice.up.model.base.UserMarkJson;
import cn.fuego.smart.home.webservice.up.rest.WebServiceContext;
public class SensorDataCache extends MispHttpHandler
{
private FuegoLog log = FuegoLog.getLog(getClass());
private List<HomeSensorJson> ctrSensorList = new ArrayList<HomeSensorJson>();
private List<HomeSensorJson> measureSensorList = new ArrayList<HomeSensorJson>();
private List<SpinnerDataModel> ctrSpinnerList = new ArrayList<SpinnerDataModel>();
private int errorCode = 0;
private static SensorDataCache instance;
private HttpListener listener;
private List<String> markList= new ArrayList<String>();
private SensorDataCache()
{
//load();
loadMarkList();
}
synchronized public static SensorDataCache getInstance()
{
if(null == instance)
{
instance = new SensorDataCache();
}
return instance;
}
public void load(HttpListener listener)
{
this.listener = listener;
GetSensorListReq req = new GetSensorListReq();
req.setToken(MemoryCache.getToken());
req.setUserID(MemoryCache.getLoginInfo().getUser().getUserID());
WebServiceContext.getInstance().getSensorManageRest(this).getSensorList(req);
}
public List<HomeSensorJson> getCtrSensorList()
{
return ctrSensorList;
}
public List<HomeSensorJson> getMeasureSensorList()
{
return measureSensorList;
}
public List<SpinnerDataModel> getCtrSpinnerList()
{
return ctrSpinnerList;
}
public List<HomeSensorJson> getCtrSensorListByConcent(int concentratorID)
{
List<HomeSensorJson> sensorList = new ArrayList<HomeSensorJson>();
for(HomeSensorJson json : this.ctrSensorList)
{
if(concentratorID == json.getConcentratorID())
{
sensorList.add(json);
}
}
return sensorList;
}
@Override
public void handle(MispHttpMessage message)
{
if (message.isSuccess())
{
//设置初始或取消联动传感器情况
//联动控制终端ID,Long ctrSensorID = 0xfffffffL;
//联动控制终端通道ID,private Integer ctrChannelID = 0xffff;
SpinnerDataModel defSD= new SpinnerDataModel();
defSD.setCtrSensorID(String.valueOf(0xfffffffL));
defSD.setCtrChannelID(String.valueOf(0xffff));
defSD.setText("未配置传感器");
errorCode = message.getErrorCode();
GetSensorListRsp rsp =(GetSensorListRsp) message.getMessage().obj;
ctrSensorList.clear();
ctrSpinnerList.clear();
measureSensorList.clear();
ctrSpinnerList.add(defSD);
for(HomeSensorJson json : rsp.getSensorList())
{
switch (SensorKindEunm.getEnumByInt(json.getSensorKind()))
{
case CTRL_SENSOR:
ctrSensorList.add(json);
SpinnerDataModel spinnerData= new SpinnerDataModel();
spinnerData.setCtrSensorID(String.valueOf(json.getSensorID()));
spinnerData.setCtrChannelID(String.valueOf(json.getChannelID()));
spinnerData.setText(json.getSensorTypeName()+"位于"+json.getMark());
ctrSpinnerList.add(spinnerData);
break;
case DISCRETE_SENSOR:
case CONTIUOUS_SENSOR:
measureSensorList.add(json);
break;
default:
break;
}
}
}
listener.handle(message);
}
public int getErrorCode()
{
return errorCode;
}
public List<String> loadMarkList()
{
GetUserMarkListReq req = new GetUserMarkListReq();
req.setToken(MemoryCache.getToken());
req.setUserID(MemoryCache.getLoginInfo().getUser().getUserID());
WebServiceContext.getInstance().getUserManageRest(new MispHttpHandler(){
@Override
public void handle(MispHttpMessage msg)
{
if (msg.isSuccess())
{
GetUserMarkListRsp rsp = (GetUserMarkListRsp) msg.getMessage().obj;
List<UserMarkJson> userMarkList = rsp.getMarkList();
for(int i=0;i<userMarkList.size();i++)
{
markList.add(userMarkList.get(i).getMark());
}
//默认分组-未分组
markList.add("未分组");
}
else
{
//super.sendMessage(msg);
//Toast.makeText(context, text, duration)
log.info("load marklist failed:"+msg);
}
}
}).getUserMarkList(req);
return markList;
}
public List<String> getMarkList()
{
return markList;
}
public boolean noData()
{
Boolean result = false;
if (ValidatorUtil.isEmpty(this.getCtrSensorList())&& ValidatorUtil.isEmpty(this.getCtrSensorList()))
{
result = true;
}
return result;
}
}
| UTF-8 | Java | 5,127 | java | SensorDataCache.java | Java | [
{
"context": "eq = new GetUserMarkListReq();\n \treq.setToken(MemoryCache.getToken());\n \treq.setUserID(MemoryCache.getLoginInfo()",
"end": 4012,
"score": 0.5311511158943176,
"start": 3992,
"tag": "KEY",
"value": "MemoryCache.getToken"
}
] | null | [] | package cn.fuego.smart.home.service;
import java.util.ArrayList;
import java.util.List;
import cn.fuego.common.log.FuegoLog;
import cn.fuego.common.util.validate.ValidatorUtil;
import cn.fuego.misp.service.http.HttpListener;
import cn.fuego.misp.service.http.MispHttpHandler;
import cn.fuego.misp.service.http.MispHttpMessage;
import cn.fuego.smart.home.constant.SensorKindEunm;
import cn.fuego.smart.home.ui.model.SpinnerDataModel;
import cn.fuego.smart.home.webservice.up.model.GetSensorListReq;
import cn.fuego.smart.home.webservice.up.model.GetSensorListRsp;
import cn.fuego.smart.home.webservice.up.model.GetUserMarkListReq;
import cn.fuego.smart.home.webservice.up.model.GetUserMarkListRsp;
import cn.fuego.smart.home.webservice.up.model.base.HomeSensorJson;
import cn.fuego.smart.home.webservice.up.model.base.UserMarkJson;
import cn.fuego.smart.home.webservice.up.rest.WebServiceContext;
public class SensorDataCache extends MispHttpHandler
{
private FuegoLog log = FuegoLog.getLog(getClass());
private List<HomeSensorJson> ctrSensorList = new ArrayList<HomeSensorJson>();
private List<HomeSensorJson> measureSensorList = new ArrayList<HomeSensorJson>();
private List<SpinnerDataModel> ctrSpinnerList = new ArrayList<SpinnerDataModel>();
private int errorCode = 0;
private static SensorDataCache instance;
private HttpListener listener;
private List<String> markList= new ArrayList<String>();
private SensorDataCache()
{
//load();
loadMarkList();
}
synchronized public static SensorDataCache getInstance()
{
if(null == instance)
{
instance = new SensorDataCache();
}
return instance;
}
public void load(HttpListener listener)
{
this.listener = listener;
GetSensorListReq req = new GetSensorListReq();
req.setToken(MemoryCache.getToken());
req.setUserID(MemoryCache.getLoginInfo().getUser().getUserID());
WebServiceContext.getInstance().getSensorManageRest(this).getSensorList(req);
}
public List<HomeSensorJson> getCtrSensorList()
{
return ctrSensorList;
}
public List<HomeSensorJson> getMeasureSensorList()
{
return measureSensorList;
}
public List<SpinnerDataModel> getCtrSpinnerList()
{
return ctrSpinnerList;
}
public List<HomeSensorJson> getCtrSensorListByConcent(int concentratorID)
{
List<HomeSensorJson> sensorList = new ArrayList<HomeSensorJson>();
for(HomeSensorJson json : this.ctrSensorList)
{
if(concentratorID == json.getConcentratorID())
{
sensorList.add(json);
}
}
return sensorList;
}
@Override
public void handle(MispHttpMessage message)
{
if (message.isSuccess())
{
//设置初始或取消联动传感器情况
//联动控制终端ID,Long ctrSensorID = 0xfffffffL;
//联动控制终端通道ID,private Integer ctrChannelID = 0xffff;
SpinnerDataModel defSD= new SpinnerDataModel();
defSD.setCtrSensorID(String.valueOf(0xfffffffL));
defSD.setCtrChannelID(String.valueOf(0xffff));
defSD.setText("未配置传感器");
errorCode = message.getErrorCode();
GetSensorListRsp rsp =(GetSensorListRsp) message.getMessage().obj;
ctrSensorList.clear();
ctrSpinnerList.clear();
measureSensorList.clear();
ctrSpinnerList.add(defSD);
for(HomeSensorJson json : rsp.getSensorList())
{
switch (SensorKindEunm.getEnumByInt(json.getSensorKind()))
{
case CTRL_SENSOR:
ctrSensorList.add(json);
SpinnerDataModel spinnerData= new SpinnerDataModel();
spinnerData.setCtrSensorID(String.valueOf(json.getSensorID()));
spinnerData.setCtrChannelID(String.valueOf(json.getChannelID()));
spinnerData.setText(json.getSensorTypeName()+"位于"+json.getMark());
ctrSpinnerList.add(spinnerData);
break;
case DISCRETE_SENSOR:
case CONTIUOUS_SENSOR:
measureSensorList.add(json);
break;
default:
break;
}
}
}
listener.handle(message);
}
public int getErrorCode()
{
return errorCode;
}
public List<String> loadMarkList()
{
GetUserMarkListReq req = new GetUserMarkListReq();
req.setToken(MemoryCache.getToken());
req.setUserID(MemoryCache.getLoginInfo().getUser().getUserID());
WebServiceContext.getInstance().getUserManageRest(new MispHttpHandler(){
@Override
public void handle(MispHttpMessage msg)
{
if (msg.isSuccess())
{
GetUserMarkListRsp rsp = (GetUserMarkListRsp) msg.getMessage().obj;
List<UserMarkJson> userMarkList = rsp.getMarkList();
for(int i=0;i<userMarkList.size();i++)
{
markList.add(userMarkList.get(i).getMark());
}
//默认分组-未分组
markList.add("未分组");
}
else
{
//super.sendMessage(msg);
//Toast.makeText(context, text, duration)
log.info("load marklist failed:"+msg);
}
}
}).getUserMarkList(req);
return markList;
}
public List<String> getMarkList()
{
return markList;
}
public boolean noData()
{
Boolean result = false;
if (ValidatorUtil.isEmpty(this.getCtrSensorList())&& ValidatorUtil.isEmpty(this.getCtrSensorList()))
{
result = true;
}
return result;
}
}
| 5,127 | 0.726912 | 0.72572 | 188 | 25.781916 | 24.667799 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.473404 | false | false | 9 |
c81eace993ce6c00c936c5b8b0e6d376f93e2799 | 32,521,492,432,382 | 0b0934cb4f7fcd92fdd67029ea7447d294fa405a | /rxjava2.0/src/main/java/com/vst/rxjava20/MathActivity.java | ecc12e66aa8918cec4c75253e13d17e014e27529 | [] | no_license | zhouweiyong/RxDemo | https://github.com/zhouweiyong/RxDemo | 3b354b8fb19f87883c71dcfa82f971ccf92489c6 | a7567a0159658ec9f2c2e5d80e7215991dce2b5d | refs/heads/master | 2021-01-18T19:42:47.742000 | 2018-12-11T08:24:30 | 2018-12-11T08:24:30 | 86,906,647 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.vst.rxjava20;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.Arrays;
import io.reactivex.Observable;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
/**
* Created by zwy on 2017/9/18.
* email:16681805@qq.com
* 数学操作和聚合操作
*/
public class MathActivity extends Activity {
private ListView lv_main;
private String[] items = new String[]{"count", "reduce", "scan"};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
lv_main = (ListView) findViewById(R.id.lv_main);
lv_main.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, Arrays.asList(items)));
lv_main.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
count();
break;
case 1:
reduce();
break;
case 2:
scan();
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
case 7:
break;
}
}
});
}
/**
* 计算原始Observable发射物的数量,然后只发射这个值
*/
private void count() {
Observable.range(1, 10)
.count()
.subscribe(new Consumer<Long>() {
@Override
public void accept(@NonNull Long aLong) throws Exception {
L.i("count>>>" + aLong);
}
});
}
/**
* Reduce操作符应用一个函数接收Observable发射的数据和函数的计算结果作为下次计算的参数,输出最后的结果。
* 跟scan操作符很类似,只是scan会输出每次计算的结果,而reduce只会输出最后的结果。
*/
public void reduce() {
Observable.range(1, 10)
.reduce(new BiFunction<Integer, Integer, Integer>() {
@Override
public Integer apply(@NonNull Integer integer, @NonNull Integer integer2) throws Exception {
L.i(integer + ">>>>" + integer2);
return integer + integer2;
}
}).subscribe(new Consumer<Integer>() {
@Override
public void accept(@NonNull Integer integer) throws Exception {
L.i("subscribe>>>" + integer);
}
});
}
public void scan() {
//递加,每次递加都会发送结果
Observable.range(1, 10)
.scan(new BiFunction<Integer, Integer, Integer>() {
@Override
public Integer apply(@NonNull Integer sum, @NonNull Integer item) throws Exception {
return sum + item;
}
}).subscribe(new Consumer<Integer>() {
@Override
public void accept(@NonNull Integer integer) throws Exception {
L.i("rs===" + integer);
}
});
}
}
| UTF-8 | Java | 3,909 | java | MathActivity.java | Java | [
{
"context": "o.reactivex.functions.Consumer;\n\n/**\n * Created by zwy on 2017/9/18.\n * email:16681805@qq.com\n * 数学操作和聚合",
"end": 459,
"score": 0.9996569156646729,
"start": 456,
"tag": "USERNAME",
"value": "zwy"
},
{
"context": "er;\n\n/**\n * Created by zwy on 2017/9/18.\n * emai... | null | [] | package com.vst.rxjava20;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.Arrays;
import io.reactivex.Observable;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
/**
* Created by zwy on 2017/9/18.
* email:<EMAIL>
* 数学操作和聚合操作
*/
public class MathActivity extends Activity {
private ListView lv_main;
private String[] items = new String[]{"count", "reduce", "scan"};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
lv_main = (ListView) findViewById(R.id.lv_main);
lv_main.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, Arrays.asList(items)));
lv_main.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
count();
break;
case 1:
reduce();
break;
case 2:
scan();
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
case 7:
break;
}
}
});
}
/**
* 计算原始Observable发射物的数量,然后只发射这个值
*/
private void count() {
Observable.range(1, 10)
.count()
.subscribe(new Consumer<Long>() {
@Override
public void accept(@NonNull Long aLong) throws Exception {
L.i("count>>>" + aLong);
}
});
}
/**
* Reduce操作符应用一个函数接收Observable发射的数据和函数的计算结果作为下次计算的参数,输出最后的结果。
* 跟scan操作符很类似,只是scan会输出每次计算的结果,而reduce只会输出最后的结果。
*/
public void reduce() {
Observable.range(1, 10)
.reduce(new BiFunction<Integer, Integer, Integer>() {
@Override
public Integer apply(@NonNull Integer integer, @NonNull Integer integer2) throws Exception {
L.i(integer + ">>>>" + integer2);
return integer + integer2;
}
}).subscribe(new Consumer<Integer>() {
@Override
public void accept(@NonNull Integer integer) throws Exception {
L.i("subscribe>>>" + integer);
}
});
}
public void scan() {
//递加,每次递加都会发送结果
Observable.range(1, 10)
.scan(new BiFunction<Integer, Integer, Integer>() {
@Override
public Integer apply(@NonNull Integer sum, @NonNull Integer item) throws Exception {
return sum + item;
}
}).subscribe(new Consumer<Integer>() {
@Override
public void accept(@NonNull Integer integer) throws Exception {
L.i("rs===" + integer);
}
});
}
}
| 3,901 | 0.507203 | 0.496874 | 118 | 30.177965 | 24.471231 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.483051 | false | false | 9 |
eac03d76241928f69ce95b48f821d8d3e185d5ce | 20,306,605,437,113 | 6d978c0513a7c14cd783d69f21c11b9435e84df4 | /app/src/main/java/jnu/edu/timeapplication/Time.java | 00b2f9f78a5ac1efd33ea41ac53ffe5797cd3c96 | [] | no_license | d654321/iTime--finally | https://github.com/d654321/iTime--finally | 19bb0bd23c64b1603f3fff0291cc6220bfbbebd6 | d579dc65d63ce4e132ccca5ac0c7e6f697a74e13 | refs/heads/master | 2020-11-28T01:25:41.038000 | 2019-12-23T03:15:00 | 2019-12-23T03:15:00 | 229,668,002 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package jnu.edu.timeapplication;
import java.io.Serializable;
public class Time implements Serializable {
public Time(String title, int resourceId, String countdown) { //生成构造函数
this.setTitle(title);
this.setResourceId(resourceId);
this.setCountdown(countdown);
}
private String title; //日期加描述
private int resourceId;
public String getCountdown() {
return countdown;
}
public void setCountdown(String countdown) {
this.countdown = countdown;
}
private String countdown; //倒计时剩余时间
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getResourceId() {
return resourceId;
}
public void setResourceId(int resourceId) {
this.resourceId = resourceId;
}
}
| UTF-8 | Java | 896 | java | Time.java | Java | [] | null | [] | package jnu.edu.timeapplication;
import java.io.Serializable;
public class Time implements Serializable {
public Time(String title, int resourceId, String countdown) { //生成构造函数
this.setTitle(title);
this.setResourceId(resourceId);
this.setCountdown(countdown);
}
private String title; //日期加描述
private int resourceId;
public String getCountdown() {
return countdown;
}
public void setCountdown(String countdown) {
this.countdown = countdown;
}
private String countdown; //倒计时剩余时间
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getResourceId() {
return resourceId;
}
public void setResourceId(int resourceId) {
this.resourceId = resourceId;
}
}
| 896 | 0.645349 | 0.645349 | 40 | 20.5 | 18.637327 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 9 |
e070b83e6e293ba4b5aae6806da76a9723e9b151 | 9,861,244,955,978 | 3dedcfd4c1bb7cd819e06bc486d4fbeac50103ad | /Assign3/src/java/ser321/library/MediaLibraryInterface.java | af5ee6f1e1779c3624bfe95d1ed168c4a879a3b6 | [
"MIT",
"Apache-2.0"
] | permissive | christopher-henderson/SER_321 | https://github.com/christopher-henderson/SER_321 | 9832a1599a5ad8334968c529fffe3f9d9c18fee5 | 34cf94f40dd47f4409c90bf3b9985f3258c0ff18 | refs/heads/master | 2016-08-06T19:32:21.367000 | 2015-12-04T04:25:20 | 2015-12-04T04:25:20 | 41,100,470 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* The MIT License (MIT)
*
* Copyright (c) 2015 Christopher Henderson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Purpose: A media library server. Aggregates MediaDescriptions and provides
* access.
*
* Ser321 Foundations of Distributed Applications
* see http://pooh.poly.asu.edu/Ser321
*
* @author Christopher Henderson chris@chenderson.org
* Software Engineering
* @version 0.1.0
**/
package ser321.library;
import java.io.IOException;
import org.json.JSONObject;
import ser321.media.MediaDescription;
/**
* @author Christopher Henderson chris@chenderson.org
* @version 0.1.0
*/
public interface MediaLibraryInterface {
/**
* @return JSON string serialization of this MediaLibrary.
*/
public String toString();
/**
* @return JSONObject of the serialization of this MediaLibrary.
*/
public JSONObject toJSON();
/**
* @param aClip MediaDescription to add to this MediaLibrary.
* @return boolean Success status of the addition.
*/
public boolean add(MediaDescription aClip);
/**
* @param aClip Title of the MediaDescription to remove.
* @return boolean Success status of this removal.
*/
public boolean remove(String aClip);
/**
* @param filename Path to the file to write to.
* @throws IOException Catch all file IO exception.
*/
public void toJSONFile(String filename) throws IOException;
/**
* @param aTitle Title of the MediaDescription to retrieve.
* @return MediaDescription
*/
public MediaDescription get(String aTitle);
/**
* @return Array of all titles in this MediaLibrary.
*/
public String[] getTitles();
/**
* @return Array of all music titles in this MediaLibrary.
*/
public String[] getMusicTitles();
/**
* @return Array of all video titles in this MediaLibrary.
*/
public String[] getVideoTitles();
/**
* @param debug Debugging mode.
*/
public void setDebug(boolean debug);
}
| UTF-8 | Java | 3,034 | java | MediaLibraryInterface.java | Java | [
{
"context": "/**\n* The MIT License (MIT)\n*\n* Copyright (c) 2015 Christopher Henderson\n*\n* Permission is hereby granted, free of charge,",
"end": 72,
"score": 0.999903678894043,
"start": 51,
"tag": "NAME",
"value": "Christopher Henderson"
},
{
"context": "\n* see http://pooh.pol... | null | [] | /**
* The MIT License (MIT)
*
* Copyright (c) 2015 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Purpose: A media library server. Aggregates MediaDescriptions and provides
* access.
*
* Ser321 Foundations of Distributed Applications
* see http://pooh.poly.asu.edu/Ser321
*
* @author <NAME> <EMAIL>
* Software Engineering
* @version 0.1.0
**/
package ser321.library;
import java.io.IOException;
import org.json.JSONObject;
import ser321.media.MediaDescription;
/**
* @author <NAME> <EMAIL>
* @version 0.1.0
*/
public interface MediaLibraryInterface {
/**
* @return JSON string serialization of this MediaLibrary.
*/
public String toString();
/**
* @return JSONObject of the serialization of this MediaLibrary.
*/
public JSONObject toJSON();
/**
* @param aClip MediaDescription to add to this MediaLibrary.
* @return boolean Success status of the addition.
*/
public boolean add(MediaDescription aClip);
/**
* @param aClip Title of the MediaDescription to remove.
* @return boolean Success status of this removal.
*/
public boolean remove(String aClip);
/**
* @param filename Path to the file to write to.
* @throws IOException Catch all file IO exception.
*/
public void toJSONFile(String filename) throws IOException;
/**
* @param aTitle Title of the MediaDescription to retrieve.
* @return MediaDescription
*/
public MediaDescription get(String aTitle);
/**
* @return Array of all titles in this MediaLibrary.
*/
public String[] getTitles();
/**
* @return Array of all music titles in this MediaLibrary.
*/
public String[] getMusicTitles();
/**
* @return Array of all video titles in this MediaLibrary.
*/
public String[] getVideoTitles();
/**
* @param debug Debugging mode.
*/
public void setDebug(boolean debug);
}
| 2,963 | 0.706658 | 0.699407 | 101 | 29.039604 | 27.717787 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.356436 | false | false | 9 |
2d46f502e9a6f9430967357796826a5519145cfd | 9,861,244,952,618 | 3194a774dfa815eaa89b84fa82fdbdd27095300b | /src/main/java/havis/net/ui/middleware/client/shared/event/SpecChangedEvent.java | 332b5731da629db1e1215313997876af471a6a6e | [
"Apache-2.0"
] | permissive | menucha-de/Middleware.UI | https://github.com/menucha-de/Middleware.UI | 27e8fd74160c4fbe6d1d83f3df943f1678285004 | 0405009676c714405a95d593a5a3c4ed4644cfe4 | refs/heads/main | 2023-03-22T09:19:58.366000 | 2021-03-17T15:02:41 | 2021-03-17T15:02:41 | 348,751,041 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package havis.net.ui.middleware.client.shared.event;
import com.google.web.bindery.event.shared.Event;
import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.event.shared.HandlerRegistration;
public class SpecChangedEvent extends Event<SpecChangedEvent.Handler> {
public interface Handler {
void onSpecChanged(SpecChangedEvent event);
}
private static final Type<SpecChangedEvent.Handler> TYPE = new Type<SpecChangedEvent.Handler>();
public static HandlerRegistration register(EventBus eventBus, SpecChangedEvent.Handler handler) {
return eventBus.addHandler(TYPE, handler);
}
private String id;
public String getId() {
return id;
}
public SpecChangedEvent(String id) {
this.id = id;
}
public SpecChangedEvent(boolean failed, String message) {
}
@Override
public Type<SpecChangedEvent.Handler> getAssociatedType() {
return TYPE;
}
@Override
protected void dispatch(Handler handler) {
handler.onSpecChanged(this);
}
public static Type<SpecChangedEvent.Handler> getType() {
return TYPE;
}
}
| UTF-8 | Java | 1,063 | java | SpecChangedEvent.java | Java | [] | null | [] | package havis.net.ui.middleware.client.shared.event;
import com.google.web.bindery.event.shared.Event;
import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.event.shared.HandlerRegistration;
public class SpecChangedEvent extends Event<SpecChangedEvent.Handler> {
public interface Handler {
void onSpecChanged(SpecChangedEvent event);
}
private static final Type<SpecChangedEvent.Handler> TYPE = new Type<SpecChangedEvent.Handler>();
public static HandlerRegistration register(EventBus eventBus, SpecChangedEvent.Handler handler) {
return eventBus.addHandler(TYPE, handler);
}
private String id;
public String getId() {
return id;
}
public SpecChangedEvent(String id) {
this.id = id;
}
public SpecChangedEvent(boolean failed, String message) {
}
@Override
public Type<SpecChangedEvent.Handler> getAssociatedType() {
return TYPE;
}
@Override
protected void dispatch(Handler handler) {
handler.onSpecChanged(this);
}
public static Type<SpecChangedEvent.Handler> getType() {
return TYPE;
}
}
| 1,063 | 0.773283 | 0.773283 | 45 | 22.622223 | 27.387985 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.111111 | false | false | 9 |
5761cc34e443932423263b75956850c170f35136 | 10,436,770,563,249 | a9a03e4a263384e8b97b8b638ffe8d7f637f3934 | /dev/MyMaskModel/src/main/java/fr/annecy/pochat/production/mymaskmodel/typeZone.java | e74b90d2642e54308281b738505ff5ad7b2e44d6 | [] | no_license | m2cci-mohamed-limam/MyMaskWeb | https://github.com/m2cci-mohamed-limam/MyMaskWeb | 64602362cc43a520034ceeaf38e0e1dd7e6a0a5d | 97b0ae9559ccf9d8637f4ac9e9ac08c0a3bf1a10 | refs/heads/master | 2023-06-13T04:24:37.885000 | 2021-07-04T11:08:55 | 2021-07-04T11:08:55 | 382,829,063 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 fr.annecy.pochat.production.mymaskmodel;
/**
*
* @author limem
*/
public enum typeZone {
Date("Date"),
TexteFixe("TexteFixe"),
Nombre("Nombre"),
Prix("Prix"),
TexteVariable("TexteVariable"),
Poids("Poids"),
Code("Code"),
Graphique("Graphique");
private String label;
private typeZone(String label) {
this.label = label;
}
public String getLabel() {
return this.label;
}
}
| UTF-8 | Java | 641 | java | typeZone.java | Java | [
{
"context": ".pochat.production.mymaskmodel;\n\n/**\n *\n * @author limem\n */\npublic enum typeZone {\n\n Date(\"Date\"),\n ",
"end": 258,
"score": 0.9996613264083862,
"start": 253,
"tag": "USERNAME",
"value": "limem"
}
] | null | [] | /*
* 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 fr.annecy.pochat.production.mymaskmodel;
/**
*
* @author limem
*/
public enum typeZone {
Date("Date"),
TexteFixe("TexteFixe"),
Nombre("Nombre"),
Prix("Prix"),
TexteVariable("TexteVariable"),
Poids("Poids"),
Code("Code"),
Graphique("Graphique");
private String label;
private typeZone(String label) {
this.label = label;
}
public String getLabel() {
return this.label;
}
}
| 641 | 0.638066 | 0.638066 | 32 | 19.03125 | 18.648869 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.46875 | false | false | 9 |
197354639a60c6e1ab3877f3e8f4f25513fb9c29 | 10,436,770,562,112 | 05a06704238d81a8ec4cec9727fa27fbe8e79515 | /src/jets/Fleet.java | 259d510f9e53340e6250bd0ba13f00732005060a | [] | no_license | JosiahDM/Jets | https://github.com/JosiahDM/Jets | eb54c2c455368f099600cacfa68de4a85ec66789 | c4b6912fa924f373f76c6b68249dc99e4154d7b8 | refs/heads/master | 2021-01-09T20:23:18.127000 | 2016-07-31T22:55:20 | 2016-07-31T22:55:20 | 64,512,240 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package jets;
public class Fleet {
private Jet[] jetsArray;
private String name;
private Pilot[] pilots;
public Fleet(String name, Jet[] jetsArray) {
this.name = name;
this.jetsArray = jetsArray;
}
public Fleet(String name, Jet[] jetsArray, Pilot[] pilots) {
this.name = name;
this.jetsArray = jetsArray;
this.pilots = pilots;
this.assignRandomPilots();
}
// Methods
// List fleet prints out the model, speed, range, and price of each jet in fleet.
public void listFleet() {
System.out.println("*********** Display Fleet ***********");
printHeader();
for (Jet jet : jetsArray) {
jet.display();
}
}
// The view fastest jet and longest range options both print out all of
// the information about their jets.
public void viewFastest() {
float fastest = 0.0F;
Jet fastestJet = null;
for (Jet jet : jetsArray) {
if (jet.getSpeed() > fastest) {
fastest = jet.getSpeed();
fastestJet = jet;
}
}
System.out.println("*** Fastest jet in the fleet ***");
System.out.println("*************************************************");
printHeader();
fastestJet.display();
System.out.println();
}
public void viewLongestRange() {
int range = 0;
Jet longestRange = null;
for (Jet jet : jetsArray) {
if (jet.getRange() > range) {
range = jet.getRange();
longestRange = jet;
}
}
System.out.println("*** Longest ranged jet in the fleet ***");
System.out.println("*************************************************");
printHeader();
longestRange.display();
System.out.println();
}
// A user can add custom jets to the fleet.
public void addJet(Jet jet) {
Jet[] newJetsArray = new Jet[this.jetsArray.length + 1];
for (int i = 0; i < this.jetsArray.length; i++) {
newJetsArray[i] = this.jetsArray[i];
}
newJetsArray[newJetsArray.length-1] = jet;
this.jetsArray = newJetsArray;
}
// Loops through the array of jets, adds a random pilot to jets.
public void assignRandomPilots() {
int count = 0;
while (count < this.jetsArray.length && count < this.pilots.length) {
int randomPilotIndex = (int)(Math.random() * this.pilots.length);
boolean currentPilotAlreadyAssigned = this.pilots[randomPilotIndex].getAssignedToJet();
// Only assign the randomly chosen pilot if it isn't already assigned to a jet
if (currentPilotAlreadyAssigned == false) {
this.jetsArray[count].setPilot(this.pilots[randomPilotIndex]);
this.pilots[randomPilotIndex].setAssignedToJet(true);
count++;
}
}
}
// Add a pilot to Fleet
public void addPilot(Pilot pilot) {
Pilot[] newPilotsArray = new Pilot[this.pilots.length + 1];
for (int i = 0; i < this.pilots.length; i++) {
newPilotsArray[i] = this.pilots[i];
}
newPilotsArray[newPilotsArray.length-1] = pilot;
this.pilots = newPilotsArray;
}
public void listPilots() {
System.out.printf("%-30s %-10s %-20s\n", "Name", "Age", "Pay Grade");
for (Pilot pilot : this.pilots) {
System.out.printf("%-30s %-10s %-20s\n", pilot.getName(), pilot.getAge(), pilot.getPayGrade());
}
}
public void setPilots(Pilot[] pilots) {
this.pilots = pilots;
}
public Pilot[] getPilots() {
return this.pilots;
}
public void printHeader() {
System.out.printf("%-5s %-30s %-20s %-15s %-10s %-15s\n", "ID", "Pilot", "Model", "Speed", "Range(mi)", "Price");
}
// Getters and Setters
public Jet[] getJetsArray() {
return jetsArray;
}
public void setJetsArray(Jet[] jetsArray) {
this.jetsArray = jetsArray;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| UTF-8 | Java | 3,668 | java | Fleet.java | Java | [] | null | [] | package jets;
public class Fleet {
private Jet[] jetsArray;
private String name;
private Pilot[] pilots;
public Fleet(String name, Jet[] jetsArray) {
this.name = name;
this.jetsArray = jetsArray;
}
public Fleet(String name, Jet[] jetsArray, Pilot[] pilots) {
this.name = name;
this.jetsArray = jetsArray;
this.pilots = pilots;
this.assignRandomPilots();
}
// Methods
// List fleet prints out the model, speed, range, and price of each jet in fleet.
public void listFleet() {
System.out.println("*********** Display Fleet ***********");
printHeader();
for (Jet jet : jetsArray) {
jet.display();
}
}
// The view fastest jet and longest range options both print out all of
// the information about their jets.
public void viewFastest() {
float fastest = 0.0F;
Jet fastestJet = null;
for (Jet jet : jetsArray) {
if (jet.getSpeed() > fastest) {
fastest = jet.getSpeed();
fastestJet = jet;
}
}
System.out.println("*** Fastest jet in the fleet ***");
System.out.println("*************************************************");
printHeader();
fastestJet.display();
System.out.println();
}
public void viewLongestRange() {
int range = 0;
Jet longestRange = null;
for (Jet jet : jetsArray) {
if (jet.getRange() > range) {
range = jet.getRange();
longestRange = jet;
}
}
System.out.println("*** Longest ranged jet in the fleet ***");
System.out.println("*************************************************");
printHeader();
longestRange.display();
System.out.println();
}
// A user can add custom jets to the fleet.
public void addJet(Jet jet) {
Jet[] newJetsArray = new Jet[this.jetsArray.length + 1];
for (int i = 0; i < this.jetsArray.length; i++) {
newJetsArray[i] = this.jetsArray[i];
}
newJetsArray[newJetsArray.length-1] = jet;
this.jetsArray = newJetsArray;
}
// Loops through the array of jets, adds a random pilot to jets.
public void assignRandomPilots() {
int count = 0;
while (count < this.jetsArray.length && count < this.pilots.length) {
int randomPilotIndex = (int)(Math.random() * this.pilots.length);
boolean currentPilotAlreadyAssigned = this.pilots[randomPilotIndex].getAssignedToJet();
// Only assign the randomly chosen pilot if it isn't already assigned to a jet
if (currentPilotAlreadyAssigned == false) {
this.jetsArray[count].setPilot(this.pilots[randomPilotIndex]);
this.pilots[randomPilotIndex].setAssignedToJet(true);
count++;
}
}
}
// Add a pilot to Fleet
public void addPilot(Pilot pilot) {
Pilot[] newPilotsArray = new Pilot[this.pilots.length + 1];
for (int i = 0; i < this.pilots.length; i++) {
newPilotsArray[i] = this.pilots[i];
}
newPilotsArray[newPilotsArray.length-1] = pilot;
this.pilots = newPilotsArray;
}
public void listPilots() {
System.out.printf("%-30s %-10s %-20s\n", "Name", "Age", "Pay Grade");
for (Pilot pilot : this.pilots) {
System.out.printf("%-30s %-10s %-20s\n", pilot.getName(), pilot.getAge(), pilot.getPayGrade());
}
}
public void setPilots(Pilot[] pilots) {
this.pilots = pilots;
}
public Pilot[] getPilots() {
return this.pilots;
}
public void printHeader() {
System.out.printf("%-5s %-30s %-20s %-15s %-10s %-15s\n", "ID", "Pilot", "Model", "Speed", "Range(mi)", "Price");
}
// Getters and Setters
public Jet[] getJetsArray() {
return jetsArray;
}
public void setJetsArray(Jet[] jetsArray) {
this.jetsArray = jetsArray;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 3,668 | 0.627863 | 0.618866 | 139 | 25.388489 | 24.935747 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.223022 | false | false | 9 |
be642ae240e734d0f2ab93c72dd9b03adaa89a10 | 21,947,282,897,598 | dddf2a6920293827b861a4c67a255e23ca1581ec | /SSH2EShopping/src/com/bindong/shop/dao/AccountDao.java | 467e06fd2f85f0f0cf56baf6efe08115507b863b | [] | no_license | coolfire8850/E-commerce-site | https://github.com/coolfire8850/E-commerce-site | 93ceaf113bb5ad9fea4ae58a28dbd7a86fc534a2 | 1f9f55c64e2e6acf9f7ba0bda8ee64b93cc51553 | refs/heads/master | 2020-07-07T09:25:06.809000 | 2016-11-17T21:42:49 | 2016-11-17T21:42:49 | 74,037,749 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bindong.shop.dao;
import com.bindong.shop.model.Account;
public interface AccountDao extends BaseDao<Account> {
}
| UTF-8 | Java | 136 | java | AccountDao.java | Java | [] | null | [] | package com.bindong.shop.dao;
import com.bindong.shop.model.Account;
public interface AccountDao extends BaseDao<Account> {
}
| 136 | 0.75 | 0.75 | 7 | 17.428572 | 20.961578 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 9 |
aa667c7b08e96b9d8d9f822ee6b969959ba2787f | 8,452,495,693,675 | dfd5f04219572c678aa20717ac5f8b25053275ae | /ss-model/src/main/java/ro/unitbv/servicesupplier/model/communication/response/success/common/SubscriptionsResponse.java | 12813f94bdd1f78240035abd6a0242f62def465d | [] | no_license | paulhristea/service-supplier-app | https://github.com/paulhristea/service-supplier-app | 0ae50d5554fc1dd2597ada7992ee09fb83d64acd | 9a4275bc853a961cf6fbe5c5640a65f094fcc785 | refs/heads/master | 2021-06-01T03:15:31.975000 | 2016-05-24T00:00:55 | 2016-05-24T00:00:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ro.unitbv.servicesupplier.model.communication.response.success.common;
import ro.unitbv.servicesupplier.model.communication.response.success.SuccessResponse;
import ro.unitbv.servicesupplier.model.dto.SubscriptionDto;
import java.io.Serializable;
import java.util.List;
/**
* Created by Petri on 16-May-16.
*/
public class SubscriptionsResponse extends SuccessResponse implements Serializable {
private List<SubscriptionDto> subscriptions;
public SubscriptionsResponse(List<SubscriptionDto> subscriptions) {
super("Subscriptions retrieved successfully.");
this.subscriptions = subscriptions;
}
public List<SubscriptionDto> getSubscriptions() {
return subscriptions;
}
}
| UTF-8 | Java | 719 | java | SubscriptionsResponse.java | Java | [
{
"context": "lizable;\nimport java.util.List;\n\n/**\n * Created by Petri on 16-May-16.\n */\npublic class SubscriptionsRespo",
"end": 304,
"score": 0.9992681741714478,
"start": 299,
"tag": "NAME",
"value": "Petri"
}
] | null | [] | package ro.unitbv.servicesupplier.model.communication.response.success.common;
import ro.unitbv.servicesupplier.model.communication.response.success.SuccessResponse;
import ro.unitbv.servicesupplier.model.dto.SubscriptionDto;
import java.io.Serializable;
import java.util.List;
/**
* Created by Petri on 16-May-16.
*/
public class SubscriptionsResponse extends SuccessResponse implements Serializable {
private List<SubscriptionDto> subscriptions;
public SubscriptionsResponse(List<SubscriptionDto> subscriptions) {
super("Subscriptions retrieved successfully.");
this.subscriptions = subscriptions;
}
public List<SubscriptionDto> getSubscriptions() {
return subscriptions;
}
}
| 719 | 0.787204 | 0.781641 | 24 | 28.958334 | 29.81258 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 12 |
83f9f873c2c3f49dc2a29f0dfaf4aff88130ea89 | 8,452,495,692,959 | d3658fc34315802143a236c6fdabd4fd1be47aad | /src/main/java/com/facebook/coolpay/rs/exception/CoolpayInvalidLoginException.java | 52731f512e5214037c5a99b0b03491a52ba82e2f | [] | no_license | kgiove/coolpay-backend-demo | https://github.com/kgiove/coolpay-backend-demo | da534740134b6a5fde229467458af01df6c37a95 | 04261dd02f2626bc7b98a17ca6520ddb7b0816b8 | refs/heads/master | 2021-08-10T20:26:06.509000 | 2017-11-12T23:42:53 | 2017-11-12T23:42:53 | 109,608,730 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.facebook.coolpay.rs.exception;
import javax.ws.rs.WebApplicationException;
/**
* @author KGiove
*/
public class CoolpayInvalidLoginException extends WebApplicationException {
private static final long serialVersionUID = 1L;
public CoolpayInvalidLoginException(String message, Throwable e, int status) {
super(message, e, status);
}
public CoolpayInvalidLoginException(String message) {
super(message);
}
}
| UTF-8 | Java | 466 | java | CoolpayInvalidLoginException.java | Java | [
{
"context": "vax.ws.rs.WebApplicationException;\n\n/**\n * @author KGiove\n */\npublic class CoolpayInvalidLoginException ext",
"end": 110,
"score": 0.9737940430641174,
"start": 104,
"tag": "USERNAME",
"value": "KGiove"
}
] | null | [] | package com.facebook.coolpay.rs.exception;
import javax.ws.rs.WebApplicationException;
/**
* @author KGiove
*/
public class CoolpayInvalidLoginException extends WebApplicationException {
private static final long serialVersionUID = 1L;
public CoolpayInvalidLoginException(String message, Throwable e, int status) {
super(message, e, status);
}
public CoolpayInvalidLoginException(String message) {
super(message);
}
}
| 466 | 0.727468 | 0.725322 | 18 | 24.888889 | 26.689342 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.888889 | false | false | 12 |
ec51d4869a8e5423207dac31304ee49fcfafae01 | 16,939,351,081,252 | f618552f6e801ea057fa613c35449ce0bbc82f7b | /common/src/com/icomp/dao/VgetequipmentlistDao.java | f4efd8568a09a0d09ab7562f51d0143da3bd6e31 | [] | no_license | looooogan/icomp-mq200-server | https://github.com/looooogan/icomp-mq200-server | 0bea17befbcf9c69ff51de7673a96a1879305137 | 2ec877d1687a763a0fb8f8cfc0a3683f5460a868 | refs/heads/master | 2020-03-17T20:12:31.375000 | 2018-05-18T03:32:10 | 2018-05-18T03:32:10 | 133,898,307 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 工具自动生成:VIEWDAO接口
* 生成时间 : 2016/02/24 08:13:26
*/
package com.icomp.dao;
import com.icomp.common.dao.BaseViewDao;
/**
* 继承父接口
* @author 工具自动生成
* 创建者 :yzq
* 更新者 :taoyy
*
*/
public interface VgetequipmentlistDao extends BaseViewDao{
}
| UTF-8 | Java | 321 | java | VgetequipmentlistDao.java | Java | [
{
"context": "mmon.dao.BaseViewDao;\n\n\n/**\n * 继承父接口\n * @author 工具自动生成\n * 创建者 :yzq\n * 更新者 :taoyy\n *\n */\npublic interfa",
"end": 157,
"score": 0.9276536107063293,
"start": 153,
"tag": "USERNAME",
"value": "自动生成"
},
{
"context": "iewDao;\n\n\n/**\n * 继承父接口\n * @author 工具自动生成\... | null | [] | /*
* 工具自动生成:VIEWDAO接口
* 生成时间 : 2016/02/24 08:13:26
*/
package com.icomp.dao;
import com.icomp.common.dao.BaseViewDao;
/**
* 继承父接口
* @author 工具自动生成
* 创建者 :yzq
* 更新者 :taoyy
*
*/
public interface VgetequipmentlistDao extends BaseViewDao{
}
| 321 | 0.657588 | 0.603113 | 20 | 11.8 | 15.455096 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.1 | false | false | 12 |
3c16f86c19eddc18ad661b99cedbbabe95e53423 | 23,467,701,306,457 | 53999548ab13cbfcd3fb37affd277ecdf4e71ad9 | /src/com/nxy/controller/UserController.java | 2ceda5c11accb2f181ff151561d9ba0cfcd1bc2f | [] | no_license | CSU-NXY/94train | https://github.com/CSU-NXY/94train | d82051d12a7b5188214f19ac7261386a05174bce | ec8c10b21407969f934673036d368dc1043c621c | refs/heads/master | 2021-01-23T22:30:59.047000 | 2017-09-27T08:13:09 | 2017-09-27T08:13:09 | 102,938,211 | 2 | 8 | null | false | 2017-09-27T02:28:48 | 2017-09-09T08:10:42 | 2017-09-10T09:27:49 | 2017-09-27T02:28:47 | 17,005 | 0 | 4 | 0 | Java | null | null | package com.nxy.controller;
import com.nxy.model.User;
import com.xgh.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
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.servlet.mvc.support.RedirectAttributesModelMap;
import javax.servlet.http.HttpSession;
import com.nxy.model.Order;
import com.xgh.service.OrderService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.List;
/**
* Created by Monarch on 2017/9/17.
*/
@Controller
@RequestMapping(value = "/user", method = RequestMethod.GET)
public class UserController {
@RequestMapping(value = "/viewUserInfo.do", method = RequestMethod.GET)
public String viewUser_information(ModelMap model, HttpSession session)
{
User user = UserService.GetUserByUserID((int)session.getAttribute("S_UserID"));
model.addAttribute("UserID",user.getUserID());
model.addAttribute("Name",user.getName());
model.addAttribute("PhoneNum",user.getPhoneNum());
model.addAttribute("Email",user.getEmail());
model.addAttribute("ID",user.getID());
return "User_information";
}
@RequestMapping(value="/ChangeEmail.do",method = RequestMethod.POST)
public String ChangeEmail(@RequestParam("Email") String email,HttpSession session,RedirectAttributesModelMap modelMap)
{
int id = (int)session.getAttribute("S_UserID");
boolean result = UserService.ChangeEmail(id,email);
if(result)
{
modelMap.addFlashAttribute("Msg_S","更改Email成功");
}
else
{
modelMap.addFlashAttribute("Msg_F","更改Email失败");
}
return "redirect:/user/viewUserInfo.do";
}
@RequestMapping(value="/ChangePassword.do",method = RequestMethod.POST)
public String ChangePassword(@RequestParam("NewPassword") String newPassword,@RequestParam("OldPassword")String oldPassword,HttpSession session,RedirectAttributesModelMap modelMap)
{
int id = (int)session.getAttribute("S_UserID");
boolean result = UserService.ChangePassword(id,newPassword,oldPassword);
if(result)
{
modelMap.addFlashAttribute("Msg_S","更改密码成功");
}
else
{
modelMap.addFlashAttribute("Msg_F","更改密码失败");
}
return "redirect:/user/viewUserInfo.do";
}
@RequestMapping(value = "/viewBuyTickets.do",method = RequestMethod.GET)
public String viewBuyTickets(ModelMap model)
{ return "BuyTickets";}
@RequestMapping(value = "/viewOrderPay.do",method = RequestMethod.GET)
public String viewOrderPay(ModelMap model)
{ return "OrderPay";}
@ResponseBody
@RequestMapping(value = "/viewOrder.do",method = RequestMethod.POST)
public List<Order> viewOrder2(HttpSession session,HttpServletResponse response) throws Exception{
int id = (int)session.getAttribute("S_UserID");
List<Order> list = OrderService.FindOrder(id);
return list;
}
}
| UTF-8 | Java | 3,600 | java | UserController.java | Java | [
{
"context": "Writer;\nimport java.util.List;\n\n\n/**\n * Created by Monarch on 2017/9/17.\n */\n\n@Controller\n@RequestMapping(va",
"end": 1029,
"score": 0.973114013671875,
"start": 1022,
"tag": "NAME",
"value": "Monarch"
}
] | null | [] | package com.nxy.controller;
import com.nxy.model.User;
import com.xgh.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
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.servlet.mvc.support.RedirectAttributesModelMap;
import javax.servlet.http.HttpSession;
import com.nxy.model.Order;
import com.xgh.service.OrderService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.List;
/**
* Created by Monarch on 2017/9/17.
*/
@Controller
@RequestMapping(value = "/user", method = RequestMethod.GET)
public class UserController {
@RequestMapping(value = "/viewUserInfo.do", method = RequestMethod.GET)
public String viewUser_information(ModelMap model, HttpSession session)
{
User user = UserService.GetUserByUserID((int)session.getAttribute("S_UserID"));
model.addAttribute("UserID",user.getUserID());
model.addAttribute("Name",user.getName());
model.addAttribute("PhoneNum",user.getPhoneNum());
model.addAttribute("Email",user.getEmail());
model.addAttribute("ID",user.getID());
return "User_information";
}
@RequestMapping(value="/ChangeEmail.do",method = RequestMethod.POST)
public String ChangeEmail(@RequestParam("Email") String email,HttpSession session,RedirectAttributesModelMap modelMap)
{
int id = (int)session.getAttribute("S_UserID");
boolean result = UserService.ChangeEmail(id,email);
if(result)
{
modelMap.addFlashAttribute("Msg_S","更改Email成功");
}
else
{
modelMap.addFlashAttribute("Msg_F","更改Email失败");
}
return "redirect:/user/viewUserInfo.do";
}
@RequestMapping(value="/ChangePassword.do",method = RequestMethod.POST)
public String ChangePassword(@RequestParam("NewPassword") String newPassword,@RequestParam("OldPassword")String oldPassword,HttpSession session,RedirectAttributesModelMap modelMap)
{
int id = (int)session.getAttribute("S_UserID");
boolean result = UserService.ChangePassword(id,newPassword,oldPassword);
if(result)
{
modelMap.addFlashAttribute("Msg_S","更改密码成功");
}
else
{
modelMap.addFlashAttribute("Msg_F","更改密码失败");
}
return "redirect:/user/viewUserInfo.do";
}
@RequestMapping(value = "/viewBuyTickets.do",method = RequestMethod.GET)
public String viewBuyTickets(ModelMap model)
{ return "BuyTickets";}
@RequestMapping(value = "/viewOrderPay.do",method = RequestMethod.GET)
public String viewOrderPay(ModelMap model)
{ return "OrderPay";}
@ResponseBody
@RequestMapping(value = "/viewOrder.do",method = RequestMethod.POST)
public List<Order> viewOrder2(HttpSession session,HttpServletResponse response) throws Exception{
int id = (int)session.getAttribute("S_UserID");
List<Order> list = OrderService.FindOrder(id);
return list;
}
}
| 3,600 | 0.716854 | 0.714607 | 99 | 34.959595 | 31.614445 | 184 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.717172 | false | false | 12 |
582a052fe97a9d0d71b929c39d0253ba55d477d6 | 5,927,054,931,665 | c5e3cb259bbd9cc1d732c06664f7efa5ea5b5eda | /pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/pubsub/UpdateWorkflowStatusTest.java | f0b5a8f4d65851056b1e20071d34c19abe991aae | [
"BSD-3-Clause"
] | permissive | broadinstitute/ddp-study-server | https://github.com/broadinstitute/ddp-study-server | c7f69a0576f27f0e75955421d8bfc0cb1154b41e | 8709557b32bac942e227eaa1029477771562d47a | refs/heads/develop | 2023-09-01T02:22:28.228000 | 2023-08-31T21:03:45 | 2023-08-31T21:03:45 | 224,263,376 | 12 | 6 | BSD-3-Clause | false | 2023-09-14T16:55:00 | 2019-11-26T18:49:36 | 2023-08-04T13:55:18 | 2023-09-14T16:54:59 | 187,168 | 8 | 4 | 14 | Java | false | false | package org.broadinstitute.dsm.pubsub;
import static org.broadinstitute.dsm.pubsub.WorkflowStatusUpdate.MEMBER_TYPE;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.broadinstitute.dsm.DbTxnBaseTest;
import org.broadinstitute.dsm.db.dao.ddp.instance.DDPInstanceDao;
import org.broadinstitute.dsm.db.dao.ddp.participant.ParticipantDataDao;
import org.broadinstitute.dsm.db.dao.settings.FieldSettingsDao;
import org.broadinstitute.dsm.db.dao.user.UserDao;
import org.broadinstitute.dsm.db.dto.ddp.instance.DDPInstanceDto;
import org.broadinstitute.dsm.db.dto.ddp.participant.ParticipantData;
import org.broadinstitute.dsm.db.dto.settings.FieldSettingsDto;
import org.broadinstitute.dsm.db.dto.user.UserDto;
import org.broadinstitute.dsm.route.EditParticipantPublisherRoute;
import org.broadinstitute.dsm.util.DBTestUtil;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
@Slf4j
public class UpdateWorkflowStatusTest extends DbTxnBaseTest {
public static final String UPDATE_WORKFLOW_TEST = "UpdateWorkflowTest";
public static final String fieldTypeId = UPDATE_WORKFLOW_TEST;
private static final DDPInstanceDao ddpInstanceDao = new DDPInstanceDao();
private static final FieldSettingsDao fieldSettingsDao = FieldSettingsDao.of();
private static final UserDao userDao = new UserDao();
private static final ParticipantDataDao participantDataDao = new ParticipantDataDao();
private static Gson gson;
private static UserDto userDto;
private static DDPInstanceDto ddpInstanceDto;
private static String instanceName;
private static int fieldSettingsId;
@BeforeClass
public static void setup() {
gson = new Gson();
instanceName = String.format("%s_%d", UPDATE_WORKFLOW_TEST, Instant.now().toEpochMilli());
ddpInstanceDto = DBTestUtil.createTestDdpInstance(ddpInstanceDao, instanceName);
userDto = DBTestUtil.createTestDsmUser("UpdateWorkflowUser", "UpdateWorkflow@status.com", userDao, userDto);
createFieldSettings();
}
@AfterClass
public static void tearDown() {
if (fieldSettingsId > 0) {
fieldSettingsDao.delete(fieldSettingsId);
}
userDao.delete(userDto.getId());
ddpInstanceDao.delete(ddpInstanceDto.getDdpInstanceId());
}
private static ParticipantData createParticipantData(String participantIdSeed) {
Map<String, String> participantDataMap = new HashMap<>();
participantDataMap.put("REGISTRATION_STATUS", "REGISTERED");
participantDataMap.put("MEMBER_TYPE", "SELF");
String participantId = genParticipantId(participantIdSeed);
ParticipantData participantData = new ParticipantData.Builder()
.withDdpParticipantId(participantId).withDdpInstanceId(ddpInstanceDto.getDdpInstanceId())
.withFieldTypeId(fieldTypeId).withData(gson.toJson(participantDataMap))
.withLastChanged(System.currentTimeMillis()).withChangedBy(userDto.getEmail().orElse("")).build();
participantData.setParticipantDataId(participantDataDao.create(participantData));
return participantData;
}
private static String genParticipantId(String seed) {
return String.format("WorkflowUpdateStatusTest_%s_%d", seed, Instant.now().toEpochMilli());
}
private static void deleteParticipantData(int participantDataId) {
if (participantDataId >= 0) {
participantDataDao.delete(participantDataId);
}
}
private static void createFieldSettings() {
FieldSettingsDto fieldSettingsDto = new FieldSettingsDto.Builder(ddpInstanceDto.getDdpInstanceId())
.withFieldType(fieldTypeId)
.withColumnName(MEMBER_TYPE).build();
fieldSettingsId = FieldSettingsDao.of().create(fieldSettingsDto);
}
@Test
public void testUpdateCustomWorkflow() {
ParticipantData participantData = createParticipantData("ucf");
int participantDataId = participantData.getParticipantDataId();
String participantId = participantData.getDdpParticipantId().orElseThrow();
try {
String messageData = String.format("{\"participantGuid\":\"%s\",\"instanceName\":\"%s\","
+ "\"data\":{\"workflow\":\"%s\",\"status\":\"COMPLETED\"}}",
participantId, instanceName, MEMBER_TYPE);
JsonObject messageJsonObject = new Gson().fromJson(messageData, JsonObject.class);
String dataString = messageJsonObject.get("data").getAsJsonObject().toString();
Map<String, String> attributeMap = EditParticipantPublisherRoute.getStringStringMap("TEST", messageJsonObject);
WorkflowStatusUpdate.updateCustomWorkflow(attributeMap, dataString);
String data = participantDataDao.get(participantDataId).orElseThrow().getData().orElseThrow();
JsonObject dataJsonObject = gson.fromJson(data, JsonObject.class);
//checking that value was updated
Assert.assertEquals("COMPLETED", dataJsonObject.get("MEMBER_TYPE").getAsString());
//checking that updated value did not remove other fields
Assert.assertEquals("REGISTERED", dataJsonObject.get("REGISTRATION_STATUS").getAsString());
} finally {
deleteParticipantData(participantDataId);
}
}
@Test
public void testUpdateProbandStatus() {
ParticipantData participantData = createParticipantData("ups");
int participantDataId = participantData.getParticipantDataId();
try {
String workflow = "REGISTRATION_STATUS";
String status = "ENROLLED";
String fieldType = participantData.getFieldTypeId().orElseThrow();
WorkflowStatusUpdate.updateProbandStatus(workflow, status, participantData, fieldType);
String data = participantDataDao.get(participantDataId).orElseThrow().getData().orElseThrow();
JsonObject dataJsonObject = gson.fromJson(data, JsonObject.class);
Assert.assertEquals(status, dataJsonObject.get(workflow).getAsString());
} finally {
deleteParticipantData(participantDataId);
}
}
@Test
public void testCreateParticipantData() {
int participantDataId = -1;
try {
String workflow = "REGISTRATION_TYPE";
String status = "SELF2";
participantDataId = WorkflowStatusUpdate.createParticipantData(workflow, status,
genParticipantId("anp"), ddpInstanceDto.getDdpInstanceId(), fieldTypeId);
String data = participantDataDao.get(participantDataId).orElseThrow().getData().orElse("");
JsonObject dataJsonObject = gson.fromJson(data, JsonObject.class);
Assert.assertEquals(status, dataJsonObject.get(workflow).getAsString());
} finally {
deleteParticipantData(participantDataId);
}
}
}
| UTF-8 | Java | 7,137 | java | UpdateWorkflowStatusTest.java | Java | [
{
"context": ";\n userDto = DBTestUtil.createTestDsmUser(\"UpdateWorkflowUser\", \"UpdateWorkflow@status.com\", userDao, userDto);",
"end": 2119,
"score": 0.9582603573799133,
"start": 2101,
"tag": "USERNAME",
"value": "UpdateWorkflowUser"
},
{
"context": "TestUtil.createTestDs... | null | [] | package org.broadinstitute.dsm.pubsub;
import static org.broadinstitute.dsm.pubsub.WorkflowStatusUpdate.MEMBER_TYPE;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.broadinstitute.dsm.DbTxnBaseTest;
import org.broadinstitute.dsm.db.dao.ddp.instance.DDPInstanceDao;
import org.broadinstitute.dsm.db.dao.ddp.participant.ParticipantDataDao;
import org.broadinstitute.dsm.db.dao.settings.FieldSettingsDao;
import org.broadinstitute.dsm.db.dao.user.UserDao;
import org.broadinstitute.dsm.db.dto.ddp.instance.DDPInstanceDto;
import org.broadinstitute.dsm.db.dto.ddp.participant.ParticipantData;
import org.broadinstitute.dsm.db.dto.settings.FieldSettingsDto;
import org.broadinstitute.dsm.db.dto.user.UserDto;
import org.broadinstitute.dsm.route.EditParticipantPublisherRoute;
import org.broadinstitute.dsm.util.DBTestUtil;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
@Slf4j
public class UpdateWorkflowStatusTest extends DbTxnBaseTest {
public static final String UPDATE_WORKFLOW_TEST = "UpdateWorkflowTest";
public static final String fieldTypeId = UPDATE_WORKFLOW_TEST;
private static final DDPInstanceDao ddpInstanceDao = new DDPInstanceDao();
private static final FieldSettingsDao fieldSettingsDao = FieldSettingsDao.of();
private static final UserDao userDao = new UserDao();
private static final ParticipantDataDao participantDataDao = new ParticipantDataDao();
private static Gson gson;
private static UserDto userDto;
private static DDPInstanceDto ddpInstanceDto;
private static String instanceName;
private static int fieldSettingsId;
@BeforeClass
public static void setup() {
gson = new Gson();
instanceName = String.format("%s_%d", UPDATE_WORKFLOW_TEST, Instant.now().toEpochMilli());
ddpInstanceDto = DBTestUtil.createTestDdpInstance(ddpInstanceDao, instanceName);
userDto = DBTestUtil.createTestDsmUser("UpdateWorkflowUser", "<EMAIL>", userDao, userDto);
createFieldSettings();
}
@AfterClass
public static void tearDown() {
if (fieldSettingsId > 0) {
fieldSettingsDao.delete(fieldSettingsId);
}
userDao.delete(userDto.getId());
ddpInstanceDao.delete(ddpInstanceDto.getDdpInstanceId());
}
private static ParticipantData createParticipantData(String participantIdSeed) {
Map<String, String> participantDataMap = new HashMap<>();
participantDataMap.put("REGISTRATION_STATUS", "REGISTERED");
participantDataMap.put("MEMBER_TYPE", "SELF");
String participantId = genParticipantId(participantIdSeed);
ParticipantData participantData = new ParticipantData.Builder()
.withDdpParticipantId(participantId).withDdpInstanceId(ddpInstanceDto.getDdpInstanceId())
.withFieldTypeId(fieldTypeId).withData(gson.toJson(participantDataMap))
.withLastChanged(System.currentTimeMillis()).withChangedBy(userDto.getEmail().orElse("")).build();
participantData.setParticipantDataId(participantDataDao.create(participantData));
return participantData;
}
private static String genParticipantId(String seed) {
return String.format("WorkflowUpdateStatusTest_%s_%d", seed, Instant.now().toEpochMilli());
}
private static void deleteParticipantData(int participantDataId) {
if (participantDataId >= 0) {
participantDataDao.delete(participantDataId);
}
}
private static void createFieldSettings() {
FieldSettingsDto fieldSettingsDto = new FieldSettingsDto.Builder(ddpInstanceDto.getDdpInstanceId())
.withFieldType(fieldTypeId)
.withColumnName(MEMBER_TYPE).build();
fieldSettingsId = FieldSettingsDao.of().create(fieldSettingsDto);
}
@Test
public void testUpdateCustomWorkflow() {
ParticipantData participantData = createParticipantData("ucf");
int participantDataId = participantData.getParticipantDataId();
String participantId = participantData.getDdpParticipantId().orElseThrow();
try {
String messageData = String.format("{\"participantGuid\":\"%s\",\"instanceName\":\"%s\","
+ "\"data\":{\"workflow\":\"%s\",\"status\":\"COMPLETED\"}}",
participantId, instanceName, MEMBER_TYPE);
JsonObject messageJsonObject = new Gson().fromJson(messageData, JsonObject.class);
String dataString = messageJsonObject.get("data").getAsJsonObject().toString();
Map<String, String> attributeMap = EditParticipantPublisherRoute.getStringStringMap("TEST", messageJsonObject);
WorkflowStatusUpdate.updateCustomWorkflow(attributeMap, dataString);
String data = participantDataDao.get(participantDataId).orElseThrow().getData().orElseThrow();
JsonObject dataJsonObject = gson.fromJson(data, JsonObject.class);
//checking that value was updated
Assert.assertEquals("COMPLETED", dataJsonObject.get("MEMBER_TYPE").getAsString());
//checking that updated value did not remove other fields
Assert.assertEquals("REGISTERED", dataJsonObject.get("REGISTRATION_STATUS").getAsString());
} finally {
deleteParticipantData(participantDataId);
}
}
@Test
public void testUpdateProbandStatus() {
ParticipantData participantData = createParticipantData("ups");
int participantDataId = participantData.getParticipantDataId();
try {
String workflow = "REGISTRATION_STATUS";
String status = "ENROLLED";
String fieldType = participantData.getFieldTypeId().orElseThrow();
WorkflowStatusUpdate.updateProbandStatus(workflow, status, participantData, fieldType);
String data = participantDataDao.get(participantDataId).orElseThrow().getData().orElseThrow();
JsonObject dataJsonObject = gson.fromJson(data, JsonObject.class);
Assert.assertEquals(status, dataJsonObject.get(workflow).getAsString());
} finally {
deleteParticipantData(participantDataId);
}
}
@Test
public void testCreateParticipantData() {
int participantDataId = -1;
try {
String workflow = "REGISTRATION_TYPE";
String status = "SELF2";
participantDataId = WorkflowStatusUpdate.createParticipantData(workflow, status,
genParticipantId("anp"), ddpInstanceDto.getDdpInstanceId(), fieldTypeId);
String data = participantDataDao.get(participantDataId).orElseThrow().getData().orElse("");
JsonObject dataJsonObject = gson.fromJson(data, JsonObject.class);
Assert.assertEquals(status, dataJsonObject.get(workflow).getAsString());
} finally {
deleteParticipantData(participantDataId);
}
}
}
| 7,119 | 0.708981 | 0.708001 | 153 | 45.64706 | 34.235531 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.777778 | false | false | 12 |
3257b94c900f1b0feea017eaf0e9d04410ddee64 | 21,337,397,588,987 | 1e18442771e9a04836d3bea8a0ff59a4a8fbd4bc | /src/main/java/conditions/MainConditions.java | 5181fa5b225d75315a437cccffd82dbf126a859c | [] | no_license | AlexanderBaravulia/WebDriver | https://github.com/AlexanderBaravulia/WebDriver | 6b3c61cf1f5c96a1c4110b1624346b7e1d36f19b | 267353366987e6d6b9fc07c33c37c0d48be83c1b | refs/heads/master | 2020-04-27T09:08:17.133000 | 2019-03-28T18:42:44 | 2019-03-28T18:42:44 | 174,201,942 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package conditions;
import driver.DriverManager;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.*;
import org.testng.asserts.SoftAssert;
import utill.TestListener;
@Listeners({TestListener.class})
public class MainConditions {
protected WebDriver driver;
protected SoftAssert softAssert;
@BeforeMethod()
public void getUpBrowser(){
driver = DriverManager.getDriver();
softAssert = new SoftAssert();
}
@AfterMethod(alwaysRun = true)
public void quitBrowser(){
DriverManager.closeDriver();
}
}
| UTF-8 | Java | 575 | java | MainConditions.java | Java | [] | null | [] | package conditions;
import driver.DriverManager;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.*;
import org.testng.asserts.SoftAssert;
import utill.TestListener;
@Listeners({TestListener.class})
public class MainConditions {
protected WebDriver driver;
protected SoftAssert softAssert;
@BeforeMethod()
public void getUpBrowser(){
driver = DriverManager.getDriver();
softAssert = new SoftAssert();
}
@AfterMethod(alwaysRun = true)
public void quitBrowser(){
DriverManager.closeDriver();
}
}
| 575 | 0.718261 | 0.718261 | 26 | 21.115385 | 15.355597 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.423077 | false | false | 12 |
0f6e63faed3b575de88df7d7b42ccc95ee0aaf01 | 23,837,068,549,418 | e156c40f52f0088b11ba42abadf357d4c5638717 | /src/main/java/com/penn/spring/transaction/mapper/TUserMapper.java | 2df15f348e744cc68b44807c268a69bea7957d67 | [] | no_license | rocjava/spring-transaction | https://github.com/rocjava/spring-transaction | 41dc15d76668bedb85529c9c81ff778f1c98fd53 | f04b4a17dd7341f8d0be302ace8dd12b038d7dcf | refs/heads/master | 2022-07-16T05:02:48.301000 | 2019-12-23T11:03:22 | 2019-12-23T11:03:22 | 229,238,106 | 1 | 0 | null | false | 2022-06-21T02:29:14 | 2019-12-20T09:56:28 | 2019-12-24T01:55:46 | 2022-06-21T02:29:13 | 21 | 1 | 0 | 5 | Java | false | false | package com.penn.spring.transaction.mapper;
import com.penn.spring.transaction.entity.TUser;
import org.apache.ibatis.annotations.Mapper;
/**
* Mapper 接口
*
* @author Penn.Zhang
* @since 2019-12-23
*/
@Mapper
public interface TUserMapper {
/**
* 根据主键查询
*/
TUser selectById(Long id);
/**
* 根据主键更新
*/
int updateById(TUser tUser);
/**
* 插入数据
*/
int insert(TUser tUser);
} | UTF-8 | Java | 469 | java | TUserMapper.java | Java | [
{
"context": "notations.Mapper;\n\n/**\n * Mapper 接口\n *\n * @author Penn.Zhang\n * @since 2019-12-23\n */\n@Mapper\npublic interface",
"end": 182,
"score": 0.9998445510864258,
"start": 172,
"tag": "NAME",
"value": "Penn.Zhang"
}
] | null | [] | package com.penn.spring.transaction.mapper;
import com.penn.spring.transaction.entity.TUser;
import org.apache.ibatis.annotations.Mapper;
/**
* Mapper 接口
*
* @author Penn.Zhang
* @since 2019-12-23
*/
@Mapper
public interface TUserMapper {
/**
* 根据主键查询
*/
TUser selectById(Long id);
/**
* 根据主键更新
*/
int updateById(TUser tUser);
/**
* 插入数据
*/
int insert(TUser tUser);
} | 469 | 0.60739 | 0.588915 | 30 | 13.466666 | 14.249522 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 12 |
8948a1fc7ea31acef97baf10b1c169de8b83665e | 8,134,668,118,120 | 6043b643cd9d2dc4fcca63ef437f47c3a8f0fcc3 | /java/20201116/ArrLesson3.java | beecd2ffc7dbc5371648155f4a8db5ca99fe2952 | [] | no_license | MiekoHayasaka/Training | https://github.com/MiekoHayasaka/Training | 515e59bf88f57ff05e36974a329327651de83cb5 | b5d2a641410ef16178d2e29c6661593bcea26301 | refs/heads/master | 2023-02-03T11:00:28.856000 | 2020-12-23T05:46:02 | 2020-12-23T05:46:02 | 311,192,402 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.*;
public class ArrLesson3{
public static void main(String[] args){
System.out.print("何クラス>");
int classNum = new Scanner(System.in).nextInt();
int[][] data = new int[classNum][];
for(int i=0; i<data.length; i++){
System.out.print("クラス"+ (i+1) +"は何人>");
int member = new Scanner(System.in).nextInt();
data[i]=new int[member];
for(int j=0; j<data[i].length; j++){
System.out.printf("%d人目の点数>",j+1);
int score = new Scanner(System.in).nextInt();
data[i][j]=score;
}
}
System.out.println("---結果---");
for(int i=0;i<data.length;i++){
for(int j=0;j<data[i].length;j++){
System.out.printf("%4d",data[i][j]);
}
System.out.println();
}
}
}
| UTF-8 | Java | 742 | java | ArrLesson3.java | Java | [] | null | [] | import java.util.*;
public class ArrLesson3{
public static void main(String[] args){
System.out.print("何クラス>");
int classNum = new Scanner(System.in).nextInt();
int[][] data = new int[classNum][];
for(int i=0; i<data.length; i++){
System.out.print("クラス"+ (i+1) +"は何人>");
int member = new Scanner(System.in).nextInt();
data[i]=new int[member];
for(int j=0; j<data[i].length; j++){
System.out.printf("%d人目の点数>",j+1);
int score = new Scanner(System.in).nextInt();
data[i][j]=score;
}
}
System.out.println("---結果---");
for(int i=0;i<data.length;i++){
for(int j=0;j<data[i].length;j++){
System.out.printf("%4d",data[i][j]);
}
System.out.println();
}
}
}
| 742 | 0.591808 | 0.580508 | 25 | 27.32 | 15.916582 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.24 | false | false | 12 |
5077918cd22dc0a6fa410f36c19db6d04f645f5b | 1,906,965,542,026 | 56e0f8b9f10979070ff30fc45b2fb5c869af6f37 | /spring/src/com/arthas/e_lifecycle/UserServiceImpl.java | 39fd30c297cbd8c82862f050ff4af726f8bc9250 | [] | no_license | mohong/java | https://github.com/mohong/java | d11d785630e62608040ac6ce2371a1889e5d79f1 | de36416bf1a8fe82e48c2e9e752bf8c53234fdb9 | refs/heads/master | 2017-12-16T17:04:50.554000 | 2017-02-25T13:36:46 | 2017-02-25T13:36:46 | 77,462,663 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.arthas.e_lifecycle;
public class UserServiceImpl implements UserService {
@Override
public void addUser() {
System.out.println("e_lifecycle add user");
}
@Override
public void init() {
System.out.println("init method");
}
@Override
public void destroy() {
System.out.println("destory method");
}
}
| UTF-8 | Java | 373 | java | UserServiceImpl.java | Java | [] | null | [] | package com.arthas.e_lifecycle;
public class UserServiceImpl implements UserService {
@Override
public void addUser() {
System.out.println("e_lifecycle add user");
}
@Override
public void init() {
System.out.println("init method");
}
@Override
public void destroy() {
System.out.println("destory method");
}
}
| 373 | 0.624665 | 0.624665 | 18 | 19.722221 | 17.912769 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | false | false | 12 |
ca1b11242e31a663eafdf08a843decbdb2f07dbf | 23,562,190,650,911 | e88d01097b72b276f9c3907a48289095e5457c46 | /elk-reasoner/src/main/java/org/semanticweb/elk/reasoner/saturation/rules/RuleDeapplicationFactory.java | 8d918d24a708747f1fc47bec1b620d1538d42255 | [
"Apache-2.0"
] | permissive | ansell/elk | https://github.com/ansell/elk | 7c999a2a59c345f1a88113c7513ffba9e03831af | 423775733337b3da3ba6271d967e835b905760f6 | refs/heads/master | 2016-09-26T15:43:09.322000 | 2013-09-16T10:26:14 | 2013-09-16T10:26:14 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package org.semanticweb.elk.reasoner.saturation.rules;
/*
* #%L
* ELK Reasoner
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2011 - 2012 Department of Computer Science, University of Oxford
* %%
* 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.
* #L%
*/
import org.semanticweb.elk.reasoner.indexing.hierarchy.IndexedClassExpression;
import org.semanticweb.elk.reasoner.saturation.BasicSaturationStateWriter;
import org.semanticweb.elk.reasoner.saturation.ContextCreationListener;
import org.semanticweb.elk.reasoner.saturation.ContextModificationListener;
import org.semanticweb.elk.reasoner.saturation.SaturationState;
import org.semanticweb.elk.reasoner.saturation.SaturationStatistics;
import org.semanticweb.elk.reasoner.saturation.SaturationUtils;
import org.semanticweb.elk.reasoner.saturation.conclusions.CombinedConclusionVisitor;
import org.semanticweb.elk.reasoner.saturation.conclusions.ConclusionDeapplicationVisitor;
import org.semanticweb.elk.reasoner.saturation.conclusions.ConclusionDeletionVisitor;
import org.semanticweb.elk.reasoner.saturation.conclusions.ConclusionOccurranceCheckingVisitor;
import org.semanticweb.elk.reasoner.saturation.conclusions.ConclusionVisitor;
/**
* Creates an engine which applies rules backwards, e.g., removes conclusions
* from the context instead of adding them
*
* @author Pavel Klinov
*
* pavel.klinov@uni-ulm.de
*
* @author "Yevgeny Kazakov"
*/
public class RuleDeapplicationFactory extends RuleApplicationFactory {
public RuleDeapplicationFactory(final SaturationState saturationState,
boolean trackModifiedContexts) {
super(saturationState, trackModifiedContexts);
}
@Override
public DeapplicationEngine getDefaultEngine(
ContextCreationListener listener,
ContextModificationListener modListener) {
return new DeapplicationEngine(modListener);
}
/**
*
*/
public class DeapplicationEngine extends RuleApplicationFactory.BaseEngine {
private final BasicSaturationStateWriter writer_;
protected DeapplicationEngine(ContextModificationListener listener) {
super(new SaturationStatistics());
writer_ = saturationState.getWriter(SaturationUtils
.addStatsToContextModificationListener(listener,
localStatistics.getContextStatistics()),
SaturationUtils.addStatsToConclusionVisitor(localStatistics
.getConclusionStatistics()));
}
@Override
protected ConclusionVisitor<Boolean> getBaseConclusionProcessor(
BasicSaturationStateWriter saturationStateWriter) {
return new CombinedConclusionVisitor(
new CombinedConclusionVisitor(
new ConclusionOccurranceCheckingVisitor(),
getUsedConclusionsCountingVisitor(new ConclusionDeapplicationVisitor(
saturationStateWriter,
SaturationUtils
.getStatsAwareCompositionRuleAppVisitor(localStatistics
.getRuleStatistics()),
SaturationUtils
.getStatsAwareDecompositionRuleAppVisitor(
getDecompositionRuleApplicationVisitor(),
localStatistics
.getRuleStatistics())))),
new ConclusionDeletionVisitor());
}
@Override
public void submit(IndexedClassExpression job) {
}
@Override
protected BasicSaturationStateWriter getSaturationStateWriter() {
return writer_;
}
@Override
protected DecompositionRuleApplicationVisitor getDecompositionRuleApplicationVisitor() {
// this decomposition visitor takes the basic writer which cannot
// create new contexts
return new BackwardDecompositionRuleApplicationVisitor(
getSaturationStateWriter());
}
}
}
| UTF-8 | Java | 4,114 | java | RuleDeapplicationFactory.java | Java | [
{
"context": " the context instead of adding them\n * \n * @author Pavel Klinov\n * \n * pavel.klinov@uni-ulm.de\n * \n * @au",
"end": 1870,
"score": 0.9998737573623657,
"start": 1858,
"tag": "NAME",
"value": "Pavel Klinov"
},
{
"context": "ng them\n * \n * @author Pavel Klin... | null | [] | /**
*
*/
package org.semanticweb.elk.reasoner.saturation.rules;
/*
* #%L
* ELK Reasoner
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2011 - 2012 Department of Computer Science, University of Oxford
* %%
* 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.
* #L%
*/
import org.semanticweb.elk.reasoner.indexing.hierarchy.IndexedClassExpression;
import org.semanticweb.elk.reasoner.saturation.BasicSaturationStateWriter;
import org.semanticweb.elk.reasoner.saturation.ContextCreationListener;
import org.semanticweb.elk.reasoner.saturation.ContextModificationListener;
import org.semanticweb.elk.reasoner.saturation.SaturationState;
import org.semanticweb.elk.reasoner.saturation.SaturationStatistics;
import org.semanticweb.elk.reasoner.saturation.SaturationUtils;
import org.semanticweb.elk.reasoner.saturation.conclusions.CombinedConclusionVisitor;
import org.semanticweb.elk.reasoner.saturation.conclusions.ConclusionDeapplicationVisitor;
import org.semanticweb.elk.reasoner.saturation.conclusions.ConclusionDeletionVisitor;
import org.semanticweb.elk.reasoner.saturation.conclusions.ConclusionOccurranceCheckingVisitor;
import org.semanticweb.elk.reasoner.saturation.conclusions.ConclusionVisitor;
/**
* Creates an engine which applies rules backwards, e.g., removes conclusions
* from the context instead of adding them
*
* @author <NAME>
*
* <EMAIL>
*
* @author "<NAME>"
*/
public class RuleDeapplicationFactory extends RuleApplicationFactory {
public RuleDeapplicationFactory(final SaturationState saturationState,
boolean trackModifiedContexts) {
super(saturationState, trackModifiedContexts);
}
@Override
public DeapplicationEngine getDefaultEngine(
ContextCreationListener listener,
ContextModificationListener modListener) {
return new DeapplicationEngine(modListener);
}
/**
*
*/
public class DeapplicationEngine extends RuleApplicationFactory.BaseEngine {
private final BasicSaturationStateWriter writer_;
protected DeapplicationEngine(ContextModificationListener listener) {
super(new SaturationStatistics());
writer_ = saturationState.getWriter(SaturationUtils
.addStatsToContextModificationListener(listener,
localStatistics.getContextStatistics()),
SaturationUtils.addStatsToConclusionVisitor(localStatistics
.getConclusionStatistics()));
}
@Override
protected ConclusionVisitor<Boolean> getBaseConclusionProcessor(
BasicSaturationStateWriter saturationStateWriter) {
return new CombinedConclusionVisitor(
new CombinedConclusionVisitor(
new ConclusionOccurranceCheckingVisitor(),
getUsedConclusionsCountingVisitor(new ConclusionDeapplicationVisitor(
saturationStateWriter,
SaturationUtils
.getStatsAwareCompositionRuleAppVisitor(localStatistics
.getRuleStatistics()),
SaturationUtils
.getStatsAwareDecompositionRuleAppVisitor(
getDecompositionRuleApplicationVisitor(),
localStatistics
.getRuleStatistics())))),
new ConclusionDeletionVisitor());
}
@Override
public void submit(IndexedClassExpression job) {
}
@Override
protected BasicSaturationStateWriter getSaturationStateWriter() {
return writer_;
}
@Override
protected DecompositionRuleApplicationVisitor getDecompositionRuleApplicationVisitor() {
// this decomposition visitor takes the basic writer which cannot
// create new contexts
return new BackwardDecompositionRuleApplicationVisitor(
getSaturationStateWriter());
}
}
}
| 4,083 | 0.777832 | 0.774915 | 120 | 33.283333 | 29.518408 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.275 | false | false | 12 |
3b30612f6411384066da17f84e4c3d9523d71edc | 12,610,024,038,580 | 3702840cf394447a90d982151bc22f244e10be14 | /src/main/java/com/atguigu/day17utils/test/Equipment.java | adfc183362a8dd7c8cd13475b2b8a1c68d2eb202 | [] | no_license | Luozuanshi/onefivetownine | https://github.com/Luozuanshi/onefivetownine | 7a6b46a2a193c41aa875a91ec7fd3af42f400d4f | aa10e17d735f02fc8791910b7a1cc1b7c2905904 | refs/heads/master | 2022-12-25T20:34:17.116000 | 2021-08-29T15:00:25 | 2021-08-29T15:00:25 | 167,674,775 | 0 | 0 | null | false | 2022-11-24T06:41:28 | 2019-01-26T10:06:35 | 2021-08-29T15:00:33 | 2022-11-24T06:41:25 | 4,313 | 0 | 0 | 11 | Java | false | false | /**
*
*/
package com.atguigu.day17utils.test;
/**
* 项目名称:domo
*类名称:Equipment
* @author Administrator
* @version 1.0
* 创建时间2019年12月21日下午4:02:24
* 类描述
*/
public interface Equipment {
}
| UTF-8 | Java | 245 | java | Equipment.java | Java | [
{
"context": ";\n\n/**\n * 项目名称:domo\n *类名称:Equipment\n * @author Administrator\n * @version 1.0\n * 创建时间2019年12月21日下午4:02:24\n ",
"end": 111,
"score": 0.9860450029373169,
"start": 98,
"tag": "NAME",
"value": "Administrator"
}
] | null | [] | /**
*
*/
package com.atguigu.day17utils.test;
/**
* 项目名称:domo
*类名称:Equipment
* @author Administrator
* @version 1.0
* 创建时间2019年12月21日下午4:02:24
* 类描述
*/
public interface Equipment {
}
| 245 | 0.630542 | 0.546798 | 16 | 11.6875 | 11.541874 | 36 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.0625 | false | false | 12 |
5d1fc71c0cf6e8b3c375cf7426f94a3906903ce8 | 31,628,139,235,279 | 31356e789a95a212e38772a7a8bf219b748d4db2 | /classification/src/decisiontree/ID3.java | 9b8a836da1e533a0f87ed624c5cd703dcb0b9341 | [] | no_license | aBit19/dataMining17 | https://github.com/aBit19/dataMining17 | bde5727c4862e18b36a25a6c600b43cdc796bd05 | 72cca954a7c8a649efa53aa8f709cae9f049089e | refs/heads/master | 2020-05-22T22:37:47.378000 | 2017-04-22T09:57:07 | 2017-04-22T09:57:07 | 84,731,135 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package decisiontree;
import data.Mushroom;
import data.Util;
import enums.Class_Label;
import javax.swing.*;
import java.util.List;
import java.util.function.Predicate;
public class ID3 {
private final Tree tree;
private static final IAttributeSelection informationGain = InformationGain.INSTANCE;
public ID3(List<Mushroom> partition, List<Object> attributeList) {
tree = generateTree(partition, attributeList, informationGain);
}
public Tree getTree() {
return this.tree;
}
private static Tree generateTree(List<Mushroom> partition,
List<Object> attrList,
IAttributeSelection attrSelectionMethod) {
Node node = new Node();
if (partitionIsOfSameClass(partition))
return new Leaf(partition.get(0).m_Class);
if (attrList.isEmpty())
return new Leaf(getMajorityClassFrom(partition));
SplittingCriterion criterion = attrSelectionMethod.split(partition, attrList);
if (criterion.isDiscrete() && attrSelectionMethod.multiWaySplittingEnabled())
attrList.remove(criterion.getAttr());
for (Predicate<Mushroom> predicate : criterion.getOutcomes()) {
List<Mushroom> list = Util.filter(partition, predicate);
if (!list.isEmpty())
node.addCase(predicate, generateTree(list, attrList, attrSelectionMethod));
}
return node;
}
private static boolean partitionIsOfSameClass(List<Mushroom> lm ) {
Class_Label sample = lm.get(0).m_Class;
return lm.stream().allMatch(m -> m.m_Class.equals(sample));
}
private static Class_Label getMajorityClassFrom(List<Mushroom> partition) {
int edible = Util.filter(partition, m -> m.m_Class.equals(Class_Label.edible)).size();
return edible > partition.size()/2 ? Class_Label.edible : Class_Label.poisonous;
}
public static void main(String[] args) {
List<Mushroom> data =Util.getData(),
trainingSet = data.subList(0, 2000),
testSet = data.subList(2000, 3000);
ID3 id3 = new ID3(trainingSet, Mushroom.getAttributeList());
Tree tree = id3.getTree();
int correct = 0;
for (Mushroom m : testSet) {
if (tree.classify(m).equals(m.getAttributeValue(Class_Label.class)))
correct++;
}
System.out.println("correct predictions: " + correct);
}
}
| UTF-8 | Java | 2,494 | java | ID3.java | Java | [] | null | [] | package decisiontree;
import data.Mushroom;
import data.Util;
import enums.Class_Label;
import javax.swing.*;
import java.util.List;
import java.util.function.Predicate;
public class ID3 {
private final Tree tree;
private static final IAttributeSelection informationGain = InformationGain.INSTANCE;
public ID3(List<Mushroom> partition, List<Object> attributeList) {
tree = generateTree(partition, attributeList, informationGain);
}
public Tree getTree() {
return this.tree;
}
private static Tree generateTree(List<Mushroom> partition,
List<Object> attrList,
IAttributeSelection attrSelectionMethod) {
Node node = new Node();
if (partitionIsOfSameClass(partition))
return new Leaf(partition.get(0).m_Class);
if (attrList.isEmpty())
return new Leaf(getMajorityClassFrom(partition));
SplittingCriterion criterion = attrSelectionMethod.split(partition, attrList);
if (criterion.isDiscrete() && attrSelectionMethod.multiWaySplittingEnabled())
attrList.remove(criterion.getAttr());
for (Predicate<Mushroom> predicate : criterion.getOutcomes()) {
List<Mushroom> list = Util.filter(partition, predicate);
if (!list.isEmpty())
node.addCase(predicate, generateTree(list, attrList, attrSelectionMethod));
}
return node;
}
private static boolean partitionIsOfSameClass(List<Mushroom> lm ) {
Class_Label sample = lm.get(0).m_Class;
return lm.stream().allMatch(m -> m.m_Class.equals(sample));
}
private static Class_Label getMajorityClassFrom(List<Mushroom> partition) {
int edible = Util.filter(partition, m -> m.m_Class.equals(Class_Label.edible)).size();
return edible > partition.size()/2 ? Class_Label.edible : Class_Label.poisonous;
}
public static void main(String[] args) {
List<Mushroom> data =Util.getData(),
trainingSet = data.subList(0, 2000),
testSet = data.subList(2000, 3000);
ID3 id3 = new ID3(trainingSet, Mushroom.getAttributeList());
Tree tree = id3.getTree();
int correct = 0;
for (Mushroom m : testSet) {
if (tree.classify(m).equals(m.getAttributeValue(Class_Label.class)))
correct++;
}
System.out.println("correct predictions: " + correct);
}
}
| 2,494 | 0.637129 | 0.627907 | 70 | 34.628571 | 29.957193 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.642857 | false | false | 12 |
b13cc054eb6a32f1a1174293d364fc513458a409 | 16,587,163,713,563 | 6982f857bafbf1e699c772743eddec7aeb7f98bf | /src/Controller/WebCrawler.java | d8801bddf660cbb20cc04c77516f5d9994024d1d | [] | no_license | AviadGol/WebCrawler | https://github.com/AviadGol/WebCrawler | e01ef38f1309ccc1254f9dffe09c10cca7c82447 | cff8288601a69235ddcb2b7e57240fb79be16323 | refs/heads/master | 2020-04-05T16:41:37.932000 | 2018-11-10T21:59:53 | 2018-11-10T21:59:53 | 156,767,296 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Controller;
import Model.Output;
import Model.UrlStruct;
import Model.UrlsInfo;
import Model.WaitingQ;
import View.TerminalWin;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
/*
WebCrawler class is responsible for managing the network scan.
Receives a root address and sends it to a scan.
every address added to the waitingQ - the WebCrawler is responsible
for opening its own thread and sending it to the scan.
The WebCrawler has the option to perform a new scan/continuous scan
according to the type of constructor that the class was created for.
The WebCrawler is responsible for cleaning up all the data files
on which data from the previous scans are stored.
*/
public class WebCrawler extends Thread{
//received from user
URL urlRoot;
static final String scanDataPath = "file/temp/dataScan";
//index for scanData array
final int deepRec = 0;
final int numOfThread = 1;
int[] scanData = new int[2];
WaitingQ waitingQ = WaitingQ.getInstance();
//c-tor for new scan
public WebCrawler(URL urlRoot, int deepRec, int numOfThread) {
this.urlRoot = urlRoot;
scanData[this.deepRec] = deepRec;
scanData[this.numOfThread] = numOfThread;
//save data for continue the scan
saveScanData();
//clear all file
clearAll();
//add the path url to waitingQ
waitingQ.addUrl(new UrlStruct(urlRoot,1));
//start Web Crawler
start();
}
//c-tor for continue scan
public WebCrawler(){
////check if not exist page details (first running)
if(Files.exists(Paths.get(scanDataPath))) {
try {
FileInputStream inputStream = new FileInputStream(scanDataPath);
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
//try and catch if the file is empty
try {
scanData = (int[]) objectInputStream.readObject();
} catch (Exception e) {
}
objectInputStream.close();
//start Web Crawler
start();
} catch (Exception e) {
System.out.println("file " + scanDataPath + " not found...");
}
}
else{
System.out.println("file " + scanDataPath + " not found...");
}
}
//main function
public void run(){
try {
//make array of thread (according user chose)
Process[] processes = new Process[scanData[numOfThread]];
//As exists URL in the waitingQ
//or there is a process that still works
while (!waitingQ.isEmpty() || !allProcessesFinish(processes)){
//scan "free" thread
for(int i = 0; i < scanData[numOfThread]; i++)
if(processes[i] == null || !processes[i].isAlive()) {
//get next url from waitingQ
UrlStruct nextProcess = waitingQ.getNext();
if(nextProcess != null){
TerminalWin.getInstance().printGreen("Process-" + i + "-" + nextProcess.getUrl().toString());
//start scan url
processes[i] = new Process(nextProcess,scanData[deepRec]);
}
}
}
//Finish!!!
TerminalWin.getInstance().printGreen("Finish!!!!");
}
catch (Exception e){
System.out.println("Error in WebCrawler");
}
}
//clear files for new scan
public void clearAll(){
WaitingQ.getInstance().clear();
Output.getInstance().clear();
}
//check whether it's possible to continue scanning
public static boolean isContinual(){
//check if exist files: waitingQ, output, scanData
if(Files.exists(Paths.get(scanDataPath))){
return true;
}
return false;
}
//save data for continue the scan
public void saveScanData(){
try {
//object for file work (save)
FileOutputStream outputStream = new FileOutputStream(scanDataPath);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(scanData);
objectOutputStream.close();
} catch (Exception ex) {
System.out.println("Error save data scan...");
}
}
//return true if all processes finish
public boolean allProcessesFinish(Process[] processes){
for (Process tempProcess:processes) {
if(tempProcess != null && tempProcess.isAlive())
return false;
}
return true;
}
}
| UTF-8 | Java | 4,953 | java | WebCrawler.java | Java | [] | null | [] | package Controller;
import Model.Output;
import Model.UrlStruct;
import Model.UrlsInfo;
import Model.WaitingQ;
import View.TerminalWin;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
/*
WebCrawler class is responsible for managing the network scan.
Receives a root address and sends it to a scan.
every address added to the waitingQ - the WebCrawler is responsible
for opening its own thread and sending it to the scan.
The WebCrawler has the option to perform a new scan/continuous scan
according to the type of constructor that the class was created for.
The WebCrawler is responsible for cleaning up all the data files
on which data from the previous scans are stored.
*/
public class WebCrawler extends Thread{
//received from user
URL urlRoot;
static final String scanDataPath = "file/temp/dataScan";
//index for scanData array
final int deepRec = 0;
final int numOfThread = 1;
int[] scanData = new int[2];
WaitingQ waitingQ = WaitingQ.getInstance();
//c-tor for new scan
public WebCrawler(URL urlRoot, int deepRec, int numOfThread) {
this.urlRoot = urlRoot;
scanData[this.deepRec] = deepRec;
scanData[this.numOfThread] = numOfThread;
//save data for continue the scan
saveScanData();
//clear all file
clearAll();
//add the path url to waitingQ
waitingQ.addUrl(new UrlStruct(urlRoot,1));
//start Web Crawler
start();
}
//c-tor for continue scan
public WebCrawler(){
////check if not exist page details (first running)
if(Files.exists(Paths.get(scanDataPath))) {
try {
FileInputStream inputStream = new FileInputStream(scanDataPath);
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
//try and catch if the file is empty
try {
scanData = (int[]) objectInputStream.readObject();
} catch (Exception e) {
}
objectInputStream.close();
//start Web Crawler
start();
} catch (Exception e) {
System.out.println("file " + scanDataPath + " not found...");
}
}
else{
System.out.println("file " + scanDataPath + " not found...");
}
}
//main function
public void run(){
try {
//make array of thread (according user chose)
Process[] processes = new Process[scanData[numOfThread]];
//As exists URL in the waitingQ
//or there is a process that still works
while (!waitingQ.isEmpty() || !allProcessesFinish(processes)){
//scan "free" thread
for(int i = 0; i < scanData[numOfThread]; i++)
if(processes[i] == null || !processes[i].isAlive()) {
//get next url from waitingQ
UrlStruct nextProcess = waitingQ.getNext();
if(nextProcess != null){
TerminalWin.getInstance().printGreen("Process-" + i + "-" + nextProcess.getUrl().toString());
//start scan url
processes[i] = new Process(nextProcess,scanData[deepRec]);
}
}
}
//Finish!!!
TerminalWin.getInstance().printGreen("Finish!!!!");
}
catch (Exception e){
System.out.println("Error in WebCrawler");
}
}
//clear files for new scan
public void clearAll(){
WaitingQ.getInstance().clear();
Output.getInstance().clear();
}
//check whether it's possible to continue scanning
public static boolean isContinual(){
//check if exist files: waitingQ, output, scanData
if(Files.exists(Paths.get(scanDataPath))){
return true;
}
return false;
}
//save data for continue the scan
public void saveScanData(){
try {
//object for file work (save)
FileOutputStream outputStream = new FileOutputStream(scanDataPath);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(scanData);
objectOutputStream.close();
} catch (Exception ex) {
System.out.println("Error save data scan...");
}
}
//return true if all processes finish
public boolean allProcessesFinish(Process[] processes){
for (Process tempProcess:processes) {
if(tempProcess != null && tempProcess.isAlive())
return false;
}
return true;
}
}
| 4,953 | 0.590147 | 0.589138 | 154 | 31.162338 | 24.795912 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.402597 | false | false | 12 |
4d30ee5178786bff71b5cf9ff23aef577ca8f7c4 | 19,722,489,839,638 | a38ec308828171bc687ec198e7b032187d7c457e | /Evaluacion_Estrada/src/interfaces/Listable.java | f664d7cdd68e0385f38be1b5cab82af3da2ea4d8 | [] | no_license | erikestradaf21/java-workspace | https://github.com/erikestradaf21/java-workspace | 8af82ef29c7ed7d8af6703f8a61624d31f3262cb | bea931141adea0ae7b5f0c1051273a49cddde960 | refs/heads/master | 2023-08-23T08:36:30.865000 | 2021-10-21T00:40:46 | 2021-10-21T00:40:46 | 403,467,758 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package interfaces;
public interface Listable {
String getNombre();
}
| UTF-8 | Java | 74 | java | Listable.java | Java | [] | null | [] | package interfaces;
public interface Listable {
String getNombre();
}
| 74 | 0.743243 | 0.743243 | 6 | 11.333333 | 10.964589 | 27 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 12 |
681ef0fc18b6e36e39d3456dbfc729dab2a35629 | 35,545,149,377,363 | 25f47ddb872e8793847f793c6cd6ce86700de857 | /FOODING/Fooding/app/src/main/java/com/technology/greenenjoyshoppingstreet/newui/view/MainFragmentActivity.java | 34adf1a62f57e09bfb266ce8f69816b58e8ff352 | [] | no_license | didigosl/foodinn-android | https://github.com/didigosl/foodinn-android | caf7236dba7bc159c46d3409f79e7fe7af1b392a | 30d11f8fdfc45842fd4680bf75c25ce664b12b0c | refs/heads/master | 2020-09-11T05:15:17.242000 | 2019-11-15T15:40:14 | 2019-11-15T15:40:14 | 221,950,168 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.technology.greenenjoyshoppingstreet.newui.view;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import com.duma.ld.baselibarary.model.HttpResModel;
import com.duma.ld.mytopbar.config.PublicConfig;
import com.flyco.tablayout.SlidingTabLayout;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.technology.greenenjoyshoppingstreet.R;
import com.technology.greenenjoyshoppingstreet.main.SearchActivity;
import com.technology.greenenjoyshoppingstreet.mine.BuyVIPActivity;
import com.technology.greenenjoyshoppingstreet.newui.base.BaseMyActivity;
import com.technology.greenenjoyshoppingstreet.newui.base.MyJsonCallback;
import com.technology.greenenjoyshoppingstreet.newui.base.MyViewPagerAdapter;
import com.technology.greenenjoyshoppingstreet.newui.model.MainClassModel;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import static com.technology.greenenjoyshoppingstreet.utils.constant.URLConstant.CATEGORY_LIST;
public class MainFragmentActivity extends BaseMyActivity {
/*@BindView(R.id.gift_rl)
FrameLayout giftRl;*/
@BindView(R.id.search_rl)
FrameLayout searchRl;
@BindView(R.id.tab_goodsType)
SlidingTabLayout tabGoodsType;
@BindView(R.id.layout_tab)
FrameLayout layoutTab;
@BindView(R.id.viewPager_goodsList)
ViewPager viewPagerGoodsList;
@BindView(R.id.layout_root)
FrameLayout layoutRoot;
@Override
protected int setLayoutId(Bundle savedInstanceState) {
return R.layout.activity_fragment_main;
}
@Override
protected void initConfig(Bundle savedInstanceState, PublicConfig mPublicConfig) {
mPublicConfig.setLoadOrErrorRootLayout(R.id.layout_root);
}
@Override
protected void setStatusBar() {
}
@Override
protected void setFits(LinearLayout layout_boot_ob) {
}
@Override
protected void init(Bundle savedInstanceState) {
super.init(savedInstanceState);
starRefresh();
}
@Override
public void onHttpRefresh(int page) {
super.onHttpRefresh(page);
OkGo.<HttpResModel<List<MainClassModel>>>post(CATEGORY_LIST)
.tag(this)
.execute(new MyJsonCallback<HttpResModel<List<MainClassModel>>>(mPublicConfig) {
@Override
protected void onJsonSuccess(Response<HttpResModel<List<MainClassModel>>> respons, HttpResModel<List<MainClassModel>> goodsModelHttpResModel) {
MyViewPagerAdapter viewPagerAdapter = new MyViewPagerAdapter(getSupportFragmentManager());
List<MainClassModel> data = goodsModelHttpResModel.getData();
viewPagerAdapter.addFragment(MainTuiJianFragment.newInstance(), "推荐");
for (int i = 0; i < data.size(); i++) {
viewPagerAdapter.addFragment(MainClassFragment.newInstance(data.get(i)), data.get(i).getCategoryName());
}
viewPagerGoodsList.setAdapter(viewPagerAdapter);
tabGoodsType.setViewPager(viewPagerGoodsList);
}
});
}
@OnClick({R.id.search_rl})
public void onViewClicked(View view) {
switch (view.getId()) {
/*case R.id.gift_rl:
startActivity(new Intent(mActivity, BuyVIPActivity.class));
break;*/
case R.id.search_rl:
startActivity(new Intent(mActivity, SearchActivity.class));
break;
}
}
}
| UTF-8 | Java | 3,726 | java | MainFragmentActivity.java | Java | [] | null | [] | package com.technology.greenenjoyshoppingstreet.newui.view;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import com.duma.ld.baselibarary.model.HttpResModel;
import com.duma.ld.mytopbar.config.PublicConfig;
import com.flyco.tablayout.SlidingTabLayout;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.technology.greenenjoyshoppingstreet.R;
import com.technology.greenenjoyshoppingstreet.main.SearchActivity;
import com.technology.greenenjoyshoppingstreet.mine.BuyVIPActivity;
import com.technology.greenenjoyshoppingstreet.newui.base.BaseMyActivity;
import com.technology.greenenjoyshoppingstreet.newui.base.MyJsonCallback;
import com.technology.greenenjoyshoppingstreet.newui.base.MyViewPagerAdapter;
import com.technology.greenenjoyshoppingstreet.newui.model.MainClassModel;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import static com.technology.greenenjoyshoppingstreet.utils.constant.URLConstant.CATEGORY_LIST;
public class MainFragmentActivity extends BaseMyActivity {
/*@BindView(R.id.gift_rl)
FrameLayout giftRl;*/
@BindView(R.id.search_rl)
FrameLayout searchRl;
@BindView(R.id.tab_goodsType)
SlidingTabLayout tabGoodsType;
@BindView(R.id.layout_tab)
FrameLayout layoutTab;
@BindView(R.id.viewPager_goodsList)
ViewPager viewPagerGoodsList;
@BindView(R.id.layout_root)
FrameLayout layoutRoot;
@Override
protected int setLayoutId(Bundle savedInstanceState) {
return R.layout.activity_fragment_main;
}
@Override
protected void initConfig(Bundle savedInstanceState, PublicConfig mPublicConfig) {
mPublicConfig.setLoadOrErrorRootLayout(R.id.layout_root);
}
@Override
protected void setStatusBar() {
}
@Override
protected void setFits(LinearLayout layout_boot_ob) {
}
@Override
protected void init(Bundle savedInstanceState) {
super.init(savedInstanceState);
starRefresh();
}
@Override
public void onHttpRefresh(int page) {
super.onHttpRefresh(page);
OkGo.<HttpResModel<List<MainClassModel>>>post(CATEGORY_LIST)
.tag(this)
.execute(new MyJsonCallback<HttpResModel<List<MainClassModel>>>(mPublicConfig) {
@Override
protected void onJsonSuccess(Response<HttpResModel<List<MainClassModel>>> respons, HttpResModel<List<MainClassModel>> goodsModelHttpResModel) {
MyViewPagerAdapter viewPagerAdapter = new MyViewPagerAdapter(getSupportFragmentManager());
List<MainClassModel> data = goodsModelHttpResModel.getData();
viewPagerAdapter.addFragment(MainTuiJianFragment.newInstance(), "推荐");
for (int i = 0; i < data.size(); i++) {
viewPagerAdapter.addFragment(MainClassFragment.newInstance(data.get(i)), data.get(i).getCategoryName());
}
viewPagerGoodsList.setAdapter(viewPagerAdapter);
tabGoodsType.setViewPager(viewPagerGoodsList);
}
});
}
@OnClick({R.id.search_rl})
public void onViewClicked(View view) {
switch (view.getId()) {
/*case R.id.gift_rl:
startActivity(new Intent(mActivity, BuyVIPActivity.class));
break;*/
case R.id.search_rl:
startActivity(new Intent(mActivity, SearchActivity.class));
break;
}
}
}
| 3,726 | 0.69237 | 0.691832 | 100 | 36.220001 | 31.373741 | 163 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.53 | false | false | 12 |
b2107fd339e0f92d96bc6483c4d4b843b0198045 | 37,950,331,040,473 | da81728a8f4d07f5b383f2e12a25b17184b2f9a5 | /app/src/main/java/br/com/caelum/jogos2d/ForcaView.java | 5efa29fbd430d4271f3fbfc63b3c9e37990ab205 | [] | no_license | e3duardo/alura_jogos2d | https://github.com/e3duardo/alura_jogos2d | 3b23ac8fb41f2ea3f06d79705a5b573e35c94ece | 33de508ed93400277f5fa7fc490d3a494739e818 | refs/heads/master | 2021-04-29T01:26:49.662000 | 2017-01-01T22:33:26 | 2017-01-01T22:33:26 | 77,780,507 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.caelum.jogos2d;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
/**
* Created by eduardo on 01/01/17.
*/
public class ForcaView extends PlanoCartesianoView {
private Path pathForca;
public ForcaView(Context context) {
super(context);
pathForca = new Path();
}
public ForcaView(Context context, AttributeSet attrs) {
super(context, attrs);
pathForca = new Path();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// pathForca.moveTo(toPixel(2), toPixel(2));
// pathForca.lineTo(toPixel(8), toPixel(2));
plotaArmacaoForca();
plotaCabeca();
plotaCorpo();
plotaMembro(Membro.braco, Lado.direito);
plotaMembro(Membro.braco, Lado.esquerdo);
plotaMembro(Membro.perna, Lado.direito);
plotaMembro(Membro.perna, Lado.esquerdo);
canvas.drawPath(pathForca, getPaintForca());
}
private void plotaArmacaoForca(){
pathForca.moveTo(toPixel(1), toPixel(10));
pathForca.lineTo(toPixel(3), toPixel(10));
pathForca.moveTo(toPixel(2), toPixel(10));
pathForca.lineTo(toPixel(2), toPixel(1));
pathForca.rLineTo(toPixel(5), 0);
pathForca.rLineTo(0, toPixel(1));
}
private void plotaCabeca(){
pathForca.addCircle(toPixel(7), toPixel(3), toPixel(1), Path.Direction.CW);
}
private void plotaCorpo(){
pathForca.moveTo(toPixel(7), toPixel(4));
pathForca.lineTo(toPixel(7), toPixel(7));
}
private void plotaMembro(Membro membro, Lado lado){
final int posicaoCorpo = 7;
final int alturaBraco = 5;
final int alturaPerna = 7;
int alturaFinal = 0;
if(membro == Membro.braco){
pathForca.moveTo(toPixel(posicaoCorpo), toPixel(alturaBraco));
alturaFinal = alturaBraco+1;
}
if(membro == Membro.perna){
pathForca.moveTo(toPixel(posicaoCorpo), toPixel(alturaPerna));
alturaFinal = alturaPerna+1;
}
if(lado == Lado.direito) {
pathForca.lineTo(toPixel(posicaoCorpo+1), toPixel(alturaFinal));
}
if(lado == Lado.esquerdo) {
pathForca.lineTo(toPixel(posicaoCorpo-1), toPixel(alturaFinal));
}
}
private Paint getPaintForca() {
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(8);
return paint;
}
private enum Membro{braco, perna}
private enum Lado{direito,esquerdo}
}
| UTF-8 | Java | 2,770 | java | ForcaView.java | Java | [
{
"context": "port android.util.AttributeSet;\n\n/**\n * Created by eduardo on 01/01/17.\n */\n\npublic class ForcaView extends ",
"end": 248,
"score": 0.727869987487793,
"start": 241,
"tag": "USERNAME",
"value": "eduardo"
}
] | null | [] | package br.com.caelum.jogos2d;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
/**
* Created by eduardo on 01/01/17.
*/
public class ForcaView extends PlanoCartesianoView {
private Path pathForca;
public ForcaView(Context context) {
super(context);
pathForca = new Path();
}
public ForcaView(Context context, AttributeSet attrs) {
super(context, attrs);
pathForca = new Path();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// pathForca.moveTo(toPixel(2), toPixel(2));
// pathForca.lineTo(toPixel(8), toPixel(2));
plotaArmacaoForca();
plotaCabeca();
plotaCorpo();
plotaMembro(Membro.braco, Lado.direito);
plotaMembro(Membro.braco, Lado.esquerdo);
plotaMembro(Membro.perna, Lado.direito);
plotaMembro(Membro.perna, Lado.esquerdo);
canvas.drawPath(pathForca, getPaintForca());
}
private void plotaArmacaoForca(){
pathForca.moveTo(toPixel(1), toPixel(10));
pathForca.lineTo(toPixel(3), toPixel(10));
pathForca.moveTo(toPixel(2), toPixel(10));
pathForca.lineTo(toPixel(2), toPixel(1));
pathForca.rLineTo(toPixel(5), 0);
pathForca.rLineTo(0, toPixel(1));
}
private void plotaCabeca(){
pathForca.addCircle(toPixel(7), toPixel(3), toPixel(1), Path.Direction.CW);
}
private void plotaCorpo(){
pathForca.moveTo(toPixel(7), toPixel(4));
pathForca.lineTo(toPixel(7), toPixel(7));
}
private void plotaMembro(Membro membro, Lado lado){
final int posicaoCorpo = 7;
final int alturaBraco = 5;
final int alturaPerna = 7;
int alturaFinal = 0;
if(membro == Membro.braco){
pathForca.moveTo(toPixel(posicaoCorpo), toPixel(alturaBraco));
alturaFinal = alturaBraco+1;
}
if(membro == Membro.perna){
pathForca.moveTo(toPixel(posicaoCorpo), toPixel(alturaPerna));
alturaFinal = alturaPerna+1;
}
if(lado == Lado.direito) {
pathForca.lineTo(toPixel(posicaoCorpo+1), toPixel(alturaFinal));
}
if(lado == Lado.esquerdo) {
pathForca.lineTo(toPixel(posicaoCorpo-1), toPixel(alturaFinal));
}
}
private Paint getPaintForca() {
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(8);
return paint;
}
private enum Membro{braco, perna}
private enum Lado{direito,esquerdo}
}
| 2,770 | 0.625993 | 0.61083 | 102 | 26.156862 | 21.692026 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.72549 | false | false | 12 |
df9801ea4d23001db01babe6bb96c9a6bc663696 | 37,778,532,356,708 | d23b43c742816c6e6eec4b128a3f05a6e6ec3768 | /taxiapp/app/src/main/java/com/taxi/app/activity_about.java | 6f430ff944c2329f46d2559385072426338337ba | [] | no_license | mitosisX/Divala | https://github.com/mitosisX/Divala | 1e45937b473856362cf02a62d1ca1ccc4f8912fe | ad5a6622a33716e48129472ba19adfb31fe56980 | refs/heads/master | 2023-05-31T06:41:51.174000 | 2021-06-05T17:34:20 | 2021-06-05T17:34:20 | 373,943,283 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.taxi.app;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
//import android.app.ProgressDialog;
public class activity_about extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
}
} | UTF-8 | Java | 1,139 | java | activity_about.java | Java | [] | null | [] | package com.taxi.app;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
//import android.app.ProgressDialog;
public class activity_about extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
}
} | 1,139 | 0.813872 | 0.812994 | 39 | 28.23077 | 16.718578 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.717949 | false | false | 12 |
ef4873a73b5b743fa5eb3ab1935c6bb78f293f8f | 4,604,205,010,315 | 0c187502ca7dc8ba68a46777155bb255a219379a | /src/net/lintford/library/screenmanager/IContextHintProvider.java | f5a908c13f3d9ef74d4e2b1fcbcd1859ff9de818 | [] | no_license | LintfordPickle/LintfordLib | https://github.com/LintfordPickle/LintfordLib | cf0f6ff4db417f092fd14cc0c24b8304723ba096 | 103cf8fb1129d74af58991babc180597169afc83 | refs/heads/master | 2023-08-08T16:38:21.555000 | 2023-07-29T11:40:44 | 2023-07-29T11:40:44 | 47,000,429 | 9 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.lintford.library.screenmanager;
public interface IContextHintProvider {
ContextHintState contextHints();
}
| UTF-8 | Java | 123 | java | IContextHintProvider.java | Java | [] | null | [] | package net.lintford.library.screenmanager;
public interface IContextHintProvider {
ContextHintState contextHints();
}
| 123 | 0.821138 | 0.821138 | 7 | 16.571428 | 19.040237 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 12 |
63b2fe8d24c3fa75f5288ee975d7ccf53bfab76c | 24,756,191,547,204 | 7145ac52fb16b1467aa14391c39fbebdfbd36211 | /src/adapter/Application.java | 398359a55df33bdfc14acb58ba625dc3480339e2 | [
"MIT"
] | permissive | 2604150210/DesignPatterns | https://github.com/2604150210/DesignPatterns | 39938c008d7c83d8ab162d392a9aa67739d4964b | 3515d96c518e3e9f92ab426dc36d39ac155afd0b | refs/heads/master | 2021-05-09T20:33:50.582000 | 2018-04-12T11:32:15 | 2018-04-12T11:32:15 | 118,701,620 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package adapter;
/**
* Created by jal on 2018/4/6 0006.
*/
public class Application {
public static void main(String[] args) {
ThreeElectricOutlet wash = new Wash();
System.out.println("使用三相插座接通电流.");
wash.connectElectricCurent();
TV tv = new TV();
ThreeElectricAdapter threeElectricAdapter = new ThreeElectricAdapter(tv);
System.out.println("使用二相插座接通电源.");
threeElectricAdapter.connectElectricCurent();
ThreeAndTwoElectricAdapter threeAndTwoElectricAdapter = new ThreeAndTwoElectricAdapter(tv,wash);
threeAndTwoElectricAdapter.connectElectricCurent();
}
}
| UTF-8 | Java | 681 | java | Application.java | Java | [
{
"context": "package adapter;\n\n/**\n * Created by jal on 2018/4/6 0006.\n */\npublic class Application {\n",
"end": 39,
"score": 0.9988287091255188,
"start": 36,
"tag": "USERNAME",
"value": "jal"
}
] | null | [] | package adapter;
/**
* Created by jal on 2018/4/6 0006.
*/
public class Application {
public static void main(String[] args) {
ThreeElectricOutlet wash = new Wash();
System.out.println("使用三相插座接通电流.");
wash.connectElectricCurent();
TV tv = new TV();
ThreeElectricAdapter threeElectricAdapter = new ThreeElectricAdapter(tv);
System.out.println("使用二相插座接通电源.");
threeElectricAdapter.connectElectricCurent();
ThreeAndTwoElectricAdapter threeAndTwoElectricAdapter = new ThreeAndTwoElectricAdapter(tv,wash);
threeAndTwoElectricAdapter.connectElectricCurent();
}
}
| 681 | 0.695788 | 0.680187 | 19 | 32.736843 | 28.172106 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.578947 | false | false | 12 |
864237998b90fbe2800dac0e5803e6ec504d3fb4 | 5,609,227,358,594 | 7625d6edbdfe3e1405be3133fc3c60e27e1e41fd | /src/test/java/eve/tools/ApiTests.java | 9f9ffe73396f1f4ba678c40b882a6fcfb4f7c32a | [
"MIT"
] | permissive | buahaha/eve-tools | https://github.com/buahaha/eve-tools | 6bb83777a15ef34fc2a6205a540be65c0fd943c8 | 972ded951a539d5c42fe19eca7f462f131215655 | refs/heads/master | 2023-03-25T17:52:41.639000 | 2021-03-28T09:59:13 | 2021-03-28T09:59:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package eve.tools;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
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;
import eve.tools.esi.Api;
import eve.tools.esi.model.universe.UniverseName;
@RunWith(SpringRunner.class)
@SpringBootTest()
public class ApiTests {
@Autowired
private Api api;
@Test
public void universeNames() {
List<Long> ids = new ArrayList<>();
ids.add((long) 96061222); // character
List<UniverseName> actual = api.universeNames(ids);
List<UniverseName> expected = new ArrayList<>();
expected.add(new UniverseName((long) 96061222, "Tian Khamez", "character"));
assertEquals(expected, actual);
}
}
| UTF-8 | Java | 886 | java | ApiTests.java | Java | [
{
"context": "\t\texpected.add(new UniverseName((long) 96061222, \"Tian Khamez\", \"character\"));\n\n\t\tassertEquals(expected, actual",
"end": 828,
"score": 0.9982767105102539,
"start": 817,
"tag": "NAME",
"value": "Tian Khamez"
}
] | null | [] | package eve.tools;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
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;
import eve.tools.esi.Api;
import eve.tools.esi.model.universe.UniverseName;
@RunWith(SpringRunner.class)
@SpringBootTest()
public class ApiTests {
@Autowired
private Api api;
@Test
public void universeNames() {
List<Long> ids = new ArrayList<>();
ids.add((long) 96061222); // character
List<UniverseName> actual = api.universeNames(ids);
List<UniverseName> expected = new ArrayList<>();
expected.add(new UniverseName((long) 96061222, "<NAME>", "character"));
assertEquals(expected, actual);
}
}
| 881 | 0.765237 | 0.74605 | 36 | 23.611111 | 22.045757 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.027778 | false | false | 12 |
9b6bdfa0e96064feff42d16108157dd5ccdadf4b | 1,932,735,346,948 | 7354580586a330a1c1651baaa02818921469ac01 | /AksharWaveRecorder/src/com/aksharspeech/waverecorder/util/UTIL.java | 48eeacd3c894f7824d368a2b0032172588d4d2fb | [] | no_license | manikantaakshar/WaveRecorderASR | https://github.com/manikantaakshar/WaveRecorderASR | c989dacddea3b3f3f654ef2153a61c5df15c5e08 | 2841345529c235d2c4515ab84312226299a11476 | refs/heads/master | 2021-01-09T05:10:55.913000 | 2015-03-03T14:09:18 | 2015-03-03T14:09:18 | 31,699,709 | 1 | 0 | null | true | 2015-03-05T06:39:26 | 2015-03-05T06:39:26 | 2015-03-05T06:11:06 | 2015-03-03T14:10:02 | 3,932 | 0 | 0 | 0 | null | null | null | /**
*
*/
package com.aksharspeech.waverecorder.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
/**
* @author amitkumarsah
*
*/
public class UTIL {
/**
* verify that file is text file or not
* @param fname
* @return
*/
public static boolean verifyTextFile(String fname) {
if (fname.trim().endsWith(".txt"))
return true;
else
return false;
}
public static boolean savePrefernceStringValue(Context context, String key,
String value) {
SharedPreferences pref = context.getApplicationContext()
.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString(key, value);
return editor.commit();
}
public static boolean savePrefernceIntValue(Context context, String key,
int value) {
SharedPreferences pref = context.getApplicationContext()
.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putInt(key, value);
return editor.commit();
}
public static boolean savePrefernceFloatValue(Context context, String key,
float value) {
SharedPreferences pref = context.getApplicationContext()
.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putFloat(key, value);
return editor.commit();
}
public static int getPrefernceIntValue(Context context, String key,
int defValue) {
SharedPreferences pref = context.getApplicationContext()
.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
return pref.getInt(key, defValue);
}
public static float getPrefernceFloatValue(Context context, String key,
float defValue) {
SharedPreferences pref = context.getApplicationContext()
.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
return pref.getFloat(key, defValue);
}
public static Boolean getPrefernceBoolValue(Context context, String key,
Boolean defValue) {
SharedPreferences pref = context.getApplicationContext()
.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
return pref.getBoolean(key, defValue);
}
public static String getPrefernceStringValue(Context context, String key,
String defValue) {
SharedPreferences pref = context.getApplicationContext()
.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
return pref.getString(key, defValue);
}
public static boolean savePrefernceBoolValue(Context context, String key,
Boolean value) {
SharedPreferences pref = context.getApplicationContext()
.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putBoolean(key, value);
return editor.commit();
}
}
| UTF-8 | Java | 2,698 | java | UTIL.java | Java | [
{
"context": ".content.SharedPreferences.Editor;\n\n/**\n * @author amitkumarsah\n * \n */\npublic class UTIL {\n\t\n\t/**\n\t * verify tha",
"end": 208,
"score": 0.9987788796424866,
"start": 196,
"tag": "USERNAME",
"value": "amitkumarsah"
}
] | null | [] | /**
*
*/
package com.aksharspeech.waverecorder.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
/**
* @author amitkumarsah
*
*/
public class UTIL {
/**
* verify that file is text file or not
* @param fname
* @return
*/
public static boolean verifyTextFile(String fname) {
if (fname.trim().endsWith(".txt"))
return true;
else
return false;
}
public static boolean savePrefernceStringValue(Context context, String key,
String value) {
SharedPreferences pref = context.getApplicationContext()
.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString(key, value);
return editor.commit();
}
public static boolean savePrefernceIntValue(Context context, String key,
int value) {
SharedPreferences pref = context.getApplicationContext()
.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putInt(key, value);
return editor.commit();
}
public static boolean savePrefernceFloatValue(Context context, String key,
float value) {
SharedPreferences pref = context.getApplicationContext()
.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putFloat(key, value);
return editor.commit();
}
public static int getPrefernceIntValue(Context context, String key,
int defValue) {
SharedPreferences pref = context.getApplicationContext()
.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
return pref.getInt(key, defValue);
}
public static float getPrefernceFloatValue(Context context, String key,
float defValue) {
SharedPreferences pref = context.getApplicationContext()
.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
return pref.getFloat(key, defValue);
}
public static Boolean getPrefernceBoolValue(Context context, String key,
Boolean defValue) {
SharedPreferences pref = context.getApplicationContext()
.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
return pref.getBoolean(key, defValue);
}
public static String getPrefernceStringValue(Context context, String key,
String defValue) {
SharedPreferences pref = context.getApplicationContext()
.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
return pref.getString(key, defValue);
}
public static boolean savePrefernceBoolValue(Context context, String key,
Boolean value) {
SharedPreferences pref = context.getApplicationContext()
.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putBoolean(key, value);
return editor.commit();
}
}
| 2,698 | 0.74685 | 0.74685 | 96 | 27.104166 | 24.808634 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.083333 | false | false | 12 |
fc26087336d69414cf67f0922d3634409674650b | 39,307,540,734,008 | c0b51caa0eb1260498d65be42876f4e557458b8f | /src/main/java/com/fr/planet/app/json/Planet.java | 45d2d7b816823726b3892005d068f2cef82ed19b | [] | no_license | feuclem/protoplanet | https://github.com/feuclem/protoplanet | 39b990ee66f840d861f8947daf6efc6a451e333e | dd2e01ff88c34769397b0553326272e6483be8c3 | refs/heads/master | 2023-01-21T12:49:00.580000 | 2020-12-04T13:42:04 | 2020-12-04T13:42:04 | 318,338,234 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fr.planet.app.json;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import java.util.List;
@JsonAutoDetect
public class Planet {
int id;
String name;
List<Satellite> satellites;
public Planet(int id, String name, List<Satellite> satellites) {
this.id = id;
this.name = name;
this.satellites = satellites;
}
}
| UTF-8 | Java | 377 | java | Planet.java | Java | [] | null | [] | package com.fr.planet.app.json;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import java.util.List;
@JsonAutoDetect
public class Planet {
int id;
String name;
List<Satellite> satellites;
public Planet(int id, String name, List<Satellite> satellites) {
this.id = id;
this.name = name;
this.satellites = satellites;
}
}
| 377 | 0.676393 | 0.676393 | 18 | 19.944445 | 18.854626 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.611111 | false | false | 12 |
37932d0198610b8211bb97ce07e91ef719cd212f | 39,307,540,730,335 | da363cb0d401695c02054dfe0f7191e617670755 | /src/main/java/io/sample/springbootproj/DemoApiData2Application.java | a931a68895ca9293c800a260b60255deb1c984a8 | [] | no_license | mamisoumya/demo-springboot-proj | https://github.com/mamisoumya/demo-springboot-proj | 0472fa1c66ce6f9ca5f764c036a527fc3ca6f8f8 | ca137dab9d40ed8dfda32a677993d968d86bd57d | refs/heads/master | 2023-03-13T23:44:41.024000 | 2021-03-07T17:03:04 | 2021-03-07T17:03:04 | 345,400,219 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.sample.springbootproj;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApiData2Application {
public static void main(String[] args) {
SpringApplication.run(DemoApiData2Application.class, args);
}
}
| UTF-8 | Java | 329 | java | DemoApiData2Application.java | Java | [] | null | [] | package io.sample.springbootproj;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApiData2Application {
public static void main(String[] args) {
SpringApplication.run(DemoApiData2Application.class, args);
}
}
| 329 | 0.829787 | 0.823708 | 13 | 24.307692 | 24.599514 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.692308 | false | false | 12 |
cc69ea864b618725fde2678c201293a1855b6e0a | 37,503,654,462,135 | b169cd5734e8900b9e2dc9082267ade4060b384c | /imdblib/IMDb.java | 689ecbc79bb1c5c26dec4e8a4cdee00ea707e4d1 | [] | no_license | DH-MP/soen343 | https://github.com/DH-MP/soen343 | ed8ea19208ed2f5148790afc9e0017279b919881 | 5b3fc3f5303d88983fff0fbac2a6c57768460d79 | refs/heads/master | 2021-01-21T02:24:32.569000 | 2012-11-26T20:49:03 | 2012-11-26T20:49:03 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.sf.xmm.moviemanager.imdblib;
import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import net.sf.xmm.moviemanager.http.HttpUtil.HTTPResult;
import net.sf.xmm.moviemanager.models.imdb.ModelIMDbEntry;
import net.sf.xmm.moviemanager.models.imdb.ModelIMDbSearchHit;
public interface IMDb {
public HTTPResult getLastHTTPResult();
public ModelIMDbEntry getLastDataModel();
public HTTPResult getURLData(String urlID) throws Exception;
public ModelIMDbEntry grabInfo(String urlID, StringBuffer data) throws Exception;
public ModelIMDbEntry getEpisodeInfo(ModelIMDbSearchHit episode) throws Exception;
public boolean retrieveBiggerCover(ModelIMDbEntry dataModel);
public ArrayList<ModelIMDbSearchHit> getSimpleMatches(String title) throws UnsupportedEncodingException, UnknownHostException;
public ArrayList<ModelIMDbSearchHit> getSeriesMatches(String title);
public ArrayList<ModelIMDbSearchHit> getSeasons(ModelIMDbSearchHit modelSeries);
public ArrayList<ModelIMDbSearchHit> getEpisodes(ModelIMDbSearchHit modelSeason, StringBuffer stream);
public StringBuffer getEpisodesStream(ModelIMDbSearchHit modelSeason);
}
| UTF-8 | Java | 1,202 | java | IMDb.java | Java | [] | null | [] | package net.sf.xmm.moviemanager.imdblib;
import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import net.sf.xmm.moviemanager.http.HttpUtil.HTTPResult;
import net.sf.xmm.moviemanager.models.imdb.ModelIMDbEntry;
import net.sf.xmm.moviemanager.models.imdb.ModelIMDbSearchHit;
public interface IMDb {
public HTTPResult getLastHTTPResult();
public ModelIMDbEntry getLastDataModel();
public HTTPResult getURLData(String urlID) throws Exception;
public ModelIMDbEntry grabInfo(String urlID, StringBuffer data) throws Exception;
public ModelIMDbEntry getEpisodeInfo(ModelIMDbSearchHit episode) throws Exception;
public boolean retrieveBiggerCover(ModelIMDbEntry dataModel);
public ArrayList<ModelIMDbSearchHit> getSimpleMatches(String title) throws UnsupportedEncodingException, UnknownHostException;
public ArrayList<ModelIMDbSearchHit> getSeriesMatches(String title);
public ArrayList<ModelIMDbSearchHit> getSeasons(ModelIMDbSearchHit modelSeries);
public ArrayList<ModelIMDbSearchHit> getEpisodes(ModelIMDbSearchHit modelSeason, StringBuffer stream);
public StringBuffer getEpisodesStream(ModelIMDbSearchHit modelSeason);
}
| 1,202 | 0.85025 | 0.85025 | 29 | 40.448277 | 35.540737 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.275862 | false | false | 12 |
c659bd4e1a778fb6ccdb226dc64643b414ae64a6 | 3,453,153,717,578 | 6471f427b9ce36c47aae04a1a9ffb2ea5f0fc1e9 | /client/WQClientGUI.java | e720d6b92bcea0027718c52d4fb6425e5ee346a6 | [] | no_license | mvreenv/WordQuizzle | https://github.com/mvreenv/WordQuizzle | a87947b33ece54bd1f2c42ed8d771a996c0fc54d | f048917008d0111fffb101e35ff4e6465d8a54fe | refs/heads/main | 2023-07-10T03:56:27.931000 | 2021-08-11T08:04:47 | 2021-08-11T08:04:47 | 304,061,589 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package client;
import common.WQUser;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.StringReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
/**
* Classe che gestisce l'interfaccia grafica del Client di WordQuizzle.
* @author Marina Pierotti
*/
public class WQClientGUI {
/**
* Palette di colori per l'interfaccia.
*/
public static final Color DARK_BLUE = Color.decode("#252A36");
public static final Color LIGHT_BLUE = Color.decode("#425563");
public static final Color MINT_GREEN = Color.decode("#80E0A7");
public static final Color WHITE = Color.WHITE;
/**
* Frame per la costruzione della GUI del client WordQuizzle.
*/
private JFrame frame;
/**
* Pannello di login coi suoi componenti.
*/
private JPanel loginPanel;
private JTextField usernameInput; // campo per inserire lo username
private JPasswordField passwordInput; // campo per inserire la password
private JButton loginButton; // se premuto tenta il login col contenuto di usernameInput e passwordInput
private JButton registerButton; // se premuto tenta di registrare un nuovo utente con usernameInput e passwordInput
/**
* Pannello in alto alla finestra che mostra informazioni sullo username e il punteggio totale.
*/
private JPanel topPanel;
private String username; // username dell'utente loggato
private int points; // punteggio totale dell'utente loggato
private JLabel userLogged; // label per il nome
private JLabel pointsLogged; // label per i punti
/**
* Panello che mostra le operazioni svolgibili dall'utente dopo il login.
*/
private JPanel settingsPanel;
private JButton addFriendButton; // bottone per aggiungere un amico
private JButton challengeFriendButton; // bottone per sfidare un amico
private JButton showLeaderboardButton; // bottone per vedere la classifica coi propri amici
private JButton showFriendListButton; // bottone per vedere la lista degli amici (anche offline)
private JButton logoutButton; // bottone per eseguire il logout
private JTextArea textAreaAmiciOnline;
/**
* Username dell'utente sfidato.
*/
public String challenger;
/**
* Pannello dell'interfaccia della sfida coi suoi componenti.
*/
private JPanel challengePanel;
private JLabel challengerLabel; // label col nome dell'aversario
private JLabel currentWord; // parola da tradurre nel round corrente della sfida
private JTextField translationInput; // campo per inserire la parola tradotta
private JButton translateButton; // bottone per inviare il contenuto di translationInput
/**
* Costruttore.
*/
public WQClientGUI() {
super();
WQClientLink.gui = this;
frame = new JFrame("WordQuizzle");
frame.addWindowListener(new WindowListener(){
@Override
public void windowOpened(WindowEvent e) {}
@Override
public void windowClosing(WindowEvent e) {
if (username!=null) WQClientLink.client.logout(username);
}
@Override
public void windowClosed(WindowEvent e) { }
@Override
public void windowIconified(WindowEvent e) {}
@Override
public void windowDeiconified(WindowEvent e) {}
@Override
public void windowActivated(WindowEvent e) {}
@Override
public void windowDeactivated(WindowEvent e) {}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.setBackground(LIGHT_BLUE);
// Inizializzo la schermata di login e registrazione
loginPanel = new JPanel();
loginPanel.setBackground(LIGHT_BLUE);
loginPanel.setLayout(new GridBagLayout());
GridBagConstraints loginPanelConstraints = new GridBagConstraints();
JLabel usernameLabel = new JLabel("Username");
usernameLabel.setForeground(WHITE);
usernameInput = new JTextField();
usernameInput.setBackground(DARK_BLUE);
usernameInput.setForeground(WHITE);
usernameInput.setCaretColor(MINT_GREEN);
usernameLabel.setLabelFor(usernameInput);
JLabel passwordLabel = new JLabel("Password");
passwordLabel.setForeground(WHITE);
passwordInput = new JPasswordField();
passwordInput.setBackground(DARK_BLUE);
passwordInput.setForeground(WHITE);
passwordInput.setCaretColor(MINT_GREEN);
passwordInput.addKeyListener(new KeyAdapter(){
@Override
public void keyPressed(KeyEvent e){
if(e.getKeyCode()==KeyEvent.VK_ENTER) loginButton.doClick();
}
});
passwordLabel.setLabelFor(passwordInput);
loginButton = new JButton("Login");
loginButton.setBackground(DARK_BLUE);
loginButton.setForeground(MINT_GREEN);
loginButton.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
String user = usernameInput.getText();
String pw = String.copyValueOf(passwordInput.getPassword());
if(user!=null && !user.isEmpty() && !user.isBlank() && pw!=null && !pw.isEmpty() && !pw.isBlank()) {
int n = WQClientLink.client.login(user, pw);
if (n==0) { // login avvenuto con successo
try { Thread.sleep(500); }
catch (InterruptedException e ) {}
WQClientLink.client.send("online"); // chiedo al server la lista aggiornata degli utenti online
usernameInput.setText(""); // svuoto l'input username
passwordInput.setText(""); // svuoto l'input password
frame.invalidate();
frame.getContentPane().removeAll();
frame.add(topPanel, BorderLayout.NORTH);
frame.add(settingsPanel, BorderLayout.CENTER);
frame.revalidate();
frame.repaint();
}
else if (n==-1) { // password errata
WQClientGUIPopup.showMessageDialog(frame, "Password errata.", "Errore login");
}
else if (n==-2) { // utente non registrato
WQClientGUIPopup.showMessageDialog(frame, "Username non riconosciuto.", "Errore login");
}
else if (n==-3) { // l'utente è già loggato
WQClientGUIPopup.showMessageDialog(frame, "Utente già loggato.", "Errore login");
}
else if (n==-4) { // errore generico (server offline)
WQClientGUIPopup.showMessageDialog(frame, "Il Server è offline.", "Errore login");
}
}
else {
WQClientGUIPopup.showMessageDialog(frame, "Riempire i campi per favore.", "Errore login.");
}
}
});
registerButton = new JButton("Registrati");
registerButton.setBackground(DARK_BLUE);
registerButton.setForeground(WHITE);
registerButton.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
String user = usernameInput.getText();
String pw = String.copyValueOf(passwordInput.getPassword());
if(user!=null && !user.isEmpty() && !user.isBlank()) {
int n = WQClientLink.client.registra_utente(user, pw);
if (n==0) {
System.out.println(">> CLIENT >> Registrazione di " + user + " avvenuta con successo.");
WQClientGUIPopup.showMessageDialog(frame, "Registrazione avvenuta con successo.", "Esito registrazione");
usernameInput.setText("");
passwordInput.setText("");
}
else if (n==-1) {
System.out.println(">> CLIENT >> Username già registrato.");
WQClientGUIPopup.showMessageDialog(frame, "Username già registrato, registrazione non eseguita.", "Esito registrazione");
usernameInput.setText("");
passwordInput.setText("");
}
else if (n==-2) {
System.out.println(">> CLIENT >> Password vuota, registrazione non eseguita.");
WQClientGUIPopup.showMessageDialog(frame, "Password vuota, registrazione non eseguita.", "Esito registrazione");
}
else if (n==-3) {
System.out.println(">> CLIENT >> Errore di connessione al server.");
WQClientGUIPopup.showMessageDialog(frame, "Errore di connessione al Server.", "Esito registrazione");
}
}
}
});
loginPanelConstraints.fill = GridBagConstraints.HORIZONTAL;
loginPanelConstraints.insets.right = 10;
Font logoFont = new Font("WQlogo", Font.ROMAN_BASELINE, 40);
JLabel logo = new JLabel("WordQuizzle");
logo.setForeground(MINT_GREEN);
logo.setFont(logoFont);
loginPanelConstraints.gridx = 0;
loginPanelConstraints.gridy = 0;
loginPanelConstraints.gridwidth = 2;
loginPanelConstraints.insets.bottom = 20;
loginPanel.add(logo, loginPanelConstraints);
loginPanelConstraints.gridx = 0;
loginPanelConstraints.gridy = 1;
loginPanelConstraints.gridwidth = 1;
loginPanelConstraints.insets.bottom = 0;
loginPanel.add(usernameLabel, loginPanelConstraints);
loginPanelConstraints.gridx = 1;
loginPanelConstraints.gridy = 1;
loginPanel.add(usernameInput, loginPanelConstraints);
loginPanelConstraints.insets.top = 10;
loginPanelConstraints.gridx = 0;
loginPanelConstraints.gridy = 2;
loginPanel.add(passwordLabel, loginPanelConstraints);
loginPanelConstraints.gridx = 1;
loginPanelConstraints.gridy = 2;
loginPanel.add(passwordInput, loginPanelConstraints);
loginPanelConstraints.insets.top = 20;
loginPanelConstraints.insets.right = 20;
loginPanelConstraints.gridx = 0;
loginPanelConstraints.gridy = 3;
loginPanel.add(registerButton, loginPanelConstraints);
loginPanelConstraints.insets.left = 20;
loginPanelConstraints.gridx = 1;
loginPanelConstraints.gridy = 3;
loginPanel.add(loginButton, loginPanelConstraints);
// Fine inizializzazione schermata di login e registrazione
// Inizializzo il pannello con le informazioni dell'utente
topPanel = new JPanel();
topPanel.setLayout(new GridBagLayout());
GridBagConstraints topPanelConstraints = new GridBagConstraints();
userLogged = new JLabel("Utente: " + username);
pointsLogged = new JLabel("Punti: " + Integer.toString(points));
topPanel.setBackground(DARK_BLUE);
userLogged.setForeground(MINT_GREEN);
pointsLogged.setForeground(MINT_GREEN);
topPanelConstraints.gridx = 0;
topPanelConstraints.gridy = 0;
topPanelConstraints.insets.top = 10;
topPanelConstraints.insets.bottom = 10;
topPanelConstraints.insets.left = 10;
topPanelConstraints.insets.right = 30;
topPanel.add(userLogged, topPanelConstraints);
topPanelConstraints.gridx = 1;
topPanelConstraints.gridy = 0;
topPanelConstraints.insets.left = 30;
topPanelConstraints.insets.right = 10;
topPanel.add(pointsLogged, topPanelConstraints);
// Fine inizializzazione pannello con informazioni utente
// Inizializzo la schermata principale
settingsPanel = new JPanel();
settingsPanel.setBackground(LIGHT_BLUE);
settingsPanel.setLayout(new GridBagLayout());
GridBagConstraints settingsPanelConstraints = new GridBagConstraints();
addFriendButton = new JButton("Aggiungi amico");
addFriendButton.setBackground(DARK_BLUE);
addFriendButton.setForeground(WHITE);
addFriendButton.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
String friendName = JOptionPane.showInputDialog(frame, "Chi vuoi aggiungere come amico?", null);
if (friendName!=null && !friendName.isBlank() && !friendName.isEmpty()) {
try { Thread.sleep(130);}
catch (InterruptedException e ) { e.printStackTrace(); }
int n = WQClientLink.client.send("addfriend " + username + " " + friendName);
if (n==1) WQClientGUIPopup.showMessageDialog(frame, friendName + " aggiunto alla tua lista amici.", "Amico");
else if (n==0) WQClientGUIPopup.showMessageDialog(frame, "Errore formattazione dati.", "Errore amicizia.");
else if (n==-1) WQClientGUIPopup.showMessageDialog(frame, friendName + " non è un utente registrato.", "Errore amicizia.");
else if (n==-2) WQClientGUIPopup.showMessageDialog(frame, "Sei già amico di " + friendName + ".", "Errore amicizia.");
else if (n==-3) WQClientGUIPopup.showMessageDialog(frame, "Non puoi aggiungere te stesso come amico.", "Errore amicizia.");
}
}
});
settingsPanelConstraints.gridx = 0;
settingsPanelConstraints.gridy = 1;
settingsPanelConstraints.insets.bottom = 10;
settingsPanel.add(addFriendButton, settingsPanelConstraints);
challengeFriendButton = new JButton("Sfida amico");
challengeFriendButton.setBackground(DARK_BLUE);
challengeFriendButton.setForeground(WHITE);
challengeFriendButton.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
if (challenger==null) {
String friendName = JOptionPane.showInputDialog(frame, "Chi vuoi sfidare?", null);
int n = WQClientLink.client.send("challenge " + friendName);
// if (n==1) WQClientGUIPopup.showMessageDialog(frame, "Sfida inviata.", "Invio sfida.");
if (n==0) WQClientGUIPopup.showMessageDialog(frame, "Errore invio sfida.", "Invio sfida.");
challenger = friendName;
challengerLabel.setText("Sfida contro " + friendName);
}
else {
WQClientGUIPopup.showMessageDialog(frame, "Stai già aspettando una risposta ad una sfida.", "Errore sfida.");
}
}
});
settingsPanelConstraints.gridx = 0;
settingsPanelConstraints.gridy = 2;
settingsPanel.add(challengeFriendButton, settingsPanelConstraints);
showLeaderboardButton = new JButton("Mostra classifica");
showLeaderboardButton.setBackground(DARK_BLUE);
showLeaderboardButton.setForeground(WHITE);
showLeaderboardButton.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
int n = WQClientLink.client.send("leaderboard " + WQClientLink.gui.username);
if (n==0) WQClientGUIPopup.showMessageDialog(frame, "Errore classifica.", "Errore.");
}
});
settingsPanelConstraints.gridx = 0;
settingsPanelConstraints.gridy = 3;
settingsPanel.add(showLeaderboardButton, settingsPanelConstraints);
showFriendListButton = new JButton("Lista completa amici");
showFriendListButton.setBackground(DARK_BLUE);
showFriendListButton.setForeground(WHITE);
showFriendListButton.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
int n = WQClientLink.client.send("friendlist " + WQClientLink.gui.username);
if (n==0) WQClientGUIPopup.showMessageDialog(frame, "Errore lista amici.", "Errore.");
}
});
settingsPanelConstraints.gridx = 0;
settingsPanelConstraints.gridy = 4;
settingsPanel.add(showFriendListButton, settingsPanelConstraints);
logoutButton = new JButton("Logout");
logoutButton.setBackground(DARK_BLUE);
logoutButton.setForeground(WHITE);
logoutButton.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
WQClientLink.client.logout(WQClientLink.gui.username);
frame.invalidate();
frame.remove(settingsPanel);
frame.remove(topPanel);
frame.add(loginPanel, BorderLayout.CENTER);
frame.revalidate();
frame.repaint();
}
});
settingsPanelConstraints.gridx = 0;
settingsPanelConstraints.gridy = 5;
settingsPanelConstraints.insets.top = 0;
settingsPanelConstraints.insets.bottom = 0;
settingsPanel.add(logoutButton, settingsPanelConstraints);
JLabel labelAmiciOnline = new JLabel("Amici online");
labelAmiciOnline.setForeground(WHITE);
settingsPanelConstraints.gridx = 1;
settingsPanelConstraints.gridy = 0;
settingsPanelConstraints.insets.left = 50;
settingsPanelConstraints.insets.bottom = 10;
settingsPanelConstraints.insets.top = 10;
settingsPanel.add(labelAmiciOnline, settingsPanelConstraints);
textAreaAmiciOnline = new JTextArea();
textAreaAmiciOnline.setBackground(DARK_BLUE);
textAreaAmiciOnline.setForeground(MINT_GREEN);
textAreaAmiciOnline.setMargin(new Insets(10,10,10,10));
textAreaAmiciOnline.setEditable(false);
textAreaAmiciOnline.setPreferredSize(new Dimension(100, 170));
settingsPanelConstraints.gridx = 1;
settingsPanelConstraints.gridy = 1;
settingsPanelConstraints.gridheight = 6;
settingsPanelConstraints.insets.left = 50;
settingsPanelConstraints.insets.top = 0;
settingsPanel.getLayout().preferredLayoutSize(frame);
settingsPanel.add(textAreaAmiciOnline, settingsPanelConstraints);
settingsPanelConstraints.insets.top = 20;
// Fine inizializzazione schermata principale
// Inizializzo la schermata di sfida
challengePanel = new JPanel();
challengePanel.setBackground(LIGHT_BLUE);
challengePanel.setLayout(new GridBagLayout());
GridBagConstraints challengePanelConstraints = new GridBagConstraints();
challengePanelConstraints.fill = GridBagConstraints.HORIZONTAL;
challengePanelConstraints.weightx = 0.10;
challengerLabel = new JLabel("Sfida contro " + challenger);
challengerLabel.setForeground(WHITE);
challengePanelConstraints.gridx = 0;
challengePanelConstraints.gridy = 0;
challengePanelConstraints.insets.left = 30;
challengePanel.add(challengerLabel, challengePanelConstraints);
Font challengeFont = new Font("challenge", Font.TRUETYPE_FONT, 40);
currentWord = new JLabel("carico...");
currentWord.setFont(challengeFont);
currentWord.setForeground(WHITE);
currentWord.setBackground(Color.GREEN);
challengePanelConstraints.gridx = 0;
challengePanelConstraints.gridy = 1;
challengePanelConstraints.insets.top = 40;
challengePanelConstraints.insets.left = 30;
challengePanel.add(currentWord, challengePanelConstraints);
translationInput = new JTextField();
translationInput.setHorizontalAlignment(JTextField.CENTER);
translationInput.setFont(challengeFont);
translationInput.setBackground(DARK_BLUE);
translationInput.setForeground(WHITE);
translationInput.setCaretColor(MINT_GREEN);
translationInput.setSize(300, translationInput.getHeight());
challengePanelConstraints.gridx = 0;
challengePanelConstraints.gridy = 2;
challengePanelConstraints.insets.top = 20;
challengePanelConstraints.insets.left = 20;
challengePanelConstraints.insets.right = 20;
challengePanelConstraints.gridwidth = 3;
challengePanel.add(translationInput, challengePanelConstraints);
translateButton = new JButton("Traduci");
translateButton.setMargin(new Insets(10,10,10,10));
translateButton.setBackground(DARK_BLUE);
translateButton.setForeground(MINT_GREEN);
translateButton.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
// pulisco la stringa da inviare
String translation = translationInput.getText().toLowerCase().replaceAll(" ", "");
// se ho scritto qualcosa invio la parola
if(translation.length()!=0) WQClientLink.client.send("challengeanswer " + translation);
// se non ho scritto niente invio il messaggio per dire che non ho risposto
else WQClientLink.client.send("challengeanswer -1");
// pulisco il campo di input
translationInput.setText("");
}
});
translationInput.addKeyListener(new KeyAdapter(){
@Override
public void keyPressed(KeyEvent e){
if(e.getKeyCode()==KeyEvent.VK_ENTER) translateButton.doClick();
}
});
challengePanelConstraints.gridx = 1;
challengePanelConstraints.gridy = 3;
challengePanelConstraints.insets.top = 10;
challengePanelConstraints.insets.left = 0;
challengePanelConstraints.insets.right = 20;
challengePanelConstraints.gridwidth = 1;
challengePanel.getLayout().preferredLayoutSize(frame);
challengePanel.add(translateButton, challengePanelConstraints);
// Fine inizializzazione della schermata di sfida
// Panello visibile all'avvio del Client
frame.add(loginPanel, BorderLayout.CENTER);
frame.setSize(400,300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public int challengeDialog(String sfidante) {
int result = WQClientGUIPopup.showChallengeDialog(frame, sfidante);
if (result==JOptionPane.YES_OPTION); {
this.challenger = sfidante;
this.challengerLabel.setText("Sfida contro " + this.challenger);
}
return result;
}
/**
* Rende visibile la schermata di sfida.
*/
public void startChallenge() {
frame.invalidate();
frame.getContentPane().removeAll();
frame.add(challengePanel);
frame.revalidate();
frame.repaint();
}
/**
* Rende visibile la schermata principale quando termina una sfida.
*/
public void endChallenge () {
translationInput.setText("");
currentWord.setText("carico...");
currentWord.setForeground(WHITE);
frame.invalidate();
frame.getContentPane().removeAll();
if(this.username!=null) {
WQClientLink.client.send("online");
WQClientLink.client.send("userpoints");
frame.add(topPanel, BorderLayout.NORTH);
frame.add(settingsPanel, BorderLayout.CENTER);
}
else {
frame.add(loginPanel);
}
frame.revalidate();
frame.repaint();
}
/**
* Restituisce la finestra principale della GUI.
* @return La finestra della GUI.
*/
public JFrame getFrame() {
return this.frame;
}
/**
* Imposta la parola da tradurre per il round corrente della sfida e aggiorna la finestra.
* @param parola La parola da tradurre.
*/
public void setCurrentWord(String parola) {
frame.invalidate();
this.translationInput.setText("");
this.currentWord.setText(parola);
this.currentWord.setForeground(MINT_GREEN);
frame.revalidate();
frame.repaint();
}
/**
* Imposta il valore dei punti.
* @param punti I punti da impostare.
*/
public void setPoints(int punti) {
this.points = punti;
this.pointsLogged.setText("Punti: " + Integer.toString(punti));
}
/**
* Imposta username e punti dell'utente collegato con questo client.
* @param user Lo username che si vuole impostare.
* @param p I punti che si vogliono impostare.
*/
public void setUser(String user, int p) {
this.username = user;
this.points = p;
this.userLogged.setText("Utente: " + user);
this.pointsLogged.setText("Punti: " + Integer.toString(p));
}
/**
* Aggiorna la lista degli amici online.
* @param friends Nomi degli amici online separati da uno spazio (" ").
*/
public void updateOnlineFriends(String friends) {
textAreaAmiciOnline.setText("");
String[] lista = friends.split(" ");
for (int i=0; i<lista.length; i++) {
textAreaAmiciOnline.append(lista[i] + "\n");
}
}
/**
* Mostra una finestra di dialogo con il risultato della sfida.
* @param outcome Riceve "challengewon" se la sfida è stata vinta, "challengelost" se è stata persa, o "challengetie" se c'è stato un pareggio.
* @param newPoints Punteggio aggiornato dell'utente ricevuto dal Server.
*/
public void challengeResultDialog(String outcome, int newPoints) {
this.challenger = null;
// vittoria
if (outcome=="challengewon") {
WQClientGUIPopup.showMessageDialog(frame, "Hai vinto la sfida!\nHai guadagnato " + (newPoints - this.points) + " punti.\nAdesso sei a " + newPoints + " punti.", "Risultato sfida.");
}
// sconfitta
else if (outcome=="challengelost") {
WQClientGUIPopup.showMessageDialog(frame, "Hai perso la sfida!\nHai guadagnato " + (newPoints - this.points) + " punti.\nAdesso sei a " + newPoints + " punti.", "Risultato sfida.");
}
// pareggio
else if (outcome=="challengetie") {
WQClientGUIPopup.showMessageDialog(frame, "Hai pareggiato!\nHai guadagnato " + (newPoints - this.points) + " punti.\nAdesso sei a " + newPoints + " punti.", "Risultato sfida.");
}
}
/**
* Apre una finestra aggiuntiva in cui viene mostrata la classifica degli amici dell'utente.
* @param classificaJson La classifica ricevuta dal server in formato JSON.
*/
public void mostraClassifica(String classificaJson) {
Gson gson2 = new Gson();
JsonReader reader2 = new JsonReader(new StringReader(classificaJson));
reader2.setLenient(true);
Type type2 = new TypeToken<ArrayList<WQUser>>(){}.getType();
ArrayList<WQUser> classificaArray = gson2.fromJson(reader2, type2);
// se l'array ottenuto non è vuoto
if (classificaArray!=null) {
JFrame frameClassifica = new JFrame("Classifica amici di " + this.username);
JPanel panelClassifica = new JPanel();
panelClassifica.setBackground(LIGHT_BLUE);
JLabel labelClassifica = new JLabel("Classifica amici di " + this.username);
labelClassifica.setForeground(MINT_GREEN);
JTextArea textAreaClassifica = new JTextArea();
textAreaClassifica.setBackground(DARK_BLUE);
textAreaClassifica.setForeground(WHITE);
textAreaClassifica.setMargin(new Insets(10,10,0,10));
textAreaClassifica.setEditable(false);
int i = 1;
for(WQUser amico : classificaArray) {
textAreaClassifica.setText(textAreaClassifica.getText() + i + ") " + amico.username + " - " + amico.points + " punti\n");
i++;
}
panelClassifica.setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.insets.left = 10;
constraints.insets.right = 10;
constraints.insets.top = 10;
constraints.insets.bottom = 10;
constraints.gridx = 0;
constraints.gridy = 0;
panelClassifica.add(labelClassifica, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
panelClassifica.add(textAreaClassifica, constraints);
frameClassifica.add(panelClassifica);
frameClassifica.pack();
frameClassifica.setLocation(frame.getX() + frame.getWidth()/2 - frameClassifica.getWidth()/2, frame.getY() + frame.getHeight()/2 - frameClassifica.getHeight()/2);
frameClassifica.setVisible(true);
}
else {
WQClientGUIPopup.showMessageDialog(frame, "Non hai ancora amici.", "Classifica amici di " + this.username);
// JOptionPane.showMessageDialog(frame, "Non hai ancora amici.", "Classifica amici di " + this.username, JOptionPane.INFORMATION_MESSAGE);
}
}
/**
* Apre una finestra aggiuntiva in cui viene mostrata la lista completa degli amici (anche offline) dell'utente.
* @param listaJson La lista degli amici ricevuta dal server in formato JSON.
*/
public void listaAmici(String listaJson) {
Gson gson1 = new Gson();
JsonReader reader1 = new JsonReader(new StringReader(listaJson));
reader1.setLenient(true);
Type type1 = new TypeToken<ArrayList<WQUser>>(){}.getType();
ArrayList<WQUser> listaArray = gson1.fromJson(reader1, type1);
// se l'array ottenuto non è vuoto
if(listaArray!=null) {
JFrame frameLista = new JFrame("Lista amici");
JPanel panelLista = new JPanel();
panelLista.setBackground(LIGHT_BLUE);
JLabel labelLista = new JLabel("Lista amici di " + this.username);
labelLista.setForeground(MINT_GREEN);
JTextArea textAreaLista = new JTextArea();
textAreaLista.setMargin(new Insets(10,10,0,10));
textAreaLista.setBackground(DARK_BLUE);
textAreaLista.setForeground(WHITE);
textAreaLista.setEditable(false);
for(WQUser amico : listaArray) {
textAreaLista.setText(textAreaLista.getText() + "- " + amico.username + "\n");
}
panelLista.setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.insets.left = 10;
constraints.insets.right = 10;
constraints.insets.top = 10;
constraints.insets.bottom = 10;
constraints.gridx = 0;
constraints.gridy = 0;
panelLista.add(labelLista, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
panelLista.add(textAreaLista, constraints);
frameLista.add(panelLista);
frameLista.pack();
frameLista.setLocation(frame.getX() + frame.getWidth()/2 - frameLista.getWidth()/2, frame.getY() + frame.getHeight()/2 - frameLista.getHeight()/2);
frameLista.setVisible(true);
}
else {
WQClientGUIPopup.showMessageDialog(frame, "Non hai ancora amici.", "Classifica amici di " + this.username);
// JOptionPane.showMessageDialog(frame, "Non hai ancora amici.", "Lista amici di " + this.username, JOptionPane.INFORMATION_MESSAGE);
}
}
} | UTF-8 | Java | 32,957 | java | WQClientGUI.java | Java | [
{
"context": "ccia grafica del Client di WordQuizzle.\n * @author Marina Pierotti\n */\n\npublic class WQClientGUI {\n\n /**\n * P",
"end": 915,
"score": 0.9998769760131836,
"start": 900,
"tag": "NAME",
"value": "Marina Pierotti"
},
{
"context": "ame dell'utente sfidato.\n ... | null | [] | package client;
import common.WQUser;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.StringReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
/**
* Classe che gestisce l'interfaccia grafica del Client di WordQuizzle.
* @author <NAME>
*/
public class WQClientGUI {
/**
* Palette di colori per l'interfaccia.
*/
public static final Color DARK_BLUE = Color.decode("#252A36");
public static final Color LIGHT_BLUE = Color.decode("#425563");
public static final Color MINT_GREEN = Color.decode("#80E0A7");
public static final Color WHITE = Color.WHITE;
/**
* Frame per la costruzione della GUI del client WordQuizzle.
*/
private JFrame frame;
/**
* Pannello di login coi suoi componenti.
*/
private JPanel loginPanel;
private JTextField usernameInput; // campo per inserire lo username
private JPasswordField passwordInput; // campo per inserire la password
private JButton loginButton; // se premuto tenta il login col contenuto di usernameInput e passwordInput
private JButton registerButton; // se premuto tenta di registrare un nuovo utente con usernameInput e passwordInput
/**
* Pannello in alto alla finestra che mostra informazioni sullo username e il punteggio totale.
*/
private JPanel topPanel;
private String username; // username dell'utente loggato
private int points; // punteggio totale dell'utente loggato
private JLabel userLogged; // label per il nome
private JLabel pointsLogged; // label per i punti
/**
* Panello che mostra le operazioni svolgibili dall'utente dopo il login.
*/
private JPanel settingsPanel;
private JButton addFriendButton; // bottone per aggiungere un amico
private JButton challengeFriendButton; // bottone per sfidare un amico
private JButton showLeaderboardButton; // bottone per vedere la classifica coi propri amici
private JButton showFriendListButton; // bottone per vedere la lista degli amici (anche offline)
private JButton logoutButton; // bottone per eseguire il logout
private JTextArea textAreaAmiciOnline;
/**
* Username dell'utente sfidato.
*/
public String challenger;
/**
* Pannello dell'interfaccia della sfida coi suoi componenti.
*/
private JPanel challengePanel;
private JLabel challengerLabel; // label col nome dell'aversario
private JLabel currentWord; // parola da tradurre nel round corrente della sfida
private JTextField translationInput; // campo per inserire la parola tradotta
private JButton translateButton; // bottone per inviare il contenuto di translationInput
/**
* Costruttore.
*/
public WQClientGUI() {
super();
WQClientLink.gui = this;
frame = new JFrame("WordQuizzle");
frame.addWindowListener(new WindowListener(){
@Override
public void windowOpened(WindowEvent e) {}
@Override
public void windowClosing(WindowEvent e) {
if (username!=null) WQClientLink.client.logout(username);
}
@Override
public void windowClosed(WindowEvent e) { }
@Override
public void windowIconified(WindowEvent e) {}
@Override
public void windowDeiconified(WindowEvent e) {}
@Override
public void windowActivated(WindowEvent e) {}
@Override
public void windowDeactivated(WindowEvent e) {}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.setBackground(LIGHT_BLUE);
// Inizializzo la schermata di login e registrazione
loginPanel = new JPanel();
loginPanel.setBackground(LIGHT_BLUE);
loginPanel.setLayout(new GridBagLayout());
GridBagConstraints loginPanelConstraints = new GridBagConstraints();
JLabel usernameLabel = new JLabel("Username");
usernameLabel.setForeground(WHITE);
usernameInput = new JTextField();
usernameInput.setBackground(DARK_BLUE);
usernameInput.setForeground(WHITE);
usernameInput.setCaretColor(MINT_GREEN);
usernameLabel.setLabelFor(usernameInput);
JLabel passwordLabel = new JLabel("<PASSWORD>");
passwordLabel.setForeground(WHITE);
passwordInput = new JPasswordField();
passwordInput.setBackground(DARK_BLUE);
passwordInput.setForeground(WHITE);
passwordInput.setCaretColor(MINT_GREEN);
passwordInput.addKeyListener(new KeyAdapter(){
@Override
public void keyPressed(KeyEvent e){
if(e.getKeyCode()==KeyEvent.VK_ENTER) loginButton.doClick();
}
});
passwordLabel.setLabelFor(passwordInput);
loginButton = new JButton("Login");
loginButton.setBackground(DARK_BLUE);
loginButton.setForeground(MINT_GREEN);
loginButton.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
String user = usernameInput.getText();
String pw = String.copyValueOf(passwordInput.getPassword());
if(user!=null && !user.isEmpty() && !user.isBlank() && pw!=null && !pw.isEmpty() && !pw.isBlank()) {
int n = WQClientLink.client.login(user, pw);
if (n==0) { // login avvenuto con successo
try { Thread.sleep(500); }
catch (InterruptedException e ) {}
WQClientLink.client.send("online"); // chiedo al server la lista aggiornata degli utenti online
usernameInput.setText(""); // svuoto l'input username
passwordInput.setText(""); // svuoto l'input password
frame.invalidate();
frame.getContentPane().removeAll();
frame.add(topPanel, BorderLayout.NORTH);
frame.add(settingsPanel, BorderLayout.CENTER);
frame.revalidate();
frame.repaint();
}
else if (n==-1) { // password errata
WQClientGUIPopup.showMessageDialog(frame, "Password errata.", "Errore login");
}
else if (n==-2) { // utente non registrato
WQClientGUIPopup.showMessageDialog(frame, "Username non riconosciuto.", "Errore login");
}
else if (n==-3) { // l'utente è già loggato
WQClientGUIPopup.showMessageDialog(frame, "Utente già loggato.", "Errore login");
}
else if (n==-4) { // errore generico (server offline)
WQClientGUIPopup.showMessageDialog(frame, "Il Server è offline.", "Errore login");
}
}
else {
WQClientGUIPopup.showMessageDialog(frame, "Riempire i campi per favore.", "Errore login.");
}
}
});
registerButton = new JButton("Registrati");
registerButton.setBackground(DARK_BLUE);
registerButton.setForeground(WHITE);
registerButton.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
String user = usernameInput.getText();
String pw = String.copyValueOf(passwordInput.getPassword());
if(user!=null && !user.isEmpty() && !user.isBlank()) {
int n = WQClientLink.client.registra_utente(user, pw);
if (n==0) {
System.out.println(">> CLIENT >> Registrazione di " + user + " avvenuta con successo.");
WQClientGUIPopup.showMessageDialog(frame, "Registrazione avvenuta con successo.", "Esito registrazione");
usernameInput.setText("");
passwordInput.setText("");
}
else if (n==-1) {
System.out.println(">> CLIENT >> Username già registrato.");
WQClientGUIPopup.showMessageDialog(frame, "Username già registrato, registrazione non eseguita.", "Esito registrazione");
usernameInput.setText("");
passwordInput.setText("");
}
else if (n==-2) {
System.out.println(">> CLIENT >> Password vuota, registrazione non eseguita.");
WQClientGUIPopup.showMessageDialog(frame, "Password vuota, registrazione non eseguita.", "Esito registrazione");
}
else if (n==-3) {
System.out.println(">> CLIENT >> Errore di connessione al server.");
WQClientGUIPopup.showMessageDialog(frame, "Errore di connessione al Server.", "Esito registrazione");
}
}
}
});
loginPanelConstraints.fill = GridBagConstraints.HORIZONTAL;
loginPanelConstraints.insets.right = 10;
Font logoFont = new Font("WQlogo", Font.ROMAN_BASELINE, 40);
JLabel logo = new JLabel("WordQuizzle");
logo.setForeground(MINT_GREEN);
logo.setFont(logoFont);
loginPanelConstraints.gridx = 0;
loginPanelConstraints.gridy = 0;
loginPanelConstraints.gridwidth = 2;
loginPanelConstraints.insets.bottom = 20;
loginPanel.add(logo, loginPanelConstraints);
loginPanelConstraints.gridx = 0;
loginPanelConstraints.gridy = 1;
loginPanelConstraints.gridwidth = 1;
loginPanelConstraints.insets.bottom = 0;
loginPanel.add(usernameLabel, loginPanelConstraints);
loginPanelConstraints.gridx = 1;
loginPanelConstraints.gridy = 1;
loginPanel.add(usernameInput, loginPanelConstraints);
loginPanelConstraints.insets.top = 10;
loginPanelConstraints.gridx = 0;
loginPanelConstraints.gridy = 2;
loginPanel.add(passwordLabel, loginPanelConstraints);
loginPanelConstraints.gridx = 1;
loginPanelConstraints.gridy = 2;
loginPanel.add(passwordInput, loginPanelConstraints);
loginPanelConstraints.insets.top = 20;
loginPanelConstraints.insets.right = 20;
loginPanelConstraints.gridx = 0;
loginPanelConstraints.gridy = 3;
loginPanel.add(registerButton, loginPanelConstraints);
loginPanelConstraints.insets.left = 20;
loginPanelConstraints.gridx = 1;
loginPanelConstraints.gridy = 3;
loginPanel.add(loginButton, loginPanelConstraints);
// Fine inizializzazione schermata di login e registrazione
// Inizializzo il pannello con le informazioni dell'utente
topPanel = new JPanel();
topPanel.setLayout(new GridBagLayout());
GridBagConstraints topPanelConstraints = new GridBagConstraints();
userLogged = new JLabel("Utente: " + username);
pointsLogged = new JLabel("Punti: " + Integer.toString(points));
topPanel.setBackground(DARK_BLUE);
userLogged.setForeground(MINT_GREEN);
pointsLogged.setForeground(MINT_GREEN);
topPanelConstraints.gridx = 0;
topPanelConstraints.gridy = 0;
topPanelConstraints.insets.top = 10;
topPanelConstraints.insets.bottom = 10;
topPanelConstraints.insets.left = 10;
topPanelConstraints.insets.right = 30;
topPanel.add(userLogged, topPanelConstraints);
topPanelConstraints.gridx = 1;
topPanelConstraints.gridy = 0;
topPanelConstraints.insets.left = 30;
topPanelConstraints.insets.right = 10;
topPanel.add(pointsLogged, topPanelConstraints);
// Fine inizializzazione pannello con informazioni utente
// Inizializzo la schermata principale
settingsPanel = new JPanel();
settingsPanel.setBackground(LIGHT_BLUE);
settingsPanel.setLayout(new GridBagLayout());
GridBagConstraints settingsPanelConstraints = new GridBagConstraints();
addFriendButton = new JButton("Aggiungi amico");
addFriendButton.setBackground(DARK_BLUE);
addFriendButton.setForeground(WHITE);
addFriendButton.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
String friendName = JOptionPane.showInputDialog(frame, "Chi vuoi aggiungere come amico?", null);
if (friendName!=null && !friendName.isBlank() && !friendName.isEmpty()) {
try { Thread.sleep(130);}
catch (InterruptedException e ) { e.printStackTrace(); }
int n = WQClientLink.client.send("addfriend " + username + " " + friendName);
if (n==1) WQClientGUIPopup.showMessageDialog(frame, friendName + " aggiunto alla tua lista amici.", "Amico");
else if (n==0) WQClientGUIPopup.showMessageDialog(frame, "Errore formattazione dati.", "Errore amicizia.");
else if (n==-1) WQClientGUIPopup.showMessageDialog(frame, friendName + " non è un utente registrato.", "Errore amicizia.");
else if (n==-2) WQClientGUIPopup.showMessageDialog(frame, "Sei già amico di " + friendName + ".", "Errore amicizia.");
else if (n==-3) WQClientGUIPopup.showMessageDialog(frame, "Non puoi aggiungere te stesso come amico.", "Errore amicizia.");
}
}
});
settingsPanelConstraints.gridx = 0;
settingsPanelConstraints.gridy = 1;
settingsPanelConstraints.insets.bottom = 10;
settingsPanel.add(addFriendButton, settingsPanelConstraints);
challengeFriendButton = new JButton("Sfida amico");
challengeFriendButton.setBackground(DARK_BLUE);
challengeFriendButton.setForeground(WHITE);
challengeFriendButton.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
if (challenger==null) {
String friendName = JOptionPane.showInputDialog(frame, "Chi vuoi sfidare?", null);
int n = WQClientLink.client.send("challenge " + friendName);
// if (n==1) WQClientGUIPopup.showMessageDialog(frame, "Sfida inviata.", "Invio sfida.");
if (n==0) WQClientGUIPopup.showMessageDialog(frame, "Errore invio sfida.", "Invio sfida.");
challenger = friendName;
challengerLabel.setText("Sfida contro " + friendName);
}
else {
WQClientGUIPopup.showMessageDialog(frame, "Stai già aspettando una risposta ad una sfida.", "Errore sfida.");
}
}
});
settingsPanelConstraints.gridx = 0;
settingsPanelConstraints.gridy = 2;
settingsPanel.add(challengeFriendButton, settingsPanelConstraints);
showLeaderboardButton = new JButton("Mostra classifica");
showLeaderboardButton.setBackground(DARK_BLUE);
showLeaderboardButton.setForeground(WHITE);
showLeaderboardButton.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
int n = WQClientLink.client.send("leaderboard " + WQClientLink.gui.username);
if (n==0) WQClientGUIPopup.showMessageDialog(frame, "Errore classifica.", "Errore.");
}
});
settingsPanelConstraints.gridx = 0;
settingsPanelConstraints.gridy = 3;
settingsPanel.add(showLeaderboardButton, settingsPanelConstraints);
showFriendListButton = new JButton("Lista completa amici");
showFriendListButton.setBackground(DARK_BLUE);
showFriendListButton.setForeground(WHITE);
showFriendListButton.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
int n = WQClientLink.client.send("friendlist " + WQClientLink.gui.username);
if (n==0) WQClientGUIPopup.showMessageDialog(frame, "Errore lista amici.", "Errore.");
}
});
settingsPanelConstraints.gridx = 0;
settingsPanelConstraints.gridy = 4;
settingsPanel.add(showFriendListButton, settingsPanelConstraints);
logoutButton = new JButton("Logout");
logoutButton.setBackground(DARK_BLUE);
logoutButton.setForeground(WHITE);
logoutButton.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
WQClientLink.client.logout(WQClientLink.gui.username);
frame.invalidate();
frame.remove(settingsPanel);
frame.remove(topPanel);
frame.add(loginPanel, BorderLayout.CENTER);
frame.revalidate();
frame.repaint();
}
});
settingsPanelConstraints.gridx = 0;
settingsPanelConstraints.gridy = 5;
settingsPanelConstraints.insets.top = 0;
settingsPanelConstraints.insets.bottom = 0;
settingsPanel.add(logoutButton, settingsPanelConstraints);
JLabel labelAmiciOnline = new JLabel("Amici online");
labelAmiciOnline.setForeground(WHITE);
settingsPanelConstraints.gridx = 1;
settingsPanelConstraints.gridy = 0;
settingsPanelConstraints.insets.left = 50;
settingsPanelConstraints.insets.bottom = 10;
settingsPanelConstraints.insets.top = 10;
settingsPanel.add(labelAmiciOnline, settingsPanelConstraints);
textAreaAmiciOnline = new JTextArea();
textAreaAmiciOnline.setBackground(DARK_BLUE);
textAreaAmiciOnline.setForeground(MINT_GREEN);
textAreaAmiciOnline.setMargin(new Insets(10,10,10,10));
textAreaAmiciOnline.setEditable(false);
textAreaAmiciOnline.setPreferredSize(new Dimension(100, 170));
settingsPanelConstraints.gridx = 1;
settingsPanelConstraints.gridy = 1;
settingsPanelConstraints.gridheight = 6;
settingsPanelConstraints.insets.left = 50;
settingsPanelConstraints.insets.top = 0;
settingsPanel.getLayout().preferredLayoutSize(frame);
settingsPanel.add(textAreaAmiciOnline, settingsPanelConstraints);
settingsPanelConstraints.insets.top = 20;
// Fine inizializzazione schermata principale
// Inizializzo la schermata di sfida
challengePanel = new JPanel();
challengePanel.setBackground(LIGHT_BLUE);
challengePanel.setLayout(new GridBagLayout());
GridBagConstraints challengePanelConstraints = new GridBagConstraints();
challengePanelConstraints.fill = GridBagConstraints.HORIZONTAL;
challengePanelConstraints.weightx = 0.10;
challengerLabel = new JLabel("Sfida contro " + challenger);
challengerLabel.setForeground(WHITE);
challengePanelConstraints.gridx = 0;
challengePanelConstraints.gridy = 0;
challengePanelConstraints.insets.left = 30;
challengePanel.add(challengerLabel, challengePanelConstraints);
Font challengeFont = new Font("challenge", Font.TRUETYPE_FONT, 40);
currentWord = new JLabel("carico...");
currentWord.setFont(challengeFont);
currentWord.setForeground(WHITE);
currentWord.setBackground(Color.GREEN);
challengePanelConstraints.gridx = 0;
challengePanelConstraints.gridy = 1;
challengePanelConstraints.insets.top = 40;
challengePanelConstraints.insets.left = 30;
challengePanel.add(currentWord, challengePanelConstraints);
translationInput = new JTextField();
translationInput.setHorizontalAlignment(JTextField.CENTER);
translationInput.setFont(challengeFont);
translationInput.setBackground(DARK_BLUE);
translationInput.setForeground(WHITE);
translationInput.setCaretColor(MINT_GREEN);
translationInput.setSize(300, translationInput.getHeight());
challengePanelConstraints.gridx = 0;
challengePanelConstraints.gridy = 2;
challengePanelConstraints.insets.top = 20;
challengePanelConstraints.insets.left = 20;
challengePanelConstraints.insets.right = 20;
challengePanelConstraints.gridwidth = 3;
challengePanel.add(translationInput, challengePanelConstraints);
translateButton = new JButton("Traduci");
translateButton.setMargin(new Insets(10,10,10,10));
translateButton.setBackground(DARK_BLUE);
translateButton.setForeground(MINT_GREEN);
translateButton.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
// pulisco la stringa da inviare
String translation = translationInput.getText().toLowerCase().replaceAll(" ", "");
// se ho scritto qualcosa invio la parola
if(translation.length()!=0) WQClientLink.client.send("challengeanswer " + translation);
// se non ho scritto niente invio il messaggio per dire che non ho risposto
else WQClientLink.client.send("challengeanswer -1");
// pulisco il campo di input
translationInput.setText("");
}
});
translationInput.addKeyListener(new KeyAdapter(){
@Override
public void keyPressed(KeyEvent e){
if(e.getKeyCode()==KeyEvent.VK_ENTER) translateButton.doClick();
}
});
challengePanelConstraints.gridx = 1;
challengePanelConstraints.gridy = 3;
challengePanelConstraints.insets.top = 10;
challengePanelConstraints.insets.left = 0;
challengePanelConstraints.insets.right = 20;
challengePanelConstraints.gridwidth = 1;
challengePanel.getLayout().preferredLayoutSize(frame);
challengePanel.add(translateButton, challengePanelConstraints);
// Fine inizializzazione della schermata di sfida
// Panello visibile all'avvio del Client
frame.add(loginPanel, BorderLayout.CENTER);
frame.setSize(400,300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public int challengeDialog(String sfidante) {
int result = WQClientGUIPopup.showChallengeDialog(frame, sfidante);
if (result==JOptionPane.YES_OPTION); {
this.challenger = sfidante;
this.challengerLabel.setText("Sfida contro " + this.challenger);
}
return result;
}
/**
* Rende visibile la schermata di sfida.
*/
public void startChallenge() {
frame.invalidate();
frame.getContentPane().removeAll();
frame.add(challengePanel);
frame.revalidate();
frame.repaint();
}
/**
* Rende visibile la schermata principale quando termina una sfida.
*/
public void endChallenge () {
translationInput.setText("");
currentWord.setText("carico...");
currentWord.setForeground(WHITE);
frame.invalidate();
frame.getContentPane().removeAll();
if(this.username!=null) {
WQClientLink.client.send("online");
WQClientLink.client.send("userpoints");
frame.add(topPanel, BorderLayout.NORTH);
frame.add(settingsPanel, BorderLayout.CENTER);
}
else {
frame.add(loginPanel);
}
frame.revalidate();
frame.repaint();
}
/**
* Restituisce la finestra principale della GUI.
* @return La finestra della GUI.
*/
public JFrame getFrame() {
return this.frame;
}
/**
* Imposta la parola da tradurre per il round corrente della sfida e aggiorna la finestra.
* @param parola La parola da tradurre.
*/
public void setCurrentWord(String parola) {
frame.invalidate();
this.translationInput.setText("");
this.currentWord.setText(parola);
this.currentWord.setForeground(MINT_GREEN);
frame.revalidate();
frame.repaint();
}
/**
* Imposta il valore dei punti.
* @param punti I punti da impostare.
*/
public void setPoints(int punti) {
this.points = punti;
this.pointsLogged.setText("Punti: " + Integer.toString(punti));
}
/**
* Imposta username e punti dell'utente collegato con questo client.
* @param user Lo username che si vuole impostare.
* @param p I punti che si vogliono impostare.
*/
public void setUser(String user, int p) {
this.username = user;
this.points = p;
this.userLogged.setText("Utente: " + user);
this.pointsLogged.setText("Punti: " + Integer.toString(p));
}
/**
* Aggiorna la lista degli amici online.
* @param friends Nomi degli amici online separati da uno spazio (" ").
*/
public void updateOnlineFriends(String friends) {
textAreaAmiciOnline.setText("");
String[] lista = friends.split(" ");
for (int i=0; i<lista.length; i++) {
textAreaAmiciOnline.append(lista[i] + "\n");
}
}
/**
* Mostra una finestra di dialogo con il risultato della sfida.
* @param outcome Riceve "challengewon" se la sfida è stata vinta, "challengelost" se è stata persa, o "challengetie" se c'è stato un pareggio.
* @param newPoints Punteggio aggiornato dell'utente ricevuto dal Server.
*/
public void challengeResultDialog(String outcome, int newPoints) {
this.challenger = null;
// vittoria
if (outcome=="challengewon") {
WQClientGUIPopup.showMessageDialog(frame, "Hai vinto la sfida!\nHai guadagnato " + (newPoints - this.points) + " punti.\nAdesso sei a " + newPoints + " punti.", "Risultato sfida.");
}
// sconfitta
else if (outcome=="challengelost") {
WQClientGUIPopup.showMessageDialog(frame, "Hai perso la sfida!\nHai guadagnato " + (newPoints - this.points) + " punti.\nAdesso sei a " + newPoints + " punti.", "Risultato sfida.");
}
// pareggio
else if (outcome=="challengetie") {
WQClientGUIPopup.showMessageDialog(frame, "Hai pareggiato!\nHai guadagnato " + (newPoints - this.points) + " punti.\nAdesso sei a " + newPoints + " punti.", "Risultato sfida.");
}
}
/**
* Apre una finestra aggiuntiva in cui viene mostrata la classifica degli amici dell'utente.
* @param classificaJson La classifica ricevuta dal server in formato JSON.
*/
public void mostraClassifica(String classificaJson) {
Gson gson2 = new Gson();
JsonReader reader2 = new JsonReader(new StringReader(classificaJson));
reader2.setLenient(true);
Type type2 = new TypeToken<ArrayList<WQUser>>(){}.getType();
ArrayList<WQUser> classificaArray = gson2.fromJson(reader2, type2);
// se l'array ottenuto non è vuoto
if (classificaArray!=null) {
JFrame frameClassifica = new JFrame("Classifica amici di " + this.username);
JPanel panelClassifica = new JPanel();
panelClassifica.setBackground(LIGHT_BLUE);
JLabel labelClassifica = new JLabel("Classifica amici di " + this.username);
labelClassifica.setForeground(MINT_GREEN);
JTextArea textAreaClassifica = new JTextArea();
textAreaClassifica.setBackground(DARK_BLUE);
textAreaClassifica.setForeground(WHITE);
textAreaClassifica.setMargin(new Insets(10,10,0,10));
textAreaClassifica.setEditable(false);
int i = 1;
for(WQUser amico : classificaArray) {
textAreaClassifica.setText(textAreaClassifica.getText() + i + ") " + amico.username + " - " + amico.points + " punti\n");
i++;
}
panelClassifica.setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.insets.left = 10;
constraints.insets.right = 10;
constraints.insets.top = 10;
constraints.insets.bottom = 10;
constraints.gridx = 0;
constraints.gridy = 0;
panelClassifica.add(labelClassifica, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
panelClassifica.add(textAreaClassifica, constraints);
frameClassifica.add(panelClassifica);
frameClassifica.pack();
frameClassifica.setLocation(frame.getX() + frame.getWidth()/2 - frameClassifica.getWidth()/2, frame.getY() + frame.getHeight()/2 - frameClassifica.getHeight()/2);
frameClassifica.setVisible(true);
}
else {
WQClientGUIPopup.showMessageDialog(frame, "Non hai ancora amici.", "Classifica amici di " + this.username);
// JOptionPane.showMessageDialog(frame, "Non hai ancora amici.", "Classifica amici di " + this.username, JOptionPane.INFORMATION_MESSAGE);
}
}
/**
* Apre una finestra aggiuntiva in cui viene mostrata la lista completa degli amici (anche offline) dell'utente.
* @param listaJson La lista degli amici ricevuta dal server in formato JSON.
*/
public void listaAmici(String listaJson) {
Gson gson1 = new Gson();
JsonReader reader1 = new JsonReader(new StringReader(listaJson));
reader1.setLenient(true);
Type type1 = new TypeToken<ArrayList<WQUser>>(){}.getType();
ArrayList<WQUser> listaArray = gson1.fromJson(reader1, type1);
// se l'array ottenuto non è vuoto
if(listaArray!=null) {
JFrame frameLista = new JFrame("Lista amici");
JPanel panelLista = new JPanel();
panelLista.setBackground(LIGHT_BLUE);
JLabel labelLista = new JLabel("Lista amici di " + this.username);
labelLista.setForeground(MINT_GREEN);
JTextArea textAreaLista = new JTextArea();
textAreaLista.setMargin(new Insets(10,10,0,10));
textAreaLista.setBackground(DARK_BLUE);
textAreaLista.setForeground(WHITE);
textAreaLista.setEditable(false);
for(WQUser amico : listaArray) {
textAreaLista.setText(textAreaLista.getText() + "- " + amico.username + "\n");
}
panelLista.setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.insets.left = 10;
constraints.insets.right = 10;
constraints.insets.top = 10;
constraints.insets.bottom = 10;
constraints.gridx = 0;
constraints.gridy = 0;
panelLista.add(labelLista, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
panelLista.add(textAreaLista, constraints);
frameLista.add(panelLista);
frameLista.pack();
frameLista.setLocation(frame.getX() + frame.getWidth()/2 - frameLista.getWidth()/2, frame.getY() + frame.getHeight()/2 - frameLista.getHeight()/2);
frameLista.setVisible(true);
}
else {
WQClientGUIPopup.showMessageDialog(frame, "Non hai ancora amici.", "Classifica amici di " + this.username);
// JOptionPane.showMessageDialog(frame, "Non hai ancora amici.", "Lista amici di " + this.username, JOptionPane.INFORMATION_MESSAGE);
}
}
} | 32,950 | 0.633943 | 0.626567 | 762 | 42.233597 | 32.15535 | 193 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.792651 | false | false | 12 |
a20ad876000ccbe78ed15a2f004380fa6af8da8c | 23,158,463,711,010 | 857cc90324056fe9ff4d96dbc28c3ebfbdc46c95 | /src/mhst/project/usernamepassword/MainActivity.java | 59f5be62af3e057555198f394fb57b9b905cbc6d | [] | no_license | canhnht/checkUsernamePassword | https://github.com/canhnht/checkUsernamePassword | 020092c7c21a28fcb0f0e594eff33bc338a84e8d | 40f89c9a5e213be27badd47f617361a8cfb92fa1 | refs/heads/master | 2016-07-28T08:57:25.540000 | 2014-06-20T07:32:15 | 2014-06-20T07:32:15 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package mhst.project.usernamepassword;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Build;
public class MainActivity extends Activity {
final String DEFAULT_USERNAME = "zuizui";
final String DEFAULT_PASSWORD = "matkhau";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
final EditText editUsername = (EditText)findViewById(R.id.edit_username);
final EditText editPassword = (EditText)findViewById(R.id.edit_password);
final TextView resultMessage = (TextView)findViewById(R.id.result_message);
editUsername.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View view, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
checkUsernameAndPassword(editUsername, editPassword, resultMessage);
return true;
} else {
return false;
}
}
});
editPassword.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View view, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
checkUsernameAndPassword(editUsername, editPassword, resultMessage);
return true;
} else {
return false;
}
}
});
resultMessage.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
checkUsernameAndPassword(editUsername, editPassword, resultMessage);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* @param editUsername
* @param editPassword
*/
private void checkUsernameAndPassword(final EditText editUsername,
final EditText editPassword, final TextView resultMessage) {
if (editUsername.getText().toString().equals(DEFAULT_USERNAME) && editPassword.getText().toString().equals(DEFAULT_PASSWORD)) {
resultMessage.setText("Login successfully");
} else {
resultMessage.setText("Failed");
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
| UTF-8 | Java | 3,437 | java | MainActivity.java | Java | [
{
"context": "nds Activity {\n\n\tfinal String DEFAULT_USERNAME = \"zuizui\";\n\tfinal String DEFAULT_PASSWORD = \"matkhau\";\n\t\n\t",
"end": 662,
"score": 0.9995620846748352,
"start": 656,
"tag": "USERNAME",
"value": "zuizui"
},
{
"context": "AME = \"zuizui\";\n\tfinal String DEFAU... | null | [] | package mhst.project.usernamepassword;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Build;
public class MainActivity extends Activity {
final String DEFAULT_USERNAME = "zuizui";
final String DEFAULT_PASSWORD = "<PASSWORD>";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
final EditText editUsername = (EditText)findViewById(R.id.edit_username);
final EditText editPassword = (EditText)findViewById(R.id.edit_password);
final TextView resultMessage = (TextView)findViewById(R.id.result_message);
editUsername.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View view, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
checkUsernameAndPassword(editUsername, editPassword, resultMessage);
return true;
} else {
return false;
}
}
});
editPassword.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View view, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
checkUsernameAndPassword(editUsername, editPassword, resultMessage);
return true;
} else {
return false;
}
}
});
resultMessage.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
checkUsernameAndPassword(editUsername, editPassword, resultMessage);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* @param editUsername
* @param editPassword
*/
private void checkUsernameAndPassword(final EditText editUsername,
final EditText editPassword, final TextView resultMessage) {
if (editUsername.getText().toString().equals(DEFAULT_USERNAME) && editPassword.getText().toString().equals(DEFAULT_PASSWORD)) {
resultMessage.setText("Login successfully");
} else {
resultMessage.setText("Failed");
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
| 3,440 | 0.739889 | 0.739017 | 120 | 27.641666 | 26.763718 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.233333 | false | false | 12 |
7201cdeaec92dab96470bbe2fdd9ff0e3b3212b1 | 936,302,892,643 | b7abf30539bce1cdb8dc8883a7324a8afa344296 | /excel/src/main/java/com/excel/ExcelUtilsTest.java | 8a762b572e8eceaf3a5977a401ce272a8ddc83ae | [
"Apache-2.0"
] | permissive | tonels/dataFlower | https://github.com/tonels/dataFlower | aef9831d797f5b607032b070e03a362e98a0a667 | f1172fe58b73eb6c9fbbe372e8fbd65182c4cc4e | refs/heads/master | 2022-07-01T09:41:02.308000 | 2020-04-17T05:46:58 | 2020-04-17T05:46:58 | 220,606,519 | 0 | 0 | Apache-2.0 | false | 2022-06-29T17:51:51 | 2019-11-09T07:21:06 | 2020-04-17T05:47:28 | 2022-06-29T17:51:48 | 18,276 | 0 | 0 | 17 | Java | false | false | package com.excel;
import com.excel.model.Contact;
import com.excel.model.Person;
import com.excel.model.User;
import com.excel.thread.ThreadUtil;
import com.excel.util.ExcelUtils;
import com.excel.util.ExcelUtils2;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
public class ExcelUtilsTest {
private List<Person> persons;
private List<User> users;
private List<Contact> contacts;
@Before
public void setUp() {
Person p1 = new Person("A", "a@roytuts.com", "Kolkata");
Person p2 = new Person("B", "b@roytuts.com", "Mumbai");
Person p3 = new Person("C", "c@roytuts.com", "Delhi");
Person p4 = new Person("D", "d@roytuts.com", "Chennai");
Person p5 = new Person("E", "e@roytuts.com", "Bangalore");
Person p6 = new Person("F", "f@roytuts.com", "Hyderabad");
Person p7 = new Person("F", "f@roytuts.com", "Hyderabad");
Person p8 = new Person("F", "f@roytuts.com", "Hyderabad");
Person p9 = new Person("F", "f@roytuts.com", "Hyderabad");
Person p10 = new Person("F", "f@roytuts.com", "Hyderabad");
Person p11 = new Person("F", "f@roytuts.com", "Hyderabad");
Person p12 = new Person("F", "f@roytuts.com", "Hyderabad");
Person p13 = new Person("F", "f@roytuts.com", "Hyderabad");
persons = Lists.newArrayList(p1,
p2,
p3,
p4,
p5,
p6,
p7,
p8,
p9,
p10,
p11,
p12,
p13);
User u1 = new User("u1", "pwd1");
User u2 = new User("u2", "pwd2");
User u3 = new User("u3", "pwd3");
User u4 = new User("u4", "pwd4");
User u5 = new User("u5", "pwd5");
users = Lists.newArrayList(u1, u2, u3, u4, u5);
Contact c1 = new Contact("9478512354", "24157853", "24578613");
Contact c2 = new Contact("9478512354", "24157853", "24578613");
Contact c3 = new Contact("9478512354", "24157853", "24578613");
Contact c4 = new Contact("9478512354", "24157853", "24578613");
contacts = Lists.newArrayList(c1, c2, c3, c4);
}
@Test
public void testWriteToExcelInMultiSheets() {
ExcelUtils.writeToExcelInMultiSheets("D:/excel.xlsx", "Person Details", persons);
ExcelUtils.writeToExcelInMultiSheets("D:/excel.xlsx", "User Details", users);
ExcelUtils.writeToExcelInMultiSheets("D:/excel.xlsx", "Contact Details", contacts);
}
@Test
public void testBuildExcel() {
LinkedHashMap<String, String> titleMap = Maps.newLinkedHashMap();
titleMap.put("name", "姓名");
titleMap.put("email", "邮箱");
titleMap.put("address", "地址");
ExcelUtils2.buildExcel(persons, 3, "任务信息表", "2019届Person信息表", titleMap);
}
@Test
public void testSheetNum() {
int i = ExcelUtils2.getSheetNum(persons, 3);
System.out.println(i);
}
@Test
public void testThread() {
LinkedHashMap<String, String> titleMap = Maps.newLinkedHashMap();
titleMap.put("name", "姓名");
titleMap.put("email", "邮箱");
titleMap.put("address", "地址");
new Thread(new Runnable() {
@Override
public void run() {
ExcelUtils2.buildExcel(persons, 3, "任务信息表", "2019届Person信息表", titleMap);
}
}).run();
new Thread(new Runnable() {
@Override
public void run() {
ExcelUtils2.buildExcel(persons, 3, "任务信息表", "2019届Person信息表", titleMap);
}
}).run();
}
@Test
public void testThread2() {
// for (int i = 0; i < 100; i++) {
// Person p = new Person("name" + i, "email" + i, "address" + i);
// persons.add(p);
// }
// new Thread(new Runnable() {
//
// @Override
// public void run() {
// System.out.println(Thread.currentThread().getName());
// ExcelUtils.writeToExcelInMultiSheets("D://excel.xlsx", "sheet"+ Thread.currentThread().getName(), persons);
// }
// }).start();
System.out.println(Thread.currentThread().getName());
ExcelUtils.writeToExcelInMultiSheets("D:/excel.xlsx", "sheet"+ Thread.currentThread().getName(), persons);
}
@Test
public void a1(){
try {
String filename = "D:/NewExcelFile.xls" ;
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("FirstSheet");
HSSFRow rowhead = sheet.createRow((short)0);
rowhead.createCell(0).setCellValue("No.");
rowhead.createCell(1).setCellValue("Name");
rowhead.createCell(2).setCellValue("Address");
rowhead.createCell(3).setCellValue("Email");
HSSFRow row = sheet.createRow((short)1);
row.createCell(0).setCellValue("1");
row.createCell(1).setCellValue("Sankumarsingh");
row.createCell(2).setCellValue("India");
row.createCell(3).setCellValue("sankumarsingh@gmail.com");
FileOutputStream fileOut = new FileOutputStream(filename);
workbook.write(fileOut);
fileOut.close();
workbook.close();
System.out.println("Your excel file has been generated!");
} catch ( Exception ex ) {
System.out.println(ex);
}
}
@Test
public void createWorkbook(){
File file = new File("d://found.xlsx");
try {
FileOutputStream fos = new FileOutputStream(file);
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet1 = workbook.createSheet("fund1");
XSSFSheet sheet2 = workbook.createSheet("fund2");
XSSFSheet sheet3 = workbook.createSheet("fund3");
Row row = sheet1.createRow(0);
Cell cell0 = row.createCell(0);
cell0.setCellValue("Nav Value");
Cell cell1 = row.createCell(1);
cell1.setCellValue("Amount Change");
Cell cell2 = row.createCell(2);
cell2.setCellValue("Percent Change");
workbook.write(fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void thread1(){
File file = new File("d://thread1.xlsx");
new Thread(new Runnable() {
@Override
public void run() {
String name = Thread.currentThread().getName();
System.out.println(name);
try {
FileOutputStream fos = new FileOutputStream(file);
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet1 = workbook.createSheet(name);
Row row = sheet1.createRow(0);
Cell cell0 = row.createCell(0);
cell0.setCellValue("Nav Value");
Cell cell1 = row.createCell(1);
cell1.setCellValue("Amount Change");
Cell cell2 = row.createCell(2);
cell2.setCellValue("Percent Change");
workbook.write(fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
String name = Thread.currentThread().getName();
System.out.println(name);
try {
FileOutputStream fos = new FileOutputStream(file);
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet1 = workbook.createSheet(name);
Row row = sheet1.createRow(0);
Cell cell0 = row.createCell(0);
cell0.setCellValue("Navss Value");
Cell cell1 = row.createCell(1);
cell1.setCellValue("Amoussnt Change");
Cell cell2 = row.createCell(2);
cell2.setCellValue("Percssssent Change");
workbook.write(fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
try {
Thread.sleep(5000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void th1() throws InterruptedException {
String filePath = "D:/NewExcelFile.xlsx" ;
new Thread(new Athread(filePath,1)).start();
new Thread(new Athread(filePath,2)).start();
Thread.sleep(3000);
}
// @Test
// public void s
class Athread implements Runnable{
private String filePath;
private String name;
private int id;
public Athread(String filePath,int id) {
this.filePath = filePath;
this.id = id;
}
@Override
public void run() {
try {
name = Thread.currentThread().getName();
System.out.println("线程启动了" + Thread.currentThread().getName());
FileOutputStream fos = new FileOutputStream(filePath);
XSSFWorkbook workbook = new XSSFWorkbook();
workbook.setSheetName(id,name);
XSSFSheet sheet1 = workbook.getSheetAt(id);
Row row = sheet1.createRow(0);
Cell cell0 = row.createCell(0);
cell0.setCellValue("Nav Value");
Cell cell1 = row.createCell(1);
cell1.setCellValue("Amount Change");
Cell cell2 = row.createCell(2);
cell2.setCellValue("Percent Change");
workbook.write(fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void thB() throws InterruptedException, IOException {
String filename = "D:/ExcelB.xlsx" ;
XSSFWorkbook workbook = new XSSFWorkbook();
for (int i = 0; i < 5; i++) {
workbook.createSheet("sheet"+ i);
}
FileOutputStream fos = new FileOutputStream(filename);
fos.flush();
fos.close();
System.out.println(workbook.getSheetAt(0).getSheetName());
// 这里执行会出错,因为 excel 并没有生成
new Thread(new BThread(filename,1)).start();
new Thread(new BThread(filename,3)).start();
Thread.sleep(3000);
}
class BThread implements Runnable{
private String filePath;
private String name;
private int id;
public BThread(String filePath,int id) {
this.filePath = filePath;
this.id = id;
}
@Override
public void run() {
try {
name = Thread.currentThread().getName();
System.out.println("线程启动了" + Thread.currentThread().getName());
FileOutputStream fos = new FileOutputStream(filePath);
XSSFWorkbook workbook = new XSSFWorkbook();
workbook.setSheetName(id,name);
XSSFSheet sheet1 = workbook.getSheetAt(id);
Row row = sheet1.createRow(0);
Cell cell0 = row.createCell(0);
cell0.setCellValue("Nav Value");
Cell cell1 = row.createCell(1);
cell1.setCellValue("Amount Change");
Cell cell2 = row.createCell(2);
cell2.setCellValue("Percent Change");
workbook.write(fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| UTF-8 | Java | 12,858 | java | ExcelUtilsTest.java | Java | [
{
"context": "id setUp() {\n Person p1 = new Person(\"A\", \"a@roytuts.com\", \"Kolkata\");\n Person p2 = new Person(\"B\",",
"end": 1065,
"score": 0.9999249577522278,
"start": 1052,
"tag": "EMAIL",
"value": "a@roytuts.com"
},
{
"context": " \"Kolkata\");\n Perso... | null | [] | package com.excel;
import com.excel.model.Contact;
import com.excel.model.Person;
import com.excel.model.User;
import com.excel.thread.ThreadUtil;
import com.excel.util.ExcelUtils;
import com.excel.util.ExcelUtils2;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
public class ExcelUtilsTest {
private List<Person> persons;
private List<User> users;
private List<Contact> contacts;
@Before
public void setUp() {
Person p1 = new Person("A", "<EMAIL>", "Kolkata");
Person p2 = new Person("B", "<EMAIL>", "Mumbai");
Person p3 = new Person("C", "<EMAIL>", "Delhi");
Person p4 = new Person("D", "<EMAIL>", "Chennai");
Person p5 = new Person("E", "<EMAIL>", "Bangalore");
Person p6 = new Person("F", "<EMAIL>", "Hyderabad");
Person p7 = new Person("F", "<EMAIL>", "Hyderabad");
Person p8 = new Person("F", "<EMAIL>", "Hyderabad");
Person p9 = new Person("F", "<EMAIL>", "Hyderabad");
Person p10 = new Person("F", "<EMAIL>", "Hyderabad");
Person p11 = new Person("F", "<EMAIL>", "Hyderabad");
Person p12 = new Person("F", "<EMAIL>", "Hyderabad");
Person p13 = new Person("F", "<EMAIL>", "Hyderabad");
persons = Lists.newArrayList(p1,
p2,
p3,
p4,
p5,
p6,
p7,
p8,
p9,
p10,
p11,
p12,
p13);
User u1 = new User("u1", "<PASSWORD>");
User u2 = new User("u2", "<PASSWORD>");
User u3 = new User("u3", "<PASSWORD>");
User u4 = new User("u4", "<PASSWORD>");
User u5 = new User("u5", "<PASSWORD>");
users = Lists.newArrayList(u1, u2, u3, u4, u5);
Contact c1 = new Contact("9478512354", "24157853", "24578613");
Contact c2 = new Contact("9478512354", "24157853", "24578613");
Contact c3 = new Contact("9478512354", "24157853", "24578613");
Contact c4 = new Contact("9478512354", "24157853", "24578613");
contacts = Lists.newArrayList(c1, c2, c3, c4);
}
@Test
public void testWriteToExcelInMultiSheets() {
ExcelUtils.writeToExcelInMultiSheets("D:/excel.xlsx", "Person Details", persons);
ExcelUtils.writeToExcelInMultiSheets("D:/excel.xlsx", "User Details", users);
ExcelUtils.writeToExcelInMultiSheets("D:/excel.xlsx", "Contact Details", contacts);
}
@Test
public void testBuildExcel() {
LinkedHashMap<String, String> titleMap = Maps.newLinkedHashMap();
titleMap.put("name", "姓名");
titleMap.put("email", "邮箱");
titleMap.put("address", "地址");
ExcelUtils2.buildExcel(persons, 3, "任务信息表", "2019届Person信息表", titleMap);
}
@Test
public void testSheetNum() {
int i = ExcelUtils2.getSheetNum(persons, 3);
System.out.println(i);
}
@Test
public void testThread() {
LinkedHashMap<String, String> titleMap = Maps.newLinkedHashMap();
titleMap.put("name", "姓名");
titleMap.put("email", "邮箱");
titleMap.put("address", "地址");
new Thread(new Runnable() {
@Override
public void run() {
ExcelUtils2.buildExcel(persons, 3, "任务信息表", "2019届Person信息表", titleMap);
}
}).run();
new Thread(new Runnable() {
@Override
public void run() {
ExcelUtils2.buildExcel(persons, 3, "任务信息表", "2019届Person信息表", titleMap);
}
}).run();
}
@Test
public void testThread2() {
// for (int i = 0; i < 100; i++) {
// Person p = new Person("name" + i, "email" + i, "address" + i);
// persons.add(p);
// }
// new Thread(new Runnable() {
//
// @Override
// public void run() {
// System.out.println(Thread.currentThread().getName());
// ExcelUtils.writeToExcelInMultiSheets("D://excel.xlsx", "sheet"+ Thread.currentThread().getName(), persons);
// }
// }).start();
System.out.println(Thread.currentThread().getName());
ExcelUtils.writeToExcelInMultiSheets("D:/excel.xlsx", "sheet"+ Thread.currentThread().getName(), persons);
}
@Test
public void a1(){
try {
String filename = "D:/NewExcelFile.xls" ;
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("FirstSheet");
HSSFRow rowhead = sheet.createRow((short)0);
rowhead.createCell(0).setCellValue("No.");
rowhead.createCell(1).setCellValue("Name");
rowhead.createCell(2).setCellValue("Address");
rowhead.createCell(3).setCellValue("Email");
HSSFRow row = sheet.createRow((short)1);
row.createCell(0).setCellValue("1");
row.createCell(1).setCellValue("Sankumarsingh");
row.createCell(2).setCellValue("India");
row.createCell(3).setCellValue("<EMAIL>");
FileOutputStream fileOut = new FileOutputStream(filename);
workbook.write(fileOut);
fileOut.close();
workbook.close();
System.out.println("Your excel file has been generated!");
} catch ( Exception ex ) {
System.out.println(ex);
}
}
@Test
public void createWorkbook(){
File file = new File("d://found.xlsx");
try {
FileOutputStream fos = new FileOutputStream(file);
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet1 = workbook.createSheet("fund1");
XSSFSheet sheet2 = workbook.createSheet("fund2");
XSSFSheet sheet3 = workbook.createSheet("fund3");
Row row = sheet1.createRow(0);
Cell cell0 = row.createCell(0);
cell0.setCellValue("Nav Value");
Cell cell1 = row.createCell(1);
cell1.setCellValue("Amount Change");
Cell cell2 = row.createCell(2);
cell2.setCellValue("Percent Change");
workbook.write(fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void thread1(){
File file = new File("d://thread1.xlsx");
new Thread(new Runnable() {
@Override
public void run() {
String name = Thread.currentThread().getName();
System.out.println(name);
try {
FileOutputStream fos = new FileOutputStream(file);
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet1 = workbook.createSheet(name);
Row row = sheet1.createRow(0);
Cell cell0 = row.createCell(0);
cell0.setCellValue("Nav Value");
Cell cell1 = row.createCell(1);
cell1.setCellValue("Amount Change");
Cell cell2 = row.createCell(2);
cell2.setCellValue("Percent Change");
workbook.write(fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
String name = Thread.currentThread().getName();
System.out.println(name);
try {
FileOutputStream fos = new FileOutputStream(file);
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet1 = workbook.createSheet(name);
Row row = sheet1.createRow(0);
Cell cell0 = row.createCell(0);
cell0.setCellValue("Navss Value");
Cell cell1 = row.createCell(1);
cell1.setCellValue("Amoussnt Change");
Cell cell2 = row.createCell(2);
cell2.setCellValue("Percssssent Change");
workbook.write(fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
try {
Thread.sleep(5000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void th1() throws InterruptedException {
String filePath = "D:/NewExcelFile.xlsx" ;
new Thread(new Athread(filePath,1)).start();
new Thread(new Athread(filePath,2)).start();
Thread.sleep(3000);
}
// @Test
// public void s
class Athread implements Runnable{
private String filePath;
private String name;
private int id;
public Athread(String filePath,int id) {
this.filePath = filePath;
this.id = id;
}
@Override
public void run() {
try {
name = Thread.currentThread().getName();
System.out.println("线程启动了" + Thread.currentThread().getName());
FileOutputStream fos = new FileOutputStream(filePath);
XSSFWorkbook workbook = new XSSFWorkbook();
workbook.setSheetName(id,name);
XSSFSheet sheet1 = workbook.getSheetAt(id);
Row row = sheet1.createRow(0);
Cell cell0 = row.createCell(0);
cell0.setCellValue("Nav Value");
Cell cell1 = row.createCell(1);
cell1.setCellValue("Amount Change");
Cell cell2 = row.createCell(2);
cell2.setCellValue("Percent Change");
workbook.write(fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void thB() throws InterruptedException, IOException {
String filename = "D:/ExcelB.xlsx" ;
XSSFWorkbook workbook = new XSSFWorkbook();
for (int i = 0; i < 5; i++) {
workbook.createSheet("sheet"+ i);
}
FileOutputStream fos = new FileOutputStream(filename);
fos.flush();
fos.close();
System.out.println(workbook.getSheetAt(0).getSheetName());
// 这里执行会出错,因为 excel 并没有生成
new Thread(new BThread(filename,1)).start();
new Thread(new BThread(filename,3)).start();
Thread.sleep(3000);
}
class BThread implements Runnable{
private String filePath;
private String name;
private int id;
public BThread(String filePath,int id) {
this.filePath = filePath;
this.id = id;
}
@Override
public void run() {
try {
name = Thread.currentThread().getName();
System.out.println("线程启动了" + Thread.currentThread().getName());
FileOutputStream fos = new FileOutputStream(filePath);
XSSFWorkbook workbook = new XSSFWorkbook();
workbook.setSheetName(id,name);
XSSFSheet sheet1 = workbook.getSheetAt(id);
Row row = sheet1.createRow(0);
Cell cell0 = row.createCell(0);
cell0.setCellValue("Nav Value");
Cell cell1 = row.createCell(1);
cell1.setCellValue("Amount Change");
Cell cell2 = row.createCell(2);
cell2.setCellValue("Percent Change");
workbook.write(fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| 12,794 | 0.53857 | 0.515711 | 422 | 29.165876 | 24.667572 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.739336 | false | false | 12 |
7e18efc691fe3c25f27c25bd6259666a9c26537e | 27,341,761,859,937 | a2c8c803207e1d70b3eeaf3118b12863ab76711a | /core/src/main/java/io/neow3j/protocol/exceptions/StackItemCastException.java | c319b203a84c1e5a028595479e5c99243c047e81 | [
"Apache-2.0"
] | permissive | neow3j/neow3j | https://github.com/neow3j/neow3j | 833061679f506f94c73613eab7a725e8cacf0c59 | 0f87bf28aa5d9dea16aeb66cba950c307d30d5a4 | refs/heads/main | 2023-08-17T17:14:54.261000 | 2023-08-09T16:22:39 | 2023-08-09T16:22:39 | 160,731,309 | 155 | 31 | Apache-2.0 | false | 2023-09-14T16:03:43 | 2018-12-06T21:00:09 | 2023-08-26T12:14:04 | 2023-09-14T16:03:41 | 9,726 | 133 | 24 | 88 | Java | false | false | package io.neow3j.protocol.exceptions;
public class StackItemCastException extends RuntimeException {
public StackItemCastException(String message) {
super(message);
}
public StackItemCastException(Exception e) {
super(e);
}
}
| UTF-8 | Java | 263 | java | StackItemCastException.java | Java | [] | null | [] | package io.neow3j.protocol.exceptions;
public class StackItemCastException extends RuntimeException {
public StackItemCastException(String message) {
super(message);
}
public StackItemCastException(Exception e) {
super(e);
}
}
| 263 | 0.707224 | 0.703422 | 13 | 19.23077 | 21.934006 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.230769 | false | false | 12 |
c549e27e9dc35e02470ef89c683aa93f4f6abad9 | 9,216,999,839,473 | 4b63c1ea3a69f83dce93a0f8ac445e5eb664046c | /OVE/src/main/java/SupportBeans/MenuBean.java | dd20f3797f52805ad4d81ea8955a868aaf2bcc2b | [] | no_license | skjutar/OVE | https://github.com/skjutar/OVE | 18583cb6d93922a81b59ff4785ed89ddfd01b266 | 31499a9afea08bbd93c4277487ae83d6656025fd | refs/heads/master | 2016-09-06T04:04:24.235000 | 2013-10-23T20:24:44 | 2013-10-23T20:24:44 | 13,416,352 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package SupportBeans;
import Model.Account;
import EJB.SchoolRegistry;
import EJB.UserRegistry;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.el.ExpressionFactory;
import javax.el.MethodExpression;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import org.primefaces.component.menuitem.MenuItem;
import org.primefaces.model.DefaultMenuModel;
import org.primefaces.model.*;
/**
* Backing bean for MenuBean
*
* Though this could be done purely in XHTML, we initaly thought we maybe would
* need dropdowns with dynamic contents, therefore we implemented this class
*
* @author kristofferskjutar
*/
@SessionScoped
@Named("menuBean")
public class MenuBean implements Serializable {
@EJB
private SchoolRegistry registry;
@EJB
private UserRegistry uReg;
private ExpressionFactory factory = FacesContext.getCurrentInstance().getApplication().getExpressionFactory();
private MethodExpression exp = factory.createMethodExpression(FacesContext.getCurrentInstance().getELContext(), "#{loginBean.logout}", null, new Class[]{});
private Account a;
@PostConstruct
public void init() {
Long id = (Long) FacesContext.getCurrentInstance()
.getExternalContext().getSessionMap().get("id");
a = uReg.find(id);
}
/**
* returns an MenuModel with all components to added by the jsf pages
*
* @return The MenuModel
*/
public MenuModel getModel() {
MenuModel model = new DefaultMenuModel();
MenuItem menuItem = new MenuItem();
menuItem.setValue("MyPage");
menuItem.setOutcome("MyPage");
menuItem.setId("MyPage");
model.addMenuItem(menuItem);
menuItem = new MenuItem();
menuItem.setValue("Schools");
menuItem.setOutcome("Schools");
menuItem.setId("Schools");
model.addMenuItem(menuItem);
menuItem = new MenuItem();
menuItem.setValue("Tutors");
menuItem.setOutcome("Tutors");
menuItem.setId("Tutors");
model.addMenuItem(menuItem);
if (a.getPerson().isAdmin()) {
menuItem = new MenuItem();
menuItem.setValue("Admin");
menuItem.setOutcome("Admin");
model.addMenuItem(menuItem);
}
menuItem = new MenuItem();
menuItem.setValue("Logout");
menuItem.setId("Logout");
menuItem.setActionExpression(exp);
model.addMenuItem(menuItem);
return model;
}
}
| UTF-8 | Java | 2,789 | java | MenuBean.java | Java | [
{
"context": "herefore we implemented this class\r\n *\r\n * @author kristofferskjutar\r\n */\r\n@SessionScoped\r\n@Named(\"menuBean\")\r\npublic ",
"end": 851,
"score": 0.9957438707351685,
"start": 834,
"tag": "USERNAME",
"value": "kristofferskjutar"
}
] | null | [] | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package SupportBeans;
import Model.Account;
import EJB.SchoolRegistry;
import EJB.UserRegistry;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.el.ExpressionFactory;
import javax.el.MethodExpression;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import org.primefaces.component.menuitem.MenuItem;
import org.primefaces.model.DefaultMenuModel;
import org.primefaces.model.*;
/**
* Backing bean for MenuBean
*
* Though this could be done purely in XHTML, we initaly thought we maybe would
* need dropdowns with dynamic contents, therefore we implemented this class
*
* @author kristofferskjutar
*/
@SessionScoped
@Named("menuBean")
public class MenuBean implements Serializable {
@EJB
private SchoolRegistry registry;
@EJB
private UserRegistry uReg;
private ExpressionFactory factory = FacesContext.getCurrentInstance().getApplication().getExpressionFactory();
private MethodExpression exp = factory.createMethodExpression(FacesContext.getCurrentInstance().getELContext(), "#{loginBean.logout}", null, new Class[]{});
private Account a;
@PostConstruct
public void init() {
Long id = (Long) FacesContext.getCurrentInstance()
.getExternalContext().getSessionMap().get("id");
a = uReg.find(id);
}
/**
* returns an MenuModel with all components to added by the jsf pages
*
* @return The MenuModel
*/
public MenuModel getModel() {
MenuModel model = new DefaultMenuModel();
MenuItem menuItem = new MenuItem();
menuItem.setValue("MyPage");
menuItem.setOutcome("MyPage");
menuItem.setId("MyPage");
model.addMenuItem(menuItem);
menuItem = new MenuItem();
menuItem.setValue("Schools");
menuItem.setOutcome("Schools");
menuItem.setId("Schools");
model.addMenuItem(menuItem);
menuItem = new MenuItem();
menuItem.setValue("Tutors");
menuItem.setOutcome("Tutors");
menuItem.setId("Tutors");
model.addMenuItem(menuItem);
if (a.getPerson().isAdmin()) {
menuItem = new MenuItem();
menuItem.setValue("Admin");
menuItem.setOutcome("Admin");
model.addMenuItem(menuItem);
}
menuItem = new MenuItem();
menuItem.setValue("Logout");
menuItem.setId("Logout");
menuItem.setActionExpression(exp);
model.addMenuItem(menuItem);
return model;
}
}
| 2,789 | 0.655432 | 0.655432 | 89 | 29.337078 | 25.002895 | 160 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.617977 | false | false | 12 |
48aee1692de193e981cd2cfb6cd76900ada951b9 | 22,548,578,305,317 | 526e8ed604d39fe6369986026107e98f8fc8a1cd | /src/main/java/adnyre/maildemo/dao/UserDao.java | 0ec2d5be3b4ebeeddd5fb91e87d9c79e0e960cfa | [] | no_license | Adnyre/mail-demo | https://github.com/Adnyre/mail-demo | 66c864438501702d0998dc8e7a61a8baac093a7f | c24b839597dbf49f32b7ec9829e8c64b48f3278e | refs/heads/master | 2020-03-16T14:02:20.473000 | 2018-07-29T09:14:28 | 2018-07-29T09:33:35 | 132,705,814 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package adnyre.maildemo.dao;
import adnyre.maildemo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserDao extends JpaRepository<User, Long>, CustomUserDao {
} | UTF-8 | Java | 267 | java | UserDao.java | Java | [] | null | [] | package adnyre.maildemo.dao;
import adnyre.maildemo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserDao extends JpaRepository<User, Long>, CustomUserDao {
} | 267 | 0.838951 | 0.838951 | 9 | 28.777779 | 26.573914 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 12 |
1b846f347fd1e365f763fafdb37f5f477680f52b | 27,908,697,524,800 | 898ecb62fb712d9e6b8693ec4ff0a7ac934b679f | /app/src/main/java/com/example/dk/semesterproject/PaymentActivity.java | 2c3ba89de2960ac00c584e78998cef86e33d77c1 | [] | no_license | dk2823/SemesterProject | https://github.com/dk2823/SemesterProject | 3c0d7ffedcf382a63899d847b75d4aadbdb66cc7 | 986966b3dd62d4b961708703dd831ab8d00a2c5a | refs/heads/master | 2020-12-24T11:06:49.816000 | 2016-12-04T22:01:40 | 2016-12-04T22:01:40 | 73,199,373 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.dk.semesterproject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/**
* Created by Eck on 12/3/16.
*/
public class PaymentActivity extends Activity {
private EditText fullName;
private EditText cardNumber;
private EditText securityCode;
private Button mSubmit;
private Intent mIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.payment_page);
fullName= (EditText) findViewById(R.id.username_payment);
cardNumber= (EditText) findViewById(R.id.password_payment);
securityCode= (EditText) findViewById(R.id.security_payment);
mSubmit= (Button) findViewById(R.id.submitButton_payment);
Intent prevIntent= getIntent();
if(!prevIntent.hasExtra(OrderActivity.INGREDIENTS)){
throw new IllegalArgumentException("There's no ingredient");
}
final String ingredientIds = prevIntent.getExtras().getString(OrderActivity.INGREDIENTS);
mSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!fullName.getText().toString().trim().equals("") &&
!cardNumber.getText().toString().trim().equals("") &&
!securityCode.getText().toString().trim().equals("")) {
mIntent= new Intent(PaymentActivity.this, OrderSentActivity.class);
mIntent.putExtra(OrderActivity.INGREDIENTS, ingredientIds);
startActivity(mIntent);
} else {
Toast.makeText(PaymentActivity.this, R.string.entry_missing,
Toast.LENGTH_LONG).show();
}
}
});
}
}
| UTF-8 | Java | 1,992 | java | PaymentActivity.java | Java | [
{
"context": "t;\nimport android.widget.Toast;\n\n/**\n * Created by Eck on 12/3/16.\n */\n\npublic class PaymentActivity ext",
"end": 266,
"score": 0.8092341423034668,
"start": 263,
"tag": "USERNAME",
"value": "Eck"
}
] | null | [] | package com.example.dk.semesterproject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/**
* Created by Eck on 12/3/16.
*/
public class PaymentActivity extends Activity {
private EditText fullName;
private EditText cardNumber;
private EditText securityCode;
private Button mSubmit;
private Intent mIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.payment_page);
fullName= (EditText) findViewById(R.id.username_payment);
cardNumber= (EditText) findViewById(R.id.password_payment);
securityCode= (EditText) findViewById(R.id.security_payment);
mSubmit= (Button) findViewById(R.id.submitButton_payment);
Intent prevIntent= getIntent();
if(!prevIntent.hasExtra(OrderActivity.INGREDIENTS)){
throw new IllegalArgumentException("There's no ingredient");
}
final String ingredientIds = prevIntent.getExtras().getString(OrderActivity.INGREDIENTS);
mSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!fullName.getText().toString().trim().equals("") &&
!cardNumber.getText().toString().trim().equals("") &&
!securityCode.getText().toString().trim().equals("")) {
mIntent= new Intent(PaymentActivity.this, OrderSentActivity.class);
mIntent.putExtra(OrderActivity.INGREDIENTS, ingredientIds);
startActivity(mIntent);
} else {
Toast.makeText(PaymentActivity.this, R.string.entry_missing,
Toast.LENGTH_LONG).show();
}
}
});
}
}
| 1,992 | 0.635542 | 0.633032 | 57 | 33.947369 | 27.565821 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.54386 | false | false | 12 |
682615c9ec7c877aed282b2372bdf5bd4e062152 | 8,778,913,199,180 | 503f127341559050e81064130f419bacd1f2d2d5 | /JAVAAlgorithm/src/javaAlgorithm/JavaWork05.java | 7f3d3495de4ceb8a611842b18e64dd8325b37ebe | [] | no_license | zj7/JY3-Java | https://github.com/zj7/JY3-Java | 2302c4c8fe38846ed0a9b0907cbba9102a81ac23 | ed8558c3aea97c97ce090b16ce1fd91549d31c80 | refs/heads/master | 2020-05-04T16:14:38.578000 | 2019-04-23T12:55:32 | 2019-04-23T12:55:32 | 179,272,624 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package javaAlgorithm;
import java.util.Scanner;
public class JavaWork05 {
public static void main(String[] args) {
//三目运算符嵌套
Scanner scanner = new Scanner(System.in);
System.out.println("请输入成绩:");
int score = scanner.nextInt();
System.out.println(score >= 90 ? "A":(score>=60?"B":"C"));
scanner.close();
}
}
| GB18030 | Java | 351 | java | JavaWork05.java | Java | [] | null | [] | package javaAlgorithm;
import java.util.Scanner;
public class JavaWork05 {
public static void main(String[] args) {
//三目运算符嵌套
Scanner scanner = new Scanner(System.in);
System.out.println("请输入成绩:");
int score = scanner.nextInt();
System.out.println(score >= 90 ? "A":(score>=60?"B":"C"));
scanner.close();
}
}
| 351 | 0.673846 | 0.655385 | 14 | 22.214285 | 17.708668 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.5 | false | false | 12 |
39ab7f963599866c7c4eaf15bbe1f66b2c9150e6 | 26,319,559,629,837 | c283fdda7cd9aef3f9e132a0a1b31e85f2596d7e | /smart-algorithm/src/main/java/com/smart/algorithm/sort/RadixSort1.java | 83627dfb9bc4da5fa2f8f0f7c8e629b75eb6832b | [] | no_license | wangfengchao/smart | https://github.com/wangfengchao/smart | 72449d183df0f9e6cff3827dc2a6ffd313be6bd7 | 9d58aebebf7a7a0bbd57d38a5529cfe9edbd3b68 | refs/heads/master | 2021-09-12T19:24:07.680000 | 2018-04-20T03:26:41 | 2018-04-20T03:26:41 | 73,781,462 | 8 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.smart.algorithm.sort;
import java.util.Arrays;
/**
* Created by fc.w on 2017/2/7.
*/
public class RadixSort1 {
public static void main(String[] args) {
int[] array = {3,2,3,2,5,333,45566,2345678,78,990,12,432,56};
radixSort(array,10,7);
for (int i = 0; i < array.length; i++) {
System.out.print(" " + array[i]);
}
}
/**
*
* @param array 待排序数组
* @param radix 基数
* @param distance
*/
private static void radixSort(int[] array, int radix, int distance) {
int length = array.length;
// 用于暂存元素
int[] temp = new int[length];
// 用于计数排序
int[] count = new int[radix];
int divide = 1;
for (int i = 0; i < distance; i++) {
System.arraycopy(array, 0, temp, 0, length);
Arrays.fill(count, 0);
for (int j = 0; j < length; j++) {
int tempKey = (temp[j] / divide) % radix;
count[tempKey]++;
}
for (int j = 1; j < radix; j++) {
count[j] = count[j] + count[j - 1];
}
for (int j = length - 1; j >= 0; j--) {
int tempKey = (temp[j] / divide) % radix;
count[tempKey]--;
array[count[tempKey]] = temp[j];
}
divide = divide * radix;
}
}
}
| UTF-8 | Java | 1,435 | java | RadixSort1.java | Java | [
{
"context": "ort;\n\nimport java.util.Arrays;\n\n/**\n * Created by fc.w on 2017/2/7.\n */\npublic class RadixSort1 {\n\n p",
"end": 84,
"score": 0.9996262192726135,
"start": 80,
"tag": "USERNAME",
"value": "fc.w"
}
] | null | [] | package com.smart.algorithm.sort;
import java.util.Arrays;
/**
* Created by fc.w on 2017/2/7.
*/
public class RadixSort1 {
public static void main(String[] args) {
int[] array = {3,2,3,2,5,333,45566,2345678,78,990,12,432,56};
radixSort(array,10,7);
for (int i = 0; i < array.length; i++) {
System.out.print(" " + array[i]);
}
}
/**
*
* @param array 待排序数组
* @param radix 基数
* @param distance
*/
private static void radixSort(int[] array, int radix, int distance) {
int length = array.length;
// 用于暂存元素
int[] temp = new int[length];
// 用于计数排序
int[] count = new int[radix];
int divide = 1;
for (int i = 0; i < distance; i++) {
System.arraycopy(array, 0, temp, 0, length);
Arrays.fill(count, 0);
for (int j = 0; j < length; j++) {
int tempKey = (temp[j] / divide) % radix;
count[tempKey]++;
}
for (int j = 1; j < radix; j++) {
count[j] = count[j] + count[j - 1];
}
for (int j = length - 1; j >= 0; j--) {
int tempKey = (temp[j] / divide) % radix;
count[tempKey]--;
array[count[tempKey]] = temp[j];
}
divide = divide * radix;
}
}
}
| 1,435 | 0.456693 | 0.418754 | 54 | 24.870371 | 20.445089 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.907407 | false | false | 12 |
b52399e5339dff9077fbc94023095eaab005923d | 20,942,260,570,881 | f1d78dc5cd93b19919da17cf4943575eafcc9394 | /jCoapSniffer/src/jCoapParser/IPv6Packet.java | c249bdb72864f11b0b28e23f7d22249c62fbe88c | [] | no_license | kincki/recep | https://github.com/kincki/recep | 19ff5b74c843724d26a2f1e8eba78c07fa9b801e | 46fd484d50bebdbddeda6f548dccdc93c83c823a | refs/heads/master | 2021-01-21T13:52:38.495000 | 2016-05-17T20:59:26 | 2016-05-17T20:59:26 | 50,204,601 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package jCoapParser;
import net.sourceforge.jpcap.net.RawPacket;
import java.nio.ByteBuffer;
import java.net.InetAddress;
/**
* @author root
*
*/
public class IPv6Packet {
private final short RAW_FRAME_HEADER_LENGTH = 16; /* this much data will be discarded */
private final short IP_CLASS_LENGTH = 4;
private final short IP6_ADDR_LENGTH = 16;
private byte[] rawData; //original raw packet arrived
private byte[] macData; //mac layer data, not used for now
private byte[] ipClassData;
private short payloadLength; // length of the IPv6 Payload
private byte nextHdr; // what is the protocol in payload
private byte hopLimit; // what is the hop limit for this packet
private byte [] sourceIP; // 16byte long source IPv6 address
private byte [] destIP; // 16byte long source IPv6 address
private long timeOfArrival; // time of arrival for this packet
UDPacket payload; //the whole UDP packet
/*
* Parse incoming RawPacket into this IPv6 packet format
*
*/
public IPv6Packet(RawPacket packet) {
this.rawData = packet.getData();
}
public void parseRawData() {
//This wrapper is used over and over again to retrieve packet details
ByteBuffer wrapper = ByteBuffer.wrap(rawData);
this.timeOfArrival = System.currentTimeMillis();
try {
//strip-off mac data
this.macData = new byte[RAW_FRAME_HEADER_LENGTH];
wrapper.get(this.macData);
//strip-off ipclass data
this.ipClassData = new byte[IP_CLASS_LENGTH];
wrapper.get(this.ipClassData);
//payload_length is represented with two (2) bytes
this.payloadLength = wrapper.getShort();
//next header is represented with one (1) byte
//add 2 to the beginning offset to account for 2 bytes of payload field
this.nextHdr = wrapper.get();
//hop limit is represented with one (1) byte
this.hopLimit = wrapper.get();
//source address is 16 bytes
this.sourceIP = new byte[IP6_ADDR_LENGTH];
wrapper.get(this.sourceIP);
//destination address is 16 bytes
this.destIP = new byte[IP6_ADDR_LENGTH];
wrapper.get(this.destIP);
//UDP payload is payloadLength length
byte[] udpPayload = new byte[this.payloadLength];
wrapper.get(udpPayload);
this.payload = new UDPacket(udpPayload);
//If the UDP packet is parsed correctly, then we can setup coap parser for this source IP
if (this.payload.isCoap()) {
if (this.payload.getCOAP_PORT() == this.payload.getSourcePort())
this.payload.getCoapPacket().setRawData(InetAddress.getByAddress(this.getSourceIPAddress().toString(), this.getSourceIPAddress()), this.payload.getSourcePort());
else
this.payload.getCoapPacket().setRawData(InetAddress.getByAddress(this.getDestIPAddress().toString(), this.getDestIPAddress()), this.payload.getDestPort());
this.payload.getCoapPacket().parseMessage();
if (this.payload.getCoapPacket().isEmptyMessage())
System.out.println("Empty Message");
else if (this.payload.getCoapPacket().isRequest())
System.out.println("Request: " + this.payload.getCoapPacket().getRequest().getPayloadString());
else if (this.payload.getCoapPacket().isResponse())
System.out.println("Response: " + this.payload.getCoapPacket().getResponse().getPayloadString());
else
System.out.println("Bu NE MESAJI BOYLE?");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public final byte [] getSourceIPAddress() {
return sourceIP;
}
public void setSourceIPAddress(byte [] source) {
this.sourceIP = source;
}
public final byte [] getDestIPAddress () {
return destIP;
}
}
| UTF-8 | Java | 3,630 | java | IPv6Packet.java | Java | [
{
"context": "ffer;\nimport java.net.InetAddress;\n\n/**\n * @author root\n *\n */\npublic class IPv6Packet {\n\t\n\tprivate final",
"end": 155,
"score": 0.9990320205688477,
"start": 151,
"tag": "USERNAME",
"value": "root"
}
] | null | [] | /**
*
*/
package jCoapParser;
import net.sourceforge.jpcap.net.RawPacket;
import java.nio.ByteBuffer;
import java.net.InetAddress;
/**
* @author root
*
*/
public class IPv6Packet {
private final short RAW_FRAME_HEADER_LENGTH = 16; /* this much data will be discarded */
private final short IP_CLASS_LENGTH = 4;
private final short IP6_ADDR_LENGTH = 16;
private byte[] rawData; //original raw packet arrived
private byte[] macData; //mac layer data, not used for now
private byte[] ipClassData;
private short payloadLength; // length of the IPv6 Payload
private byte nextHdr; // what is the protocol in payload
private byte hopLimit; // what is the hop limit for this packet
private byte [] sourceIP; // 16byte long source IPv6 address
private byte [] destIP; // 16byte long source IPv6 address
private long timeOfArrival; // time of arrival for this packet
UDPacket payload; //the whole UDP packet
/*
* Parse incoming RawPacket into this IPv6 packet format
*
*/
public IPv6Packet(RawPacket packet) {
this.rawData = packet.getData();
}
public void parseRawData() {
//This wrapper is used over and over again to retrieve packet details
ByteBuffer wrapper = ByteBuffer.wrap(rawData);
this.timeOfArrival = System.currentTimeMillis();
try {
//strip-off mac data
this.macData = new byte[RAW_FRAME_HEADER_LENGTH];
wrapper.get(this.macData);
//strip-off ipclass data
this.ipClassData = new byte[IP_CLASS_LENGTH];
wrapper.get(this.ipClassData);
//payload_length is represented with two (2) bytes
this.payloadLength = wrapper.getShort();
//next header is represented with one (1) byte
//add 2 to the beginning offset to account for 2 bytes of payload field
this.nextHdr = wrapper.get();
//hop limit is represented with one (1) byte
this.hopLimit = wrapper.get();
//source address is 16 bytes
this.sourceIP = new byte[IP6_ADDR_LENGTH];
wrapper.get(this.sourceIP);
//destination address is 16 bytes
this.destIP = new byte[IP6_ADDR_LENGTH];
wrapper.get(this.destIP);
//UDP payload is payloadLength length
byte[] udpPayload = new byte[this.payloadLength];
wrapper.get(udpPayload);
this.payload = new UDPacket(udpPayload);
//If the UDP packet is parsed correctly, then we can setup coap parser for this source IP
if (this.payload.isCoap()) {
if (this.payload.getCOAP_PORT() == this.payload.getSourcePort())
this.payload.getCoapPacket().setRawData(InetAddress.getByAddress(this.getSourceIPAddress().toString(), this.getSourceIPAddress()), this.payload.getSourcePort());
else
this.payload.getCoapPacket().setRawData(InetAddress.getByAddress(this.getDestIPAddress().toString(), this.getDestIPAddress()), this.payload.getDestPort());
this.payload.getCoapPacket().parseMessage();
if (this.payload.getCoapPacket().isEmptyMessage())
System.out.println("Empty Message");
else if (this.payload.getCoapPacket().isRequest())
System.out.println("Request: " + this.payload.getCoapPacket().getRequest().getPayloadString());
else if (this.payload.getCoapPacket().isResponse())
System.out.println("Response: " + this.payload.getCoapPacket().getResponse().getPayloadString());
else
System.out.println("Bu NE MESAJI BOYLE?");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public final byte [] getSourceIPAddress() {
return sourceIP;
}
public void setSourceIPAddress(byte [] source) {
this.sourceIP = source;
}
public final byte [] getDestIPAddress () {
return destIP;
}
}
| 3,630 | 0.702479 | 0.695041 | 117 | 30.02564 | 30.64728 | 166 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.529915 | false | false | 12 |
43d42b15084ca8db9cad8f44ab5e7392e452eaaa | 30,915,174,625,143 | f5d3905e250565dd0f106b0155345bc5d6556dd4 | /src/main/java/au/com/digitalspider/webgpio/controller/ErrorController.java | 8be86e673221c23d6a72c489eb025afd7d0100b7 | [
"Apache-2.0"
] | permissive | digitalspider/webgpio | https://github.com/digitalspider/webgpio | 5fa65f902e800cd3175ac944a1285fdef88d0666 | 0cb53ea23ec2a49747b143dcc2a34e014bed38df | refs/heads/master | 2021-01-22T13:52:19.548000 | 2017-08-19T22:56:04 | 2017-08-19T22:56:04 | 100,695,721 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package au.com.digitalspider.webgpio.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/error")
public class ErrorController {
@RequestMapping(method = RequestMethod.GET, path = "")
public String handleNotFound() {
return "The page you request could not be found!";
}
}
| UTF-8 | Java | 444 | java | ErrorController.java | Java | [] | null | [] | package au.com.digitalspider.webgpio.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/error")
public class ErrorController {
@RequestMapping(method = RequestMethod.GET, path = "")
public String handleNotFound() {
return "The page you request could not be found!";
}
}
| 444 | 0.797297 | 0.797297 | 15 | 28.6 | 23.762156 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.733333 | false | false | 12 |
afb1fdda70f3848ababa15ac304214f19d1e2695 | 28,561,532,527,702 | e8a932de25e25cc4629109d8abb60542fae84465 | /src/com/ibatis/sqlmap/implgen/bean/ParsedClass.java | d42e720b4e16e11d3438e71326fee4cc51ce048d | [
"BSD-3-Clause"
] | permissive | paultuckey/ibatis-implgen | https://github.com/paultuckey/ibatis-implgen | 569cb7bfd254bd810dff2600034a1043b32c7918 | f9580b56a7fdba543cd769512a293a5e909e15cf | refs/heads/master | 2023-08-27T07:35:21.788000 | 2015-03-13T21:53:50 | 2015-03-13T21:53:50 | 32,114,032 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Copyright 2007 Paul Tuckey
*
* 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.ibatis.sqlmap.implgen.bean;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class ParsedClass {
private ParsedMethod.Type overrideXmlType;
private static final String GENERATED_FILE_SUFFIX = "GeneratedSqlMap";
private String name = "";
private String packageStr = "";
private List<ParsedMethod> methods = new ArrayList<ParsedMethod>();
private List<ParsedCacheModel> cacheModels = new ArrayList<ParsedCacheModel>();
private List<ParsedResultMap> resultMaps = new ArrayList<ParsedResultMap>();
private List<ParsedParameterMap> parameterMaps = new ArrayList<ParsedParameterMap>();
private File classFile;
private boolean classAnInterface;
private String forceExtendClass;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<ParsedMethod> getMethods() {
return methods;
}
public String getPackageStr() {
return packageStr;
}
public void setPackageStr(String packageStr) {
this.packageStr = packageStr;
}
public File getClassFile() {
return classFile;
}
public void setClassFile(File classFile) {
this.classFile = classFile;
}
public String getFullyQualifiedName() {
return packageStr + "." + name;
}
public String getGeneratedXmlFileName() {
return name + GENERATED_FILE_SUFFIX + ".xml";
}
public String getGeneratedXmlFilePath() {
return getPackageStr().replace('.', '/') + '/' + getGeneratedXmlFileName();
}
public String getGeneratedJavaClassName() {
return name + GENERATED_FILE_SUFFIX;
}
public String getGeneratedJavaClassFullyQualifiedName() {
return getFullyQualifiedName() + GENERATED_FILE_SUFFIX;
}
public List<ParsedCacheModel> getCacheModels() {
return cacheModels;
}
public List<ParsedResultMap> getResultMaps() {
return resultMaps;
}
public void setClassAnInterface(boolean classAnInterface) {
this.classAnInterface = classAnInterface;
}
public boolean isAnySQLMethods() {
for (ParsedMethod method : methods) {
if ( method.isSqlMethod() ) return true;
}
return false;
}
public ParsedMethod.Type getOverrideXmlType() {
return overrideXmlType;
}
public void setOverrideXmlType(ParsedMethod.Type overrideXmlType) {
this.overrideXmlType = overrideXmlType;
}
public boolean isClassAnInterface() {
return classAnInterface;
}
public List<ParsedParameterMap> getParameterMaps() {
return parameterMaps;
}
public void setForceExtendClass(String forceExtendClass) {
this.forceExtendClass = forceExtendClass;
}
public String getForceExtendClass() {
return forceExtendClass == null ? "SqlMapDaoTemplate" : forceExtendClass;
}
}
| UTF-8 | Java | 3,711 | java | ParsedClass.java | Java | [
{
"context": "/**\r\n * Copyright 2007 Paul Tuckey\r\n *\r\n * Licensed under the Apache License, Versi",
"end": 34,
"score": 0.9997584819793701,
"start": 23,
"tag": "NAME",
"value": "Paul Tuckey"
}
] | null | [] | /**
* Copyright 2007 <NAME>
*
* 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.ibatis.sqlmap.implgen.bean;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class ParsedClass {
private ParsedMethod.Type overrideXmlType;
private static final String GENERATED_FILE_SUFFIX = "GeneratedSqlMap";
private String name = "";
private String packageStr = "";
private List<ParsedMethod> methods = new ArrayList<ParsedMethod>();
private List<ParsedCacheModel> cacheModels = new ArrayList<ParsedCacheModel>();
private List<ParsedResultMap> resultMaps = new ArrayList<ParsedResultMap>();
private List<ParsedParameterMap> parameterMaps = new ArrayList<ParsedParameterMap>();
private File classFile;
private boolean classAnInterface;
private String forceExtendClass;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<ParsedMethod> getMethods() {
return methods;
}
public String getPackageStr() {
return packageStr;
}
public void setPackageStr(String packageStr) {
this.packageStr = packageStr;
}
public File getClassFile() {
return classFile;
}
public void setClassFile(File classFile) {
this.classFile = classFile;
}
public String getFullyQualifiedName() {
return packageStr + "." + name;
}
public String getGeneratedXmlFileName() {
return name + GENERATED_FILE_SUFFIX + ".xml";
}
public String getGeneratedXmlFilePath() {
return getPackageStr().replace('.', '/') + '/' + getGeneratedXmlFileName();
}
public String getGeneratedJavaClassName() {
return name + GENERATED_FILE_SUFFIX;
}
public String getGeneratedJavaClassFullyQualifiedName() {
return getFullyQualifiedName() + GENERATED_FILE_SUFFIX;
}
public List<ParsedCacheModel> getCacheModels() {
return cacheModels;
}
public List<ParsedResultMap> getResultMaps() {
return resultMaps;
}
public void setClassAnInterface(boolean classAnInterface) {
this.classAnInterface = classAnInterface;
}
public boolean isAnySQLMethods() {
for (ParsedMethod method : methods) {
if ( method.isSqlMethod() ) return true;
}
return false;
}
public ParsedMethod.Type getOverrideXmlType() {
return overrideXmlType;
}
public void setOverrideXmlType(ParsedMethod.Type overrideXmlType) {
this.overrideXmlType = overrideXmlType;
}
public boolean isClassAnInterface() {
return classAnInterface;
}
public List<ParsedParameterMap> getParameterMaps() {
return parameterMaps;
}
public void setForceExtendClass(String forceExtendClass) {
this.forceExtendClass = forceExtendClass;
}
public String getForceExtendClass() {
return forceExtendClass == null ? "SqlMapDaoTemplate" : forceExtendClass;
}
}
| 3,706 | 0.657774 | 0.655618 | 127 | 27.188976 | 25.569338 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.346457 | false | false | 12 |
3cfd40b9b1b0b909a14be7920f0329dbeae738b4 | 25,134,148,631,792 | 6fd165acd0704d8a8659b27b10c6ef56b98dbc9d | /Character.java | eed89b63fb2382e79ba269954b676ec13d0c3398 | [] | no_license | calvinvuong/YoRPG_DLC | https://github.com/calvinvuong/YoRPG_DLC | 2582b18be3b40e57782ee1946ed6b48d72004723 | 1ef5cc6e07783d8e9faf781849e501b6cc103f76 | refs/heads/master | 2021-01-10T12:59:14.903000 | 2015-11-17T03:47:41 | 2015-11-17T03:47:41 | 46,321,462 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // DLC -- Derek Lin, Lisa Shi, Calvin Vuong
// APCS1 pd5
// HW31 -- Ye Olde Role Playing Game, Unchained
// 2015-11-17
public abstract class Character{
// Instance Variables
//protected so that only visible to subclasses
protected String name = "";
protected int hp;
protected int mana;
protected int strength;
protected int defense;
protected double attackRating;
protected double baseAttackRating;
protected double defenseRating;
protected double baseDefenseRating;
//ABSTRACT METHODS
public abstract void normalize();
public abstract void specialize();
public abstract String about();
// Constructors
// Default Constructor; set instance vars to default vals
public Character(){
hp = 10;
strength = 10;
defense = 10;
attackRating = 1.0;
baseAttackRating = attackRating;
defenseRating = 1.0;
baseDefenseRating = defenseRating;
}
//Overloaded Constructor; set instance vars to input params, no name
public Character(int inputHp, int inputStrength, int inputDefense,
double inputAttackRating, double inputDefenseRating){
this();
hp = inputHp;
strength = inputStrength;
defense = inputDefense;
attackRating = inputAttackRating;
defenseRating = inputDefenseRating;
baseAttackRating = attackRating;
baseDefenseRating = defenseRating;
}
//Overloaded Constructor; set instance vars to input params, w/ name
public Character(String inputName, int inputHp, int inputStrength, int inputDefense,
double inputAttackRating, double inputDefenseRating){
this(inputHp, inputStrength, inputDefense, inputAttackRating, inputDefenseRating);
name = inputName;
}
// Methods
//for debugging purposes
public String stats(){
String retStr = "";
retStr += "Name: " + name + "\n";
retStr += "HP: " + hp + "\n";
retStr += "Strength: " + strength + "\n";
retStr += "Defense: " + defense + "\n";
retStr += "Base Attack Rating: " + baseAttackRating + "\n";
retStr += "Base Defense Rating: " + baseDefenseRating;
return retStr;
}
//returns true if character alive
public boolean isAlive(){
return (hp > 0);
}
//returns true if character has mana
public boolean hasMana(){
return (mana > 0);
}
//returns value of character's HP
public int getHP(){
return hp;
}
//returns value of character's defense
public int getDefense(){
return defense;
}
//returns value of charater's defense rating
public double getDefenseRating(){
return defenseRating;
}
// return name of character
public String getName(){
return name;
}
//lower character's HP by int specified in param
public int lowerHP(int recieveDamage){
hp -= recieveDamage;
return recieveDamage;
}
//attack character specified in other
public int attack(Character other){
int inflictDamage;
inflictDamage = (int) ( (strength * attackRating) - (other.getDefense() * other.getDefenseRating()) );
if (inflictDamage < 0){ //prevent doing negative damage
inflictDamage = 0;
}
other.lowerHP(inflictDamage);
return inflictDamage;
}
} | UTF-8 | Java | 3,435 | java | Character.java | Java | [
{
"context": "// DLC -- Derek Lin, Lisa Shi, Calvin Vuong\n// APCS1 pd5\n// HW31 -- Y",
"end": 19,
"score": 0.9998470544815063,
"start": 10,
"tag": "NAME",
"value": "Derek Lin"
},
{
"context": "// DLC -- Derek Lin, Lisa Shi, Calvin Vuong\n// APCS1 pd5\n// HW31 -- Ye Olde Rol",
"e... | null | [] | // DLC -- <NAME>, <NAME>, <NAME>
// APCS1 pd5
// HW31 -- Ye Olde Role Playing Game, Unchained
// 2015-11-17
public abstract class Character{
// Instance Variables
//protected so that only visible to subclasses
protected String name = "";
protected int hp;
protected int mana;
protected int strength;
protected int defense;
protected double attackRating;
protected double baseAttackRating;
protected double defenseRating;
protected double baseDefenseRating;
//ABSTRACT METHODS
public abstract void normalize();
public abstract void specialize();
public abstract String about();
// Constructors
// Default Constructor; set instance vars to default vals
public Character(){
hp = 10;
strength = 10;
defense = 10;
attackRating = 1.0;
baseAttackRating = attackRating;
defenseRating = 1.0;
baseDefenseRating = defenseRating;
}
//Overloaded Constructor; set instance vars to input params, no name
public Character(int inputHp, int inputStrength, int inputDefense,
double inputAttackRating, double inputDefenseRating){
this();
hp = inputHp;
strength = inputStrength;
defense = inputDefense;
attackRating = inputAttackRating;
defenseRating = inputDefenseRating;
baseAttackRating = attackRating;
baseDefenseRating = defenseRating;
}
//Overloaded Constructor; set instance vars to input params, w/ name
public Character(String inputName, int inputHp, int inputStrength, int inputDefense,
double inputAttackRating, double inputDefenseRating){
this(inputHp, inputStrength, inputDefense, inputAttackRating, inputDefenseRating);
name = inputName;
}
// Methods
//for debugging purposes
public String stats(){
String retStr = "";
retStr += "Name: " + name + "\n";
retStr += "HP: " + hp + "\n";
retStr += "Strength: " + strength + "\n";
retStr += "Defense: " + defense + "\n";
retStr += "Base Attack Rating: " + baseAttackRating + "\n";
retStr += "Base Defense Rating: " + baseDefenseRating;
return retStr;
}
//returns true if character alive
public boolean isAlive(){
return (hp > 0);
}
//returns true if character has mana
public boolean hasMana(){
return (mana > 0);
}
//returns value of character's HP
public int getHP(){
return hp;
}
//returns value of character's defense
public int getDefense(){
return defense;
}
//returns value of charater's defense rating
public double getDefenseRating(){
return defenseRating;
}
// return name of character
public String getName(){
return name;
}
//lower character's HP by int specified in param
public int lowerHP(int recieveDamage){
hp -= recieveDamage;
return recieveDamage;
}
//attack character specified in other
public int attack(Character other){
int inflictDamage;
inflictDamage = (int) ( (strength * attackRating) - (other.getDefense() * other.getDefenseRating()) );
if (inflictDamage < 0){ //prevent doing negative damage
inflictDamage = 0;
}
other.lowerHP(inflictDamage);
return inflictDamage;
}
} | 3,424 | 0.628821 | 0.621252 | 105 | 31.72381 | 20.744017 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.67619 | false | false | 12 |
8da4dde23504e5a8f3e9823eb08b0f9c93d2861d | 16,947,940,968,315 | d8bf6bd9d78b58ce35b6142ef757f9b7a1c73921 | /Computer-science/4th_semester/network_1/trab_gb/Game of Stop/src/Listener/Listener.java | 917c9c3e67d8df2d3a2fb5f09bc2e399710247e8 | [] | no_license | pedroaccorsi/Unisinos | https://github.com/pedroaccorsi/Unisinos | bcfab36fa215b7cd8c19644bf4af629fe014a6e9 | 7f8fa978bbda0eefc1f06e328aa311748b02b1e2 | refs/heads/master | 2020-07-13T05:06:24.798000 | 2020-07-05T18:56:37 | 2020-07-05T18:56:37 | 204,997,635 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Listener;
public interface Listener {
public void listenString();
public void waitForInputString();
public boolean hasInputString();
public void listenObject();
public void waitForInputObject();
public boolean hasInputObject();
}
| UTF-8 | Java | 265 | java | Listener.java | Java | [] | null | [] | package Listener;
public interface Listener {
public void listenString();
public void waitForInputString();
public boolean hasInputString();
public void listenObject();
public void waitForInputObject();
public boolean hasInputObject();
}
| 265 | 0.724528 | 0.724528 | 12 | 21.083334 | 15.644266 | 37 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 12 |
24114935413749de766958791d6ddecec953a427 | 10,703,058,528,750 | 3d3e3151ef72f6492d06fbf56a942f48344c0678 | /app/src/main/java/com/example/administrator/yisihqingdan/activity/WelcomeActivity.java | 6afdc824e6c389e533f152218bf36f8f3cf852e9 | [] | no_license | MyYiShi/QingDan | https://github.com/MyYiShi/QingDan | 20bfcb2da909559a090f4a31441a958bcb5ebc01 | e4a1f919c1bffb2bdeeb311dd46aa37571c76e4b | refs/heads/master | 2020-07-05T07:38:57.096000 | 2016-11-18T11:06:49 | 2016-11-18T11:06:49 | 74,121,638 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.administrator.yisihqingdan.activity;
import android.content.Intent;
import android.os.Bundle;
import com.example.administrator.yisihqingdan.R;
/**
* Created by Yishi on 2016/10/27.
*/
public class WelcomeActivity extends BaseActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Thread(){
@Override
public void run() {
try {
sleep(2000);
startActivity(new Intent(WelcomeActivity.this,MainActivity.class));
finish();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
@Override
protected int getContentResId() {
return R.layout.activity_welcome;
}
@Override
protected void initView() {
}
}
| UTF-8 | Java | 932 | java | WelcomeActivity.java | Java | [
{
"context": "e.administrator.yisihqingdan.R;\n\n/**\n * Created by Yishi on 2016/10/27.\n */\n\npublic class WelcomeActivity ",
"end": 189,
"score": 0.9984782338142395,
"start": 184,
"tag": "NAME",
"value": "Yishi"
}
] | null | [] | package com.example.administrator.yisihqingdan.activity;
import android.content.Intent;
import android.os.Bundle;
import com.example.administrator.yisihqingdan.R;
/**
* Created by Yishi on 2016/10/27.
*/
public class WelcomeActivity extends BaseActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Thread(){
@Override
public void run() {
try {
sleep(2000);
startActivity(new Intent(WelcomeActivity.this,MainActivity.class));
finish();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
@Override
protected int getContentResId() {
return R.layout.activity_welcome;
}
@Override
protected void initView() {
}
}
| 932 | 0.57618 | 0.563305 | 40 | 22.299999 | 20.570852 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false | 12 |
8c9400a758180266e1b295bfc41cf5b88e981a67 | 4,166,118,304,015 | c79b5dbe245abe41a067a59279e932e567a30eff | /PokerGame/main/java/com/capgemini/solejnik/PokerGame/PokerHand.java | 3768b1f33596e06f547edd38f1632bd26270f786 | [] | no_license | solejnik/MyStarterKit | https://github.com/solejnik/MyStarterKit | c4bcb1dab61a1e630a53c0f1e0c19039b37df10b | af283a4d4c69d9d656ae3bbd7165ff0611b26a28 | refs/heads/master | 2021-01-10T03:38:15.438000 | 2016-01-07T08:00:27 | 2016-01-07T08:00:27 | 48,329,534 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.capgemini.solejnik.PokerGame;
import java.util.List;
public class PokerHand {
private List<Card> cards;
public PokerHand(List<Card> cards) {
super();
PokerSort sorter = new PokerSort(cards);
sorter.sort();
this.cards = sorter.getCards();
}
protected List<Card> getCards() {
return cards;
}
}
| UTF-8 | Java | 323 | java | PokerHand.java | Java | [] | null | [] | package com.capgemini.solejnik.PokerGame;
import java.util.List;
public class PokerHand {
private List<Card> cards;
public PokerHand(List<Card> cards) {
super();
PokerSort sorter = new PokerSort(cards);
sorter.sort();
this.cards = sorter.getCards();
}
protected List<Card> getCards() {
return cards;
}
}
| 323 | 0.705882 | 0.705882 | 18 | 16.944445 | 15.306034 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.277778 | false | false | 12 |
06196afeee6e38ddb79330636c0b253b2597eddd | 16,106,127,374,950 | 02cfe43d3c3002bfaeab66968f303a196814217e | /hrms/src/main/java/kilobyte/hrms/business/abstracts/TechnologyService.java | b9b3ac9293a5d73803880f4085ede7c855d69230 | [] | no_license | KB-Silence/HRMS-Project | https://github.com/KB-Silence/HRMS-Project | d441e2b5a973fc5a624439877cf1bc90192b8234 | 0cf7f4f7d92aa5c5efb17aedc92cd08397162e15 | refs/heads/main | 2023-08-07T14:23:23.877000 | 2021-09-21T19:47:17 | 2021-09-21T19:47:17 | 371,966,906 | 9 | 0 | null | false | 2021-08-12T20:41:37 | 2021-05-29T12:24:45 | 2021-08-07T23:06:57 | 2021-08-12T20:41:37 | 225 | 5 | 0 | 0 | Java | false | false | package kilobyte.hrms.business.abstracts;
import java.util.List;
import kilobyte.hrms.core.utilities.results.DataResult;
import kilobyte.hrms.core.utilities.results.Result;
import kilobyte.hrms.entities.concretes.Technology;
import kilobyte.hrms.entities.dtos.TechnologyDto;
public interface TechnologyService {
Result addTechnology(TechnologyDto technologyDto);
Result updateTechnology(TechnologyDto technologyDto, int technologyId);
Result deleteTechnology(int technologyId);
DataResult<List<Technology>> getAll();
DataResult<List<Technology>> getByUnemployedId(int unemployedId);
}
| UTF-8 | Java | 593 | java | TechnologyService.java | Java | [] | null | [] | package kilobyte.hrms.business.abstracts;
import java.util.List;
import kilobyte.hrms.core.utilities.results.DataResult;
import kilobyte.hrms.core.utilities.results.Result;
import kilobyte.hrms.entities.concretes.Technology;
import kilobyte.hrms.entities.dtos.TechnologyDto;
public interface TechnologyService {
Result addTechnology(TechnologyDto technologyDto);
Result updateTechnology(TechnologyDto technologyDto, int technologyId);
Result deleteTechnology(int technologyId);
DataResult<List<Technology>> getAll();
DataResult<List<Technology>> getByUnemployedId(int unemployedId);
}
| 593 | 0.838111 | 0.838111 | 16 | 36.0625 | 23.442667 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.0625 | false | false | 12 |
37756c9c82e0e7006842dcd35d6ebcff6c417ee1 | 16,106,127,375,873 | 50824f8fb57050e443fd13de36930e945eca0d2e | /src/builder/b/Produto.java | 13c095dd69c73d7755c9ccc38bc58b7f9085dd12 | [] | no_license | felipegonelli/javaPatterns | https://github.com/felipegonelli/javaPatterns | 95d179b7f59d08ec4c90eb6612cb9ab67011c5b9 | d3d1e5f3c1f0f1ae175d99df080b31ba41c1d65f | refs/heads/master | 2020-04-04T21:17:16.465000 | 2019-05-28T17:38:06 | 2019-05-28T17:38:06 | 156,280,807 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package builder.b;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDate;
public class Produto {
Integer id;
String descricao;
BigDecimal imposto;
BigDecimal margemLucro;
BigDecimal valor;
BigDecimal valorVenda;
String marca;
String setor;
String rastreamento;
LocalDate dataFabricacao;
LocalDate dataValidade;
private Produto() { }
public static class Builder {
Integer id;
String descricao;
BigDecimal imposto;
BigDecimal margemLucro;
BigDecimal valor;
BigDecimal valorVenda;
String marca;
String setor;
String rastreamento;
LocalDate dataFabricacao;
LocalDate dataValidade;
public Builder(Integer id) {
this.id = id;
}
public Builder descricao(String descricao) {
this.descricao = descricao;
return this;
}
public Builder imposto(BigDecimal imposto) {
this.imposto = imposto;
return this;
}
public Builder margemLucro(BigDecimal margemLucro) {
this.margemLucro = margemLucro;
return this;
}
public Builder valor(BigDecimal valor) {
this.valor = valor;
return this;
}
public Builder valorVenda(BigDecimal valorVenda) {
this.valorVenda = valorVenda;
return this;
}
public Builder marca(String marca) {
this.marca = marca;
return this;
}
public Builder setor(String setor) {
this.setor = setor;
return this;
}
public Builder rastreamento(String rastreamento) {
this.rastreamento = rastreamento;
return this;
}
public Builder dataFabricacao(LocalDate dataFabricacao) {
this.dataFabricacao = dataFabricacao;
return this;
}
public Builder dataValidade(LocalDate dataValidade) {
this.dataValidade = dataValidade;
return this;
}
public Produto build() {
Produto p = new Produto();
p.id = this.id;
p.descricao = this.descricao;
p.imposto = this.imposto;
p.margemLucro = this.margemLucro;
p.valor = this.valor;
p.valorVenda = this.valorVenda;
p.marca = this.marca;
p.setor = this.setor;
p.rastreamento = this.rastreamento;
p.dataFabricacao = this.dataFabricacao;
p.dataValidade = this.dataValidade;
return p;
}
}
@Override
public String toString() {
DecimalFormat dfM = new DecimalFormat("R$ #,###.00");
DecimalFormat dfP = new DecimalFormat("#,00 %");
StringBuilder s = new StringBuilder();
s.append("Id: ").append(id).append("\n");
s.append("Descrição: ").append(descricao).append("\n");
s.append("Marca: ").append(marca).append("\n");
s.append("Valor Produto: ").append(dfM.format(valor)).append("\n");
s.append("Valor tributação: ").append(dfM.format(imposto)).append("\n");
s.append("Margem Lucro: ").append(dfP.format(margemLucro)).append("\n");
s.append("Valor de Venda:").append(dfM.format(valorVenda)).append("\n");
s.append("Setor: ").append(setor).append("\n");
s.append("Rastreamento: ").append(rastreamento).append("\n");
s.append("Data de Fabricação: ").append(dataFabricacao).append("\n");
s.append("Data de Validade: ").append(dataValidade).append("\n");
return s.toString();
}
}
| ISO-8859-1 | Java | 3,190 | java | Produto.java | Java | [
{
"context": "d(dfM.format(imposto)).append(\"\\n\");\r\n\t\ts.append(\"Margem Lucro: \").append(dfP.format(margemLucro)).append(\"\\n\");",
"end": 2767,
"score": 0.8948706984519958,
"start": 2755,
"tag": "NAME",
"value": "Margem Lucro"
}
] | null | [] | package builder.b;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDate;
public class Produto {
Integer id;
String descricao;
BigDecimal imposto;
BigDecimal margemLucro;
BigDecimal valor;
BigDecimal valorVenda;
String marca;
String setor;
String rastreamento;
LocalDate dataFabricacao;
LocalDate dataValidade;
private Produto() { }
public static class Builder {
Integer id;
String descricao;
BigDecimal imposto;
BigDecimal margemLucro;
BigDecimal valor;
BigDecimal valorVenda;
String marca;
String setor;
String rastreamento;
LocalDate dataFabricacao;
LocalDate dataValidade;
public Builder(Integer id) {
this.id = id;
}
public Builder descricao(String descricao) {
this.descricao = descricao;
return this;
}
public Builder imposto(BigDecimal imposto) {
this.imposto = imposto;
return this;
}
public Builder margemLucro(BigDecimal margemLucro) {
this.margemLucro = margemLucro;
return this;
}
public Builder valor(BigDecimal valor) {
this.valor = valor;
return this;
}
public Builder valorVenda(BigDecimal valorVenda) {
this.valorVenda = valorVenda;
return this;
}
public Builder marca(String marca) {
this.marca = marca;
return this;
}
public Builder setor(String setor) {
this.setor = setor;
return this;
}
public Builder rastreamento(String rastreamento) {
this.rastreamento = rastreamento;
return this;
}
public Builder dataFabricacao(LocalDate dataFabricacao) {
this.dataFabricacao = dataFabricacao;
return this;
}
public Builder dataValidade(LocalDate dataValidade) {
this.dataValidade = dataValidade;
return this;
}
public Produto build() {
Produto p = new Produto();
p.id = this.id;
p.descricao = this.descricao;
p.imposto = this.imposto;
p.margemLucro = this.margemLucro;
p.valor = this.valor;
p.valorVenda = this.valorVenda;
p.marca = this.marca;
p.setor = this.setor;
p.rastreamento = this.rastreamento;
p.dataFabricacao = this.dataFabricacao;
p.dataValidade = this.dataValidade;
return p;
}
}
@Override
public String toString() {
DecimalFormat dfM = new DecimalFormat("R$ #,###.00");
DecimalFormat dfP = new DecimalFormat("#,00 %");
StringBuilder s = new StringBuilder();
s.append("Id: ").append(id).append("\n");
s.append("Descrição: ").append(descricao).append("\n");
s.append("Marca: ").append(marca).append("\n");
s.append("Valor Produto: ").append(dfM.format(valor)).append("\n");
s.append("Valor tributação: ").append(dfM.format(imposto)).append("\n");
s.append("<NAME>: ").append(dfP.format(margemLucro)).append("\n");
s.append("Valor de Venda:").append(dfM.format(valorVenda)).append("\n");
s.append("Setor: ").append(setor).append("\n");
s.append("Rastreamento: ").append(rastreamento).append("\n");
s.append("Data de Fabricação: ").append(dataFabricacao).append("\n");
s.append("Data de Validade: ").append(dataValidade).append("\n");
return s.toString();
}
}
| 3,184 | 0.670226 | 0.66897 | 118 | 24.983051 | 18.984821 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.627119 | false | false | 12 |
1516d9cb6eba1a6e8250f0559dd7850f53a2067b | 13,580,686,617,990 | df98231e84b157ca69a10aa64d78ca613537d9c4 | /src/Gui/MusicTableRenderer.java | 23381bd68d3797667aaa6f605e9d2d4c7c0e5baf | [] | no_license | inksmallfrog/MusicPlayer_Java | https://github.com/inksmallfrog/MusicPlayer_Java | a4b183af4474feee581b789ff34cd4eb6a202043 | aec8b6b7507d1a652ccbefdc5c0123ebad60df23 | refs/heads/master | 2016-08-10T21:24:34.764000 | 2015-11-03T13:25:08 | 2015-11-03T13:25:08 | 45,020,734 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Gui;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
/**
* Created by inksmallfrog on 10/28/15.
*/
public class MusicTableRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if(table.getColumnName(column) == "button"){
return (JButton)value;
}
setText(value.toString());
setForeground(Color.white);
if(row % 2 == 0){
setBackground(new Color(93, 93, 93));
}
else{
setBackground(new Color(70, 70, 70));
}
return this;
}
}
| UTF-8 | Java | 735 | java | MusicTableRenderer.java | Java | [
{
"context": "ellRenderer;\nimport java.awt.*;\n\n/**\n * Created by inksmallfrog on 10/28/15.\n */\npublic class MusicTableRenderer ",
"end": 137,
"score": 0.9995797276496887,
"start": 125,
"tag": "USERNAME",
"value": "inksmallfrog"
}
] | null | [] | package Gui;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
/**
* Created by inksmallfrog on 10/28/15.
*/
public class MusicTableRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if(table.getColumnName(column) == "button"){
return (JButton)value;
}
setText(value.toString());
setForeground(Color.white);
if(row % 2 == 0){
setBackground(new Color(93, 93, 93));
}
else{
setBackground(new Color(70, 70, 70));
}
return this;
}
}
| 735 | 0.628571 | 0.601361 | 27 | 26.222221 | 29.017662 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.703704 | false | false | 12 |
bcda53a2db8e4b026865a5ea0bedf01e2bf9a4e2 | 16,724,602,654,077 | 903209029a93e8d05f2e95d7effb5700e986a3c3 | /main/src/main/java/com/flightStalker/main/Repository/RoundTripRepository.java | 2d13d25c8c164d3781d6800aed5e4dd8c46bc8eb | [] | no_license | adieltal/FlightStalker | https://github.com/adieltal/FlightStalker | f6ddab8678cd38ae2e9506bce05d61cbef64c5b6 | b9317a6069cb6456a4b1aee7b33183df0ae9a73a | refs/heads/master | 2020-03-30T10:38:41.503000 | 2018-12-15T17:42:51 | 2018-12-15T17:42:51 | 151,129,069 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.flightStalker.main.Repository;
import com.flightStalker.main.Entity.RoundTrip;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
//todo read about @Transactional annotation
@Repository
public interface RoundTripRepository extends CrudRepository<RoundTrip, String> {
@Query("SELECT MAX(lastCheck) FROM RoundTrip")
Long findByMaxLastCheck();
List<RoundTrip> findAllByLastCheck(long lastCheck);
}
| UTF-8 | Java | 567 | java | RoundTripRepository.java | Java | [] | null | [] | package com.flightStalker.main.Repository;
import com.flightStalker.main.Entity.RoundTrip;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
//todo read about @Transactional annotation
@Repository
public interface RoundTripRepository extends CrudRepository<RoundTrip, String> {
@Query("SELECT MAX(lastCheck) FROM RoundTrip")
Long findByMaxLastCheck();
List<RoundTrip> findAllByLastCheck(long lastCheck);
}
| 567 | 0.804233 | 0.804233 | 18 | 30.5 | 25.428003 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 12 |
fcf0cd3b8d0f4a998e95a20dd018d72f17abac4a | 21,809,843,990,320 | 7748661016b867d9ce65504b43b6511bc0770476 | /CFController/app/src/main/java/com/charleshested/cfcontroller/LocationActivity.java | cc1d2b84ded1fcebf0c8d06270d4c7fe89d6ef2d | [] | no_license | muler077/Master-Thesis-Crowdfinding | https://github.com/muler077/Master-Thesis-Crowdfinding | a4d55a980db63f952b1087c1f9e077ce70407603 | ef287406dd6b485a9dc7d69bdff03ebbd0b60949 | refs/heads/master | 2020-03-31T22:17:43.665000 | 2018-06-19T13:39:55 | 2018-06-19T13:39:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.charleshested.cfcontroller;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.database.FirebaseDatabase;
import static com.charleshested.cfcontroller.MainActivity.DATABASE_CANCEL;
import static com.charleshested.cfcontroller.MainActivity.EXP_LOCATION;
import static com.charleshested.cfcontroller.MainActivity.EXP_RUNNING;
public class LocationActivity extends AppCompatActivity {
private static final String TAG = "LocationActivity";
private EditText mEditName;
private Button mStart;
private boolean started;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
mEditName = findViewById(R.id.inputName);
mStart = findViewById(R.id.btn_start);
mStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (started) stopExperiment();
else startExperiment();
}
});
}
private void startExperiment() {
if (mEditName.getText().length() == 0) {
Toast.makeText(getApplication(), "Enter experiment name", Toast.LENGTH_SHORT).show();
return;
}
String inputText = mEditName.getText().toString();
String experiment = EXP_LOCATION + "," + "0" + "," + inputText + "," + "none";
FirebaseDatabase.getInstance()
.getReference()
.child(EXP_RUNNING)
.setValue(experiment);
mStart.setText("Stop");
started = true;
}
private void stopExperiment() {
FirebaseDatabase.getInstance()
.getReference()
.child(EXP_RUNNING)
.setValue(DATABASE_CANCEL);
mStart.setText("Start");
started = false;
}
}
| UTF-8 | Java | 2,033 | java | LocationActivity.java | Java | [] | null | [] | package com.charleshested.cfcontroller;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.database.FirebaseDatabase;
import static com.charleshested.cfcontroller.MainActivity.DATABASE_CANCEL;
import static com.charleshested.cfcontroller.MainActivity.EXP_LOCATION;
import static com.charleshested.cfcontroller.MainActivity.EXP_RUNNING;
public class LocationActivity extends AppCompatActivity {
private static final String TAG = "LocationActivity";
private EditText mEditName;
private Button mStart;
private boolean started;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
mEditName = findViewById(R.id.inputName);
mStart = findViewById(R.id.btn_start);
mStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (started) stopExperiment();
else startExperiment();
}
});
}
private void startExperiment() {
if (mEditName.getText().length() == 0) {
Toast.makeText(getApplication(), "Enter experiment name", Toast.LENGTH_SHORT).show();
return;
}
String inputText = mEditName.getText().toString();
String experiment = EXP_LOCATION + "," + "0" + "," + inputText + "," + "none";
FirebaseDatabase.getInstance()
.getReference()
.child(EXP_RUNNING)
.setValue(experiment);
mStart.setText("Stop");
started = true;
}
private void stopExperiment() {
FirebaseDatabase.getInstance()
.getReference()
.child(EXP_RUNNING)
.setValue(DATABASE_CANCEL);
mStart.setText("Start");
started = false;
}
}
| 2,033 | 0.648303 | 0.646827 | 68 | 28.897058 | 23.918451 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.544118 | false | false | 12 |
a0c012bed56d98912c07cd2202d769329f9a3229 | 15,642,270,942,272 | 1bc0743c5cfcb6062c741a0ae6cb8a9f024ead74 | /src/zootask/Bear.java | fbeb58f3a5ce0a03e4dc3ff700122cc3ed372442 | [] | no_license | vallerboy/oop12 | https://github.com/vallerboy/oop12 | 6b28c7980ba0a0b20725fc3ebabb18bb84781faa | 4944a7fa0c0dd8e6b36971537788fd3010853750 | refs/heads/master | 2020-04-29T07:34:24.014000 | 2019-03-17T15:04:24 | 2019-03-17T15:04:24 | 175,957,825 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package zootask;
import zootask.Animal;
public class Bear extends Animal {
private int furLength;
public Bear(int id, String name, float weight, int furLength) {
super(id, name, weight);
this.furLength = furLength;
}
public int getFurLength() {
return furLength;
}
public void setFurLength(int furLength) {
this.furLength = furLength;
}
@Override
public void introduce() {
System.out.println(getId() + ". I'm a bear. My name is " + getName() + ", my weight is " + getWeight() + " kg");
}
}
| UTF-8 | Java | 576 | java | Bear.java | Java | [] | null | [] | package zootask;
import zootask.Animal;
public class Bear extends Animal {
private int furLength;
public Bear(int id, String name, float weight, int furLength) {
super(id, name, weight);
this.furLength = furLength;
}
public int getFurLength() {
return furLength;
}
public void setFurLength(int furLength) {
this.furLength = furLength;
}
@Override
public void introduce() {
System.out.println(getId() + ". I'm a bear. My name is " + getName() + ", my weight is " + getWeight() + " kg");
}
}
| 576 | 0.607639 | 0.607639 | 25 | 22.040001 | 26.467308 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.56 | false | false | 12 |
c17b6113c7a28642a4c94d4b686e7b1775bedefa | 28,415,503,685,511 | a266d6856ecdcca63343ee214b6210b7d0391b57 | /chapter_jsoup/src/main/java/ru/pimalex1978/Valute.java | df7fabea10560095f7b004d96898d9318a947d8d | [] | no_license | alexander-pimenov/javalesson | https://github.com/alexander-pimenov/javalesson | 21aced7983d22daafc1e8dcb43341d2515ff7076 | 35b79e63279aaef94b8812f2ca9bc51212b9d952 | refs/heads/master | 2023-05-26T06:21:53.710000 | 2023-05-23T19:00:29 | 2023-05-23T19:00:29 | 226,805,717 | 0 | 0 | null | false | 2023-03-04T11:55:45 | 2019-12-09T06:58:50 | 2021-12-24T09:51:34 | 2023-03-04T11:55:42 | 12,738 | 0 | 0 | 14 | Java | false | false | package ru.pimalex1978;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.math.BigDecimal;
import java.time.LocalDate;
@Getter
@Setter
@ToString
@RequiredArgsConstructor
class Valute {
private LocalDate date;
private String id;
private String numCode;
private String CharCode;
private String nominal;
private String name;
private BigDecimal value;
public Valute(LocalDate date, String id, String numCode, String charCode, String nominal, String name, BigDecimal value) {
this.date = date;
this.id = id;
this.numCode = numCode;
CharCode = charCode;
this.nominal = nominal;
this.name = name;
this.value = value;
}
}
| UTF-8 | Java | 779 | java | Valute.java | Java | [] | null | [] | package ru.pimalex1978;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.math.BigDecimal;
import java.time.LocalDate;
@Getter
@Setter
@ToString
@RequiredArgsConstructor
class Valute {
private LocalDate date;
private String id;
private String numCode;
private String CharCode;
private String nominal;
private String name;
private BigDecimal value;
public Valute(LocalDate date, String id, String numCode, String charCode, String nominal, String name, BigDecimal value) {
this.date = date;
this.id = id;
this.numCode = numCode;
CharCode = charCode;
this.nominal = nominal;
this.name = name;
this.value = value;
}
}
| 779 | 0.697047 | 0.691913 | 33 | 22.60606 | 21.237387 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.818182 | false | false | 12 |
18eeec2df71827f7c8e430c85700c59bb664098a | 27,427,661,199,973 | 85986e4d862e6fd257eb1c3db6f6b9c82bc6c4d5 | /prjClienteSIC/src/main/java/ec/com/smx/sic/cliente/gestor/articulo/admin/validacion/IValidacionArticuloCamposCreacionPorArchivoGestor.java | 3b114696af69b8627c7ca8ca4f212c9f315d6451 | [] | no_license | SebasBenalcazarS/RepoAngularJS | https://github.com/SebasBenalcazarS/RepoAngularJS | 1d60d0dec454fe4f1b1a8c434b656d55166f066f | 5c3e1d5bb4a624e30cba0d518ff0b0cda14aa92c | refs/heads/master | 2016-08-03T23:21:26.639000 | 2015-08-19T16:05:00 | 2015-08-19T16:05:00 | 40,517,374 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package ec.com.smx.sic.cliente.gestor.articulo.admin.validacion;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.collections.map.MultiKeyMap;
import org.apache.poi.ss.usermodel.Cell;
import ec.com.smx.sic.cliente.common.articulo.EnumCaracteristicaDinamica;
import ec.com.smx.sic.cliente.exception.SICException;
/**
* @author eharo
*
*/
public interface IValidacionArticuloCamposCreacionPorArchivoGestor {
public String validacionesProveedor(Cell celdaExcel, List<String> observaciones, List<HashMap<String, LinkedList<String>>> listaProveedores, Integer numeroFila, Integer numeroColumna, Integer codigoCompania, String[] condicionesProveedor, boolean esFilaValida [], String codigoCabecera) throws SICException;
// public String validacionesClasificacion(Cell celdaExcel, List<String> observaciones, Set<String> listaClasificaciones, Integer numeroFila, Integer numeroColumna, Integer codigoCompania, boolean esFilaValida [], String codigoFuncionario, String codigoCabecera, String [] condicionesClasificacion) throws SICException;
public String validacionesClasificacion(Cell celdaExcel, List<String> observaciones, List<HashMap<String, LinkedList<String>>> listaClasificaciones, Integer numeroFila, Integer numeroColumna, Integer codigoCompania, boolean esFilaValida [], String codigoFuncionario, String codigoCabecera, String [] condicionesClasificacion) throws SICException;
// public String validacionesSubClasificacion(Cell celdaExcel, List<String> observaciones, String clasificacion, Integer numeroFila, Integer numeroColumna, Set<String> listaSubClasificaciones, Integer codigoCompania, boolean esFilaValida []) throws SICException;
public String validacionesSubClasificacion(Cell celdaExcel, List<String> observaciones, String clasificacion, Integer numeroFila, Integer numeroColumna, List<MultiKeyMap> listaSubClasificaciones, Integer codigoCompania, boolean esFilaValida [], String codigoCabecera) throws SICException;
public String validacionesCodigoBarras(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, Integer codigoCompania, Set<String> listaCodigosBarras, boolean esFilaValida []) throws SICException;
public String validacionesDescripcion(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, boolean esFilaValida []) throws SICException;
public String validacionesClase(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, Set<String> listaClaseArticulos, Integer codigoCompania, boolean esFilaValida [], String codigoCabecera, Boolean esCreacion) throws SICException;
public String validacionesFechaInicioFinTemporada(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, boolean esFechaInicio, boolean esFilaValida [], Map<String, String> codigosCabeceras) throws SICException;
public String validacionesUnidadManejo(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, boolean esFilaValida [], String empaque, String codigoCabecera) throws SICException;
public String validacionesEAN14(Cell celdaExcel, List<String> observaciones, String codigoBarras, Integer numeroFila, Integer numeroColumna, Integer codigoCompania, Set<String> listaCodigosEAN14, boolean esFilaValida []) throws SICException;
public String validacionesCostoMonedaOrigen(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, String nombreCampo, String origenProveedor, String proveedorImportador, boolean esFilaValida [], LinkedList<String> codigosCabeceras) throws SICException;
public String validacionesTamanio(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, boolean esFilaValida [], String codigoCabecera) throws SICException;
public String validacionesMarca(Cell celdaExcel, List<MultiKeyMap> listaMarcas, List<String> observaciones, Integer codigoCompania, Integer numeroFila, Integer numeroColumna, String codigoProveedor, boolean esFilaValida [], LinkedList<String> codigosCabeceras) throws SICException;
public String validacionesMarcaParticipacion(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, boolean esFilaValida []) throws SICException;
public String validacionesGarantia(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, boolean esFilaValida [], String codigoCabecera) throws SICException;
public String validacionesReferencia(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, boolean esFilaValida []) throws SICException;
public String validacionesReferenciaInterna(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, boolean esFilaValida []) throws SICException;
public String validacionesAlcancePrototipo(Cell celdaExcel, List<String> observaciones, List<HashMap<String, String>> listaAlcancePrototipo, Integer numeroFila, Integer numeroColumna, Integer codigoCompania, boolean esFilaValida [], String codigoCabecera , boolean validacionesAlcancePrototipo) throws SICException;
public String validacionesAgrupador(Cell celdaExcel, List<String> observaciones, List<HashMap<String, String>> listaAgrupadores, Integer numeroFila, Integer numeroColumna, boolean esFilaValida [], String codigoCabecera) throws SICException;
public String validacionesCostoBruto(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, String nombreCampo, boolean esFilaValida [], Integer maxEnteros, Integer maxDecimales) throws SICException;
public String validacionesDescuentos(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, String nombreCampo, boolean esFilaValida [], Integer maxEnteros, Integer maxDecimales) throws SICException;
public String validacionesPrecios(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, String nombreCampo, boolean esFilaValida [], Integer maxEnteros, Integer maxDecimales) throws SICException;
public String validacionesMedidas(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, String nombreCampo, boolean esFilaValida [], Integer maxEnteros, Integer maxDecimales, String codigoCabecera) throws SICException;
public String validacionesEmpaque(Cell celdaExcel, List<String> observaciones, List<HashMap<String, String>> listaEmpaques, Integer numeroFila, Integer numeroColumna, boolean esFilaValida [], String codigoCabecera) throws SICException;
public String validacionesImportancia(Cell celdaExcel, List<String> observaciones, List<HashMap<String, String>> listaImportancias, Integer codigoCompania, Integer numeroFila, Integer numeroColumna, boolean esFilaValida [], String codigoCabecera) throws SICException;
public String validacionesPlazoPago(Cell celdaExcel, List<String> observaciones, List<HashMap<String, String>> listaPlazosPagos, Integer codigoCompania, Integer numeroFila, Integer numeroColumna, boolean esFilaValida [], String codigoCabecera) throws SICException;
public String validacionesUnidadMedida(Cell celdaExcel, List<String> observaciones, List<HashMap<String, String>> listaUnidadMedida, Integer numeroFila, Integer numeroColumna, String nombreCampo, String [] condicionesUnidadMedida, boolean esFilaValida []) throws SICException;
public String validacionesVentaPrecioAfiliado(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, String nombreCampo, String parametroIngresoDatos, boolean esFilaValida []) throws SICException;
public String validacionesControlPrecios(Cell celdaExcel, List<String> observaciones, List<HashMap<String, String>> listaControlPrecios, Integer numeroFila, Integer numeroColumna, boolean esFilaValida [], String tipoSecuencia, String codigoCabecera) throws SICException;
public String validacionesDuracionConservacion(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, String nombreCampo, boolean esFilaValida [], Integer maxEnteros, Integer maxDecimales) throws SICException;
/**
* Valida si el lugar de compra ingresado en una celda de excel, es correcto
* @author bcueva
* @param celdaExcel Instancia de una celda en Excel
* @param observaciones Lista con las observaciones de los errores en el documento de excel
* @param listaLugaresCompra
* @param codigoCompania C\u00F3digo de la compan\u00EDa
* @param numeroFila N\u00FAmero de la fila que se esta valida
* @param numeroColumna N\u00FAmero de la columna
* @param esFilaValida Bandera para validar si el valor de la celda es v\u00E1lido
* @param codigoCabecera C\u00F3digo de la cabecera
* @param codigoDivGeoPol C\u00F3digo de la divicion politica
* @return
* @throws SICException
*/
String validacionesLugarCompra(Cell celdaExcel, List<String> observaciones, List<HashMap<String, String>> listaLugaresCompra, Integer codigoCompania, Integer numeroFila, Integer numeroColumna, boolean esFilaValida [], String codigoCabecera, String codigoDivGeoPol) throws SICException;
public String validacionesPaisOrigen(Cell celdaExcel, List<String> observaciones, List<HashMap<String, String>> listaPaisOrigen, Integer numeroFila, Integer numeroColumna, boolean esFilaValida [], String codigoCabecera) throws SICException;
public String validacionesPesoAproximado(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, String nombreCampo, boolean esFilaValida [], Integer maxEnteros, Integer maxDecimales, String controlPrecio, String codigoCabecera) throws SICException;
public String validacionesPresentacion(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, String nombreCampo, boolean esFilaValida [], Integer maxEnteros, Integer maxDecimales) throws SICException;
public String validacionesTransgenico(Cell celdaExcel, List<String> observaciones, List<HashMap<String, String>> listaTransgenicos, Integer numeroFila, Integer numeroColumna, boolean esFilaValida [], String codigoCabecera) throws SICException;
public String validacionesUsos(Cell celdaExcel, List<String> observaciones, List<HashMap<String, String>> listaUsos, Integer numeroFila, Integer numeroColumna, String nombreCampo, boolean esFilaValida []) throws SICException;
public String validacionesRegistroSanitario(String celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, String nombreCampo, boolean esFilaValida []) throws SICException;
public String validacionesTipoSecuncia(Cell celdaExcel, List<String> observaciones, List<HashMap<String, String>> listaTipoSecuencias, Integer numeroFila, Integer numeroColumna, boolean esFilaValida [], String codigoCabecera) throws SICException;
/**
* Metodo que retorna un string con el valor de la celda de acuerdo al formato
* @param celda
* @return
* @author eharo
*/
public String obtenerValorCeldaString(Cell celda) throws SICException;
/**
* Metodo que permite quitar los 0 decimales de las celdas
* @param cellValue
* @return
* @throws SICException
* @author eharo
*/
public String parsearValor(String cellValue) throws SICException;
public String indiceAlfabeticoColumna(int indiceColumna) throws SICException;
public void agregarEsFilaValida(boolean esFilaValida[], boolean esValido) throws SICException;
public Boolean validarCaracteristicaDinamica(String campo, Integer numeroFila, Integer numeroColumna, String cabecera, EnumCaracteristicaDinamica caracteristicaDinamica, List<String> observaciones, boolean esFilaValida []) throws SICException;
} | UTF-8 | Java | 11,818 | java | IValidacionArticuloCamposCreacionPorArchivoGestor.java | Java | [
{
"context": "ic.cliente.exception.SICException;\n\n/**\n * @author eharo\n *\n */\npublic interface IValidacionArticuloCampos",
"end": 447,
"score": 0.9988370537757874,
"start": 442,
"tag": "USERNAME",
"value": "eharo"
},
{
"context": "ado en una celda de excel, es correcto\n\t * @a... | null | [] | /**
*
*/
package ec.com.smx.sic.cliente.gestor.articulo.admin.validacion;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.collections.map.MultiKeyMap;
import org.apache.poi.ss.usermodel.Cell;
import ec.com.smx.sic.cliente.common.articulo.EnumCaracteristicaDinamica;
import ec.com.smx.sic.cliente.exception.SICException;
/**
* @author eharo
*
*/
public interface IValidacionArticuloCamposCreacionPorArchivoGestor {
public String validacionesProveedor(Cell celdaExcel, List<String> observaciones, List<HashMap<String, LinkedList<String>>> listaProveedores, Integer numeroFila, Integer numeroColumna, Integer codigoCompania, String[] condicionesProveedor, boolean esFilaValida [], String codigoCabecera) throws SICException;
// public String validacionesClasificacion(Cell celdaExcel, List<String> observaciones, Set<String> listaClasificaciones, Integer numeroFila, Integer numeroColumna, Integer codigoCompania, boolean esFilaValida [], String codigoFuncionario, String codigoCabecera, String [] condicionesClasificacion) throws SICException;
public String validacionesClasificacion(Cell celdaExcel, List<String> observaciones, List<HashMap<String, LinkedList<String>>> listaClasificaciones, Integer numeroFila, Integer numeroColumna, Integer codigoCompania, boolean esFilaValida [], String codigoFuncionario, String codigoCabecera, String [] condicionesClasificacion) throws SICException;
// public String validacionesSubClasificacion(Cell celdaExcel, List<String> observaciones, String clasificacion, Integer numeroFila, Integer numeroColumna, Set<String> listaSubClasificaciones, Integer codigoCompania, boolean esFilaValida []) throws SICException;
public String validacionesSubClasificacion(Cell celdaExcel, List<String> observaciones, String clasificacion, Integer numeroFila, Integer numeroColumna, List<MultiKeyMap> listaSubClasificaciones, Integer codigoCompania, boolean esFilaValida [], String codigoCabecera) throws SICException;
public String validacionesCodigoBarras(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, Integer codigoCompania, Set<String> listaCodigosBarras, boolean esFilaValida []) throws SICException;
public String validacionesDescripcion(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, boolean esFilaValida []) throws SICException;
public String validacionesClase(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, Set<String> listaClaseArticulos, Integer codigoCompania, boolean esFilaValida [], String codigoCabecera, Boolean esCreacion) throws SICException;
public String validacionesFechaInicioFinTemporada(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, boolean esFechaInicio, boolean esFilaValida [], Map<String, String> codigosCabeceras) throws SICException;
public String validacionesUnidadManejo(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, boolean esFilaValida [], String empaque, String codigoCabecera) throws SICException;
public String validacionesEAN14(Cell celdaExcel, List<String> observaciones, String codigoBarras, Integer numeroFila, Integer numeroColumna, Integer codigoCompania, Set<String> listaCodigosEAN14, boolean esFilaValida []) throws SICException;
public String validacionesCostoMonedaOrigen(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, String nombreCampo, String origenProveedor, String proveedorImportador, boolean esFilaValida [], LinkedList<String> codigosCabeceras) throws SICException;
public String validacionesTamanio(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, boolean esFilaValida [], String codigoCabecera) throws SICException;
public String validacionesMarca(Cell celdaExcel, List<MultiKeyMap> listaMarcas, List<String> observaciones, Integer codigoCompania, Integer numeroFila, Integer numeroColumna, String codigoProveedor, boolean esFilaValida [], LinkedList<String> codigosCabeceras) throws SICException;
public String validacionesMarcaParticipacion(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, boolean esFilaValida []) throws SICException;
public String validacionesGarantia(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, boolean esFilaValida [], String codigoCabecera) throws SICException;
public String validacionesReferencia(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, boolean esFilaValida []) throws SICException;
public String validacionesReferenciaInterna(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, boolean esFilaValida []) throws SICException;
public String validacionesAlcancePrototipo(Cell celdaExcel, List<String> observaciones, List<HashMap<String, String>> listaAlcancePrototipo, Integer numeroFila, Integer numeroColumna, Integer codigoCompania, boolean esFilaValida [], String codigoCabecera , boolean validacionesAlcancePrototipo) throws SICException;
public String validacionesAgrupador(Cell celdaExcel, List<String> observaciones, List<HashMap<String, String>> listaAgrupadores, Integer numeroFila, Integer numeroColumna, boolean esFilaValida [], String codigoCabecera) throws SICException;
public String validacionesCostoBruto(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, String nombreCampo, boolean esFilaValida [], Integer maxEnteros, Integer maxDecimales) throws SICException;
public String validacionesDescuentos(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, String nombreCampo, boolean esFilaValida [], Integer maxEnteros, Integer maxDecimales) throws SICException;
public String validacionesPrecios(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, String nombreCampo, boolean esFilaValida [], Integer maxEnteros, Integer maxDecimales) throws SICException;
public String validacionesMedidas(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, String nombreCampo, boolean esFilaValida [], Integer maxEnteros, Integer maxDecimales, String codigoCabecera) throws SICException;
public String validacionesEmpaque(Cell celdaExcel, List<String> observaciones, List<HashMap<String, String>> listaEmpaques, Integer numeroFila, Integer numeroColumna, boolean esFilaValida [], String codigoCabecera) throws SICException;
public String validacionesImportancia(Cell celdaExcel, List<String> observaciones, List<HashMap<String, String>> listaImportancias, Integer codigoCompania, Integer numeroFila, Integer numeroColumna, boolean esFilaValida [], String codigoCabecera) throws SICException;
public String validacionesPlazoPago(Cell celdaExcel, List<String> observaciones, List<HashMap<String, String>> listaPlazosPagos, Integer codigoCompania, Integer numeroFila, Integer numeroColumna, boolean esFilaValida [], String codigoCabecera) throws SICException;
public String validacionesUnidadMedida(Cell celdaExcel, List<String> observaciones, List<HashMap<String, String>> listaUnidadMedida, Integer numeroFila, Integer numeroColumna, String nombreCampo, String [] condicionesUnidadMedida, boolean esFilaValida []) throws SICException;
public String validacionesVentaPrecioAfiliado(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, String nombreCampo, String parametroIngresoDatos, boolean esFilaValida []) throws SICException;
public String validacionesControlPrecios(Cell celdaExcel, List<String> observaciones, List<HashMap<String, String>> listaControlPrecios, Integer numeroFila, Integer numeroColumna, boolean esFilaValida [], String tipoSecuencia, String codigoCabecera) throws SICException;
public String validacionesDuracionConservacion(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, String nombreCampo, boolean esFilaValida [], Integer maxEnteros, Integer maxDecimales) throws SICException;
/**
* Valida si el lugar de compra ingresado en una celda de excel, es correcto
* @author bcueva
* @param celdaExcel Instancia de una celda en Excel
* @param observaciones Lista con las observaciones de los errores en el documento de excel
* @param listaLugaresCompra
* @param codigoCompania C\u00F3digo de la compan\u00EDa
* @param numeroFila N\u00FAmero de la fila que se esta valida
* @param numeroColumna N\u00FAmero de la columna
* @param esFilaValida Bandera para validar si el valor de la celda es v\u00E1lido
* @param codigoCabecera C\u00F3digo de la cabecera
* @param codigoDivGeoPol C\u00F3digo de la divicion politica
* @return
* @throws SICException
*/
String validacionesLugarCompra(Cell celdaExcel, List<String> observaciones, List<HashMap<String, String>> listaLugaresCompra, Integer codigoCompania, Integer numeroFila, Integer numeroColumna, boolean esFilaValida [], String codigoCabecera, String codigoDivGeoPol) throws SICException;
public String validacionesPaisOrigen(Cell celdaExcel, List<String> observaciones, List<HashMap<String, String>> listaPaisOrigen, Integer numeroFila, Integer numeroColumna, boolean esFilaValida [], String codigoCabecera) throws SICException;
public String validacionesPesoAproximado(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, String nombreCampo, boolean esFilaValida [], Integer maxEnteros, Integer maxDecimales, String controlPrecio, String codigoCabecera) throws SICException;
public String validacionesPresentacion(Cell celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, String nombreCampo, boolean esFilaValida [], Integer maxEnteros, Integer maxDecimales) throws SICException;
public String validacionesTransgenico(Cell celdaExcel, List<String> observaciones, List<HashMap<String, String>> listaTransgenicos, Integer numeroFila, Integer numeroColumna, boolean esFilaValida [], String codigoCabecera) throws SICException;
public String validacionesUsos(Cell celdaExcel, List<String> observaciones, List<HashMap<String, String>> listaUsos, Integer numeroFila, Integer numeroColumna, String nombreCampo, boolean esFilaValida []) throws SICException;
public String validacionesRegistroSanitario(String celdaExcel, List<String> observaciones, Integer numeroFila, Integer numeroColumna, String nombreCampo, boolean esFilaValida []) throws SICException;
public String validacionesTipoSecuncia(Cell celdaExcel, List<String> observaciones, List<HashMap<String, String>> listaTipoSecuencias, Integer numeroFila, Integer numeroColumna, boolean esFilaValida [], String codigoCabecera) throws SICException;
/**
* Metodo que retorna un string con el valor de la celda de acuerdo al formato
* @param celda
* @return
* @author eharo
*/
public String obtenerValorCeldaString(Cell celda) throws SICException;
/**
* Metodo que permite quitar los 0 decimales de las celdas
* @param cellValue
* @return
* @throws SICException
* @author eharo
*/
public String parsearValor(String cellValue) throws SICException;
public String indiceAlfabeticoColumna(int indiceColumna) throws SICException;
public void agregarEsFilaValida(boolean esFilaValida[], boolean esValido) throws SICException;
public Boolean validarCaracteristicaDinamica(String campo, Integer numeroFila, Integer numeroColumna, String cabecera, EnumCaracteristicaDinamica caracteristicaDinamica, List<String> observaciones, boolean esFilaValida []) throws SICException;
} | 11,818 | 0.827551 | 0.825605 | 140 | 83.421425 | 107.957069 | 347 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.228571 | false | false | 12 |
1a27cec2aa1475ef4a29d3a67737c51284f4bf21 | 27,427,661,200,003 | 7f53548bf8f776698cb28ffd5d6fc2889afc45e9 | /src/prototype/pa55nyaps/dataobjects/UserPreference.java | cb544ab7651bc780109ae14f58525dfa67fb4a46 | [
"MIT",
"Apache-2.0"
] | permissive | pa55/pa55nyaps | https://github.com/pa55/pa55nyaps | d1dd233c13e80bfbe51e5c5003c651d120a21f15 | c1dfc15bf8e58ebcf0aa036b2509c1209e0da1f9 | refs/heads/master | 2021-01-10T06:02:21.010000 | 2017-02-02T02:36:58 | 2017-02-02T02:36:58 | 45,821,265 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
PA55 NYAPS Java Reference Implementation
Copyright 2015 Anirban Basu
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 prototype.pa55nyaps.dataobjects;
import prototype.pa55nyaps.core.NYAPSEncoder;
import prototype.pa55nyaps.core.NYAPSEncoder.CharacterType;
/**
* A preference of minimum and maximum constraints (number of characters)
* for a specific character type.
*
* @author Anirban Basu
*
*/
public class UserPreference {
public UserPreference(CharacterType characterType, Integer minimum, Integer maximum) {
super();
this.characterType = characterType;
if(minimum>1) {
this.minimum = minimum;
}
else {
this.minimum = 1;
}
this.maximum = maximum;
}
public UserPreference(CharacterType characterType, Integer minimum) {
super();
this.characterType = characterType;
if(minimum > 1) {
this.minimum = minimum;
}
else {
this.minimum = 1;
}
this.maximum = -1;
}
public NYAPSEncoder.CharacterType characterType;
public Integer minimum;
public Integer maximum;
}
| UTF-8 | Java | 1,506 | java | UserPreference.java | Java | [
{
"context": "YAPS Java Reference Implementation\n\nCopyright 2015 Anirban Basu\n\nLicensed under the Apache License, Version 2.0 (",
"end": 72,
"score": 0.9998852610588074,
"start": 60,
"tag": "NAME",
"value": "Anirban Basu"
},
{
"context": ")\n * for a specific character type.\n * ... | null | [] | /*
PA55 NYAPS Java Reference Implementation
Copyright 2015 <NAME>
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 prototype.pa55nyaps.dataobjects;
import prototype.pa55nyaps.core.NYAPSEncoder;
import prototype.pa55nyaps.core.NYAPSEncoder.CharacterType;
/**
* A preference of minimum and maximum constraints (number of characters)
* for a specific character type.
*
* @author <NAME>
*
*/
public class UserPreference {
public UserPreference(CharacterType characterType, Integer minimum, Integer maximum) {
super();
this.characterType = characterType;
if(minimum>1) {
this.minimum = minimum;
}
else {
this.minimum = 1;
}
this.maximum = maximum;
}
public UserPreference(CharacterType characterType, Integer minimum) {
super();
this.characterType = characterType;
if(minimum > 1) {
this.minimum = minimum;
}
else {
this.minimum = 1;
}
this.maximum = -1;
}
public NYAPSEncoder.CharacterType characterType;
public Integer minimum;
public Integer maximum;
}
| 1,494 | 0.75498 | 0.741036 | 58 | 24.965517 | 24.463179 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.241379 | false | false | 12 |
d7cb766faba72fb6f6545c096e94cd33b9f35a80 | 12,197,707,167,171 | c6cc0b02183581b3f8b64f976443a607a2b6e17e | /app/src/main/java/com/example/takuya/myctrlactivity/MainActivity.java | 029ada67ff300794aa74aaf5c850cb618965ef88 | [] | no_license | bui2jp/MyCtrlActivity | https://github.com/bui2jp/MyCtrlActivity | b2d0e17d753752c384ea5ce7da7396baf5269a04 | dea8932495c59c5dd7f00967dff66596bd859ea8 | refs/heads/master | 2021-05-07T01:57:48.114000 | 2017-11-12T05:59:27 | 2017-11-12T05:59:27 | 110,393,058 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.takuya.myctrlactivity;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onActivityResult( int requestCode, int resultCode, Intent intent )
{
// startActivityForResult()の際に指定した識別コードとの比較
if( requestCode == 1001 ){
// 返却結果ステータスとの比較
if( resultCode == Activity.RESULT_OK ){
// 返却されてきたintentから値を取り出す
String str = intent.getStringExtra( "textValue" );
//画面へ設定する
TextView editText = (TextView) findViewById(R.id.textView1);
editText.setText(str);
}
}
if( requestCode == 2001 ){
if( resultCode == Activity.RESULT_OK ){
// 返却されてきたintentから値を取り出す
String str = intent.getStringExtra( "textValue" );
int index = intent.getIntExtra("selectedIndex", -1);
str = str + ":" + index;
//画面へ設定する
TextView editText = (TextView) findViewById(R.id.textView2);
editText.setText(str);
}
}
}
//edit text
//現在の値を渡して起動する
public void onClickEditText(View view) {
Intent intent = new Intent(this, FormEditTextActivity.class);
//mainの値を渡す
TextView editText = (TextView) findViewById(R.id.textView1);
String message = editText.getText().toString();
intent.putExtra("textTitle", "車両名");
intent.putExtra("textValue", message);
intent.putExtra("maxLen", 10);
intent.putExtra("inputType", InputType.TYPE_CLASS_NUMBER);
//startActivity(intent);
int requestCode = 1001;
//値を受け取る為にstartActivityForResultで起動する
startActivityForResult(intent,requestCode);
}
//listを渡して起動する 現在の値を渡す必要はない
public void onClickList(View view) {
Intent intent = new Intent(this, FormListItemActivity.class);
//mainの値を渡す
TextView editText = (TextView) findViewById(R.id.textView2);
String message = editText.getText().toString();
ArrayList<String> carlist = new ArrayList<String>();
for(int i = 0; i<1; i++ ){
carlist.add("data - " + String.valueOf(i));
}
carlist.add("abcdefg");
carlist.add("hijklmn");
carlist.add("opqrstu");
carlist.add("vwxyz");
intent.putExtra("arrayStringValue",carlist);
int requestCode = 2001;
intent.putExtra("searchText",false);
//値を受け取る為にstartActivityForResultで起動する
//startActivity(intent);
startActivityForResult(intent,requestCode);
}
public void onClickGrid(View view) {
// Intent intent = new Intent(this, FormGridItemActivity.class);
//
// //mainの値を渡す
// TextView editText = (TextView) findViewById(R.id.textView3);
// String message = editText.getText().toString();
//
// //intent.putExtra("", message);
// startActivity(intent);intent
}
}
| UTF-8 | Java | 3,797 | java | MainActivity.java | Java | [] | null | [] | package com.example.takuya.myctrlactivity;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onActivityResult( int requestCode, int resultCode, Intent intent )
{
// startActivityForResult()の際に指定した識別コードとの比較
if( requestCode == 1001 ){
// 返却結果ステータスとの比較
if( resultCode == Activity.RESULT_OK ){
// 返却されてきたintentから値を取り出す
String str = intent.getStringExtra( "textValue" );
//画面へ設定する
TextView editText = (TextView) findViewById(R.id.textView1);
editText.setText(str);
}
}
if( requestCode == 2001 ){
if( resultCode == Activity.RESULT_OK ){
// 返却されてきたintentから値を取り出す
String str = intent.getStringExtra( "textValue" );
int index = intent.getIntExtra("selectedIndex", -1);
str = str + ":" + index;
//画面へ設定する
TextView editText = (TextView) findViewById(R.id.textView2);
editText.setText(str);
}
}
}
//edit text
//現在の値を渡して起動する
public void onClickEditText(View view) {
Intent intent = new Intent(this, FormEditTextActivity.class);
//mainの値を渡す
TextView editText = (TextView) findViewById(R.id.textView1);
String message = editText.getText().toString();
intent.putExtra("textTitle", "車両名");
intent.putExtra("textValue", message);
intent.putExtra("maxLen", 10);
intent.putExtra("inputType", InputType.TYPE_CLASS_NUMBER);
//startActivity(intent);
int requestCode = 1001;
//値を受け取る為にstartActivityForResultで起動する
startActivityForResult(intent,requestCode);
}
//listを渡して起動する 現在の値を渡す必要はない
public void onClickList(View view) {
Intent intent = new Intent(this, FormListItemActivity.class);
//mainの値を渡す
TextView editText = (TextView) findViewById(R.id.textView2);
String message = editText.getText().toString();
ArrayList<String> carlist = new ArrayList<String>();
for(int i = 0; i<1; i++ ){
carlist.add("data - " + String.valueOf(i));
}
carlist.add("abcdefg");
carlist.add("hijklmn");
carlist.add("opqrstu");
carlist.add("vwxyz");
intent.putExtra("arrayStringValue",carlist);
int requestCode = 2001;
intent.putExtra("searchText",false);
//値を受け取る為にstartActivityForResultで起動する
//startActivity(intent);
startActivityForResult(intent,requestCode);
}
public void onClickGrid(View view) {
// Intent intent = new Intent(this, FormGridItemActivity.class);
//
// //mainの値を渡す
// TextView editText = (TextView) findViewById(R.id.textView3);
// String message = editText.getText().toString();
//
// //intent.putExtra("", message);
// startActivity(intent);intent
}
}
| 3,797 | 0.618244 | 0.610237 | 121 | 27.892563 | 23.82852 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.553719 | false | false | 12 |
7317d47f834b144867b894f407c5280ef836fb1d | 11,665,131,225,698 | 94e572592fcc993c00238343aeb41fffd844a8a2 | /Back-End/product-service/src/main/java/com/shop/top/productservice/productservice/repository/CategoryRepository.java | 8e8d7435fcbac663c40e1d41aa766782489467a7 | [] | no_license | AliAnsari777/Top-Shop-E-Commerce | https://github.com/AliAnsari777/Top-Shop-E-Commerce | 025b071b45c5dabe61aada76bf706d5a31166564 | d6205dce2e0d72a3e2abf40f1f60aabe4d31ef0e | refs/heads/master | 2022-12-03T02:58:08.098000 | 2020-08-20T21:55:13 | 2020-08-20T21:55:13 | 289,117,540 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.shop.top.productservice.productservice.repository;
import com.shop.top.productservice.productservice.model.Category;
import com.sun.xml.bind.v2.model.core.ID;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface CategoryRepository extends JpaRepository<Category,Long> {
Category findByName(String name);
List<Category> findAll();
Category findById(ID id);
void deleteAllInBatch();
void deleteById(ID id);
void delete(Category category);
Category save(Category category);
}
| UTF-8 | Java | 688 | java | CategoryRepository.java | Java | [] | null | [] | package com.shop.top.productservice.productservice.repository;
import com.shop.top.productservice.productservice.model.Category;
import com.sun.xml.bind.v2.model.core.ID;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface CategoryRepository extends JpaRepository<Category,Long> {
Category findByName(String name);
List<Category> findAll();
Category findById(ID id);
void deleteAllInBatch();
void deleteById(ID id);
void delete(Category category);
Category save(Category category);
}
| 688 | 0.793605 | 0.792151 | 19 | 35.210526 | 21.879044 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.842105 | false | false | 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.