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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4ebefc7670d68d675a4477a10585a54311bc753a | 12,824,772,352,059 | 20990022d929cab24667f7772b7eeda4afa87914 | /Back-end/service/service_edu/src/main/java/fun/krits/eduservice/entity/vo/front/CourseFrontInfo.java | c198f491321dfc5b5abb2f76290ec1fd87c7c2d7 | [] | no_license | Krstar233/OnlineEducation | https://github.com/Krstar233/OnlineEducation | 45cead36f8c75059a42ee827a43d8799efb15002 | 98d170dd3ce31aa75f6b78e3bac73f6220d27a17 | refs/heads/master | 2023-08-28T07:24:53.227000 | 2023-08-21T17:05:49 | 2023-08-21T17:05:49 | 341,183,802 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fun.krits.eduservice.entity.vo.front;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.math.BigDecimal;
@Data
@ApiModel(value="前台课程页面数据", description="前台课程页面数据")
public class CourseFrontInfo {
@ApiModelProperty(value = "讲师id")
private String teacherId;
@ApiModelProperty(value = "讲师姓名")
private String teacherName;
@ApiModelProperty(value = "讲师简述")
private String teacherCareer;
@ApiModelProperty(value = "讲师头像")
private String teacherAvatar;
@ApiModelProperty(value = "课程专业ID")
private String subjectId;
@ApiModelProperty(value = "课程专业父级ID")
private String subjectParentId;
@ApiModelProperty(value = "课程标题")
private String title;
@ApiModelProperty(value = "课程销售价格,设置为0则可免费观看")
private BigDecimal price;
@ApiModelProperty(value = "总课时")
private Integer lessonNum;
@ApiModelProperty(value = "课程封面图片路径")
private String cover;
@ApiModelProperty(value = "销售数量")
private Long buyCount;
@ApiModelProperty(value = "浏览数量")
private Long viewCount;
@ApiModelProperty(value = "课程简介")
private String description;
}
| UTF-8 | Java | 1,367 | java | CourseFrontInfo.java | Java | [] | null | [] | package fun.krits.eduservice.entity.vo.front;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.math.BigDecimal;
@Data
@ApiModel(value="前台课程页面数据", description="前台课程页面数据")
public class CourseFrontInfo {
@ApiModelProperty(value = "讲师id")
private String teacherId;
@ApiModelProperty(value = "讲师姓名")
private String teacherName;
@ApiModelProperty(value = "讲师简述")
private String teacherCareer;
@ApiModelProperty(value = "讲师头像")
private String teacherAvatar;
@ApiModelProperty(value = "课程专业ID")
private String subjectId;
@ApiModelProperty(value = "课程专业父级ID")
private String subjectParentId;
@ApiModelProperty(value = "课程标题")
private String title;
@ApiModelProperty(value = "课程销售价格,设置为0则可免费观看")
private BigDecimal price;
@ApiModelProperty(value = "总课时")
private Integer lessonNum;
@ApiModelProperty(value = "课程封面图片路径")
private String cover;
@ApiModelProperty(value = "销售数量")
private Long buyCount;
@ApiModelProperty(value = "浏览数量")
private Long viewCount;
@ApiModelProperty(value = "课程简介")
private String description;
}
| 1,367 | 0.717735 | 0.716903 | 50 | 23.02 | 17.300278 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.38 | false | false | 2 |
72a622fd91cd69c4e20c47df2545d656b8836640 | 14,405,320,317,524 | 376351ac140d8884580e5edae1de82b7d0d54dfb | /bit-cinema/src/kr/co/bit_cinema/repository/servlet/snack/ListSnackServlet.java | d60c7628e6cb3085a2dd31d2e3627d3bc9d4164c | [] | no_license | moakong/bit-cinema | https://github.com/moakong/bit-cinema | 8191db0c02679e30105bd9acd09591b7317ebc00 | 4e31959c9863582fa680a3a9e196654db4933ced | refs/heads/master | 2021-01-22T04:24:30.270000 | 2017-06-16T06:01:08 | 2017-06-16T06:01:08 | 92,381,315 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package kr.co.bit_cinema.repository.servlet.snack;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;
import common.db.MyAppSqlConfig;
import kr.co.bit_cinema.repository.mapper.SnackMapper;
import kr.co.bit_cinema.repository.vo.SnackVO;
@WebServlet("/snack/ListSnack")
public class ListSnackServlet extends HttpServlet {
private SqlSession session = null;
private SnackMapper mapper = null;
public ListSnackServlet() {
session = MyAppSqlConfig.getSqlSessionInstance();
mapper = session.getMapper(SnackMapper.class);
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int no = 5;
String temp = request.getParameter("category");
if (temp != null) {
no = Integer.parseInt(temp);
}
List<SnackVO> list = null;
try {
if(no == 5){
list = mapper.bestSnack();
}
else{
list = mapper.listSnack(no);
}
} catch (Exception e) {
throw new ServletException(e);
}
request.setAttribute("list", list);
RequestDispatcher rd = request.getRequestDispatcher("/view/snack/listSnack.jsp");
rd.forward(request, response);
}
}
| UTF-8 | Java | 1,455 | java | ListSnackServlet.java | Java | [] | null | [] | package kr.co.bit_cinema.repository.servlet.snack;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;
import common.db.MyAppSqlConfig;
import kr.co.bit_cinema.repository.mapper.SnackMapper;
import kr.co.bit_cinema.repository.vo.SnackVO;
@WebServlet("/snack/ListSnack")
public class ListSnackServlet extends HttpServlet {
private SqlSession session = null;
private SnackMapper mapper = null;
public ListSnackServlet() {
session = MyAppSqlConfig.getSqlSessionInstance();
mapper = session.getMapper(SnackMapper.class);
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int no = 5;
String temp = request.getParameter("category");
if (temp != null) {
no = Integer.parseInt(temp);
}
List<SnackVO> list = null;
try {
if(no == 5){
list = mapper.bestSnack();
}
else{
list = mapper.listSnack(no);
}
} catch (Exception e) {
throw new ServletException(e);
}
request.setAttribute("list", list);
RequestDispatcher rd = request.getRequestDispatcher("/view/snack/listSnack.jsp");
rd.forward(request, response);
}
}
| 1,455 | 0.753952 | 0.752577 | 55 | 25.454546 | 21.143509 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.727273 | false | false | 2 |
246af2e45bf575549aadd2f25ec85f9d4c471ea3 | 17,454,747,096,314 | e9773b09864b285e674f0081c4e9279a5a1030c8 | /05_Servlet1/src/main/java/com/atguigu/servlet/ContextServlet.java | b23dfbcb9843b670cc0566bd0bb6bb5c0997c1c1 | [] | no_license | TinMamaDeHua/chengshengyan_Javaweb | https://github.com/TinMamaDeHua/chengshengyan_Javaweb | 9a0f43b9f152252dd3be0f2e51a489ec5af5fdd8 | 35c5a93253fd832f58ae2e5fbb3dc28ff8bbf07b | refs/heads/master | 2023-07-30T12:40:29.785000 | 2021-09-26T12:23:32 | 2021-09-26T12:23:32 | 410,544,693 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.atguigu.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ContextServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1、获取web.xml中配置的上下文参数context-param
ServletContext servletContext = getServletConfig().getServletContext();
String username = servletContext.getInitParameter("username");
System.out.println("context-param参数的username的值是:" + username);
System.out.println("context-param参数password的值是:" + servletContext.getInitParameter("password"));
// 2、获取当前的工程路径,格式: /工程路径
System.out.println("当前工程路径:" + servletContext.getContextPath());
// 3、获取工程部署后在服务器硬盘上的绝对路径
/**
* / 斜杠被服务器解析地址为:http://ip:port/工程名/ 映射到IDEA代码的web目录<br/>
*/
System.out.println("工程部署的路径是:" + servletContext.getRealPath("/"));
System.out.println("工程下css目录的绝对路径是:" + servletContext.getRealPath("/css"));
System.out.println("工程下1.jpg的绝对路径是:" + servletContext.getRealPath("/imgs/1.jpg"));
}
}
| UTF-8 | Java | 1,686 | java | ContextServlet.java | Java | [
{
"context": "tring username = servletContext.getInitParameter(\"username\");\n System.out.println(\"context-param参数的us",
"end": 770,
"score": 0.9928503036499023,
"start": 762,
"tag": "USERNAME",
"value": "username"
}
] | null | [] | package com.atguigu.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ContextServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1、获取web.xml中配置的上下文参数context-param
ServletContext servletContext = getServletConfig().getServletContext();
String username = servletContext.getInitParameter("username");
System.out.println("context-param参数的username的值是:" + username);
System.out.println("context-param参数password的值是:" + servletContext.getInitParameter("password"));
// 2、获取当前的工程路径,格式: /工程路径
System.out.println("当前工程路径:" + servletContext.getContextPath());
// 3、获取工程部署后在服务器硬盘上的绝对路径
/**
* / 斜杠被服务器解析地址为:http://ip:port/工程名/ 映射到IDEA代码的web目录<br/>
*/
System.out.println("工程部署的路径是:" + servletContext.getRealPath("/"));
System.out.println("工程下css目录的绝对路径是:" + servletContext.getRealPath("/css"));
System.out.println("工程下1.jpg的绝对路径是:" + servletContext.getRealPath("/imgs/1.jpg"));
}
}
| 1,686 | 0.718707 | 0.715268 | 33 | 43.060608 | 36.309227 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.575758 | false | false | 2 |
4942caa32b238327a8b316775585d9fd8a152c21 | 21,801,254,000,551 | 07ea680e0ba8539f7978aa912910dfe923fc5657 | /src/main/java/com/fse/taskmanager/domain/IUserDomain.java | d0d84edcbe50ef413c7c8224b9d687b495cbc35e | [] | no_license | VinothKumar1702/task-manager-repo | https://github.com/VinothKumar1702/task-manager-repo | 5828b5ad01c5b52e72aa4e81e76ae86f39b077be | d20e264f5b68140f419fc1c56066e2411e9ee04c | refs/heads/master | 2020-05-26T00:09:34.284000 | 2019-07-29T09:33:56 | 2019-07-29T09:33:56 | 188,047,814 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
*
*/
package com.fse.taskmanager.domain;
import java.util.List;
import com.fse.taskmanager.dto.UserDTO;
// TODO: Auto-generated Javadoc
/**
* The Interface IUserDomain.
*/
public interface IUserDomain {
/**
* Adds the user.
*
* @param userDto the user dto
* @return the user DTO
*/
UserDTO addUser(UserDTO userDto);
/**
* View users.
*
* @return the list
*/
List<UserDTO> viewUsers();
/**
* Delete users.
*
* @param userID the user ID
* @return true, if successful
*/
boolean deleteUsers(int userID);
/**
* Edits the users.
*
* @param userDto the user dto
* @return the user DTO
*/
UserDTO editUsers(UserDTO userDto);
/**
* Gets the user by id.
*
* @param userID the user ID
* @return the user by id
*/
UserDTO getUserById(int userID);
/**
* Gets the user by project id.
*
* @param projectId the project id
* @return the user by project id
*/
UserDTO getuserByProjectId(int projectId);
}
| UTF-8 | Java | 1,039 | java | IUserDomain.java | Java | [] | null | [] | /*
*
*/
package com.fse.taskmanager.domain;
import java.util.List;
import com.fse.taskmanager.dto.UserDTO;
// TODO: Auto-generated Javadoc
/**
* The Interface IUserDomain.
*/
public interface IUserDomain {
/**
* Adds the user.
*
* @param userDto the user dto
* @return the user DTO
*/
UserDTO addUser(UserDTO userDto);
/**
* View users.
*
* @return the list
*/
List<UserDTO> viewUsers();
/**
* Delete users.
*
* @param userID the user ID
* @return true, if successful
*/
boolean deleteUsers(int userID);
/**
* Edits the users.
*
* @param userDto the user dto
* @return the user DTO
*/
UserDTO editUsers(UserDTO userDto);
/**
* Gets the user by id.
*
* @param userID the user ID
* @return the user by id
*/
UserDTO getUserById(int userID);
/**
* Gets the user by project id.
*
* @param projectId the project id
* @return the user by project id
*/
UserDTO getuserByProjectId(int projectId);
}
| 1,039 | 0.598653 | 0.598653 | 63 | 14.492064 | 13.920264 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.809524 | false | false | 2 |
e790dcf84c8203637f170a030dbd4200d87f9d0f | 23,416,161,706,885 | 919a3a9effffead3e6c170567dae816143deaa5f | /bookPurchase/src/main/java/com/engineering/bookpurchase/detail/pojo/BookDetail.java | 677b7199b650009c58cbec94f1b7bc8bd937eb2d | [] | no_license | CallMeAlec1106/Joe_house | https://github.com/CallMeAlec1106/Joe_house | 161393c91ba4f7946ca08e0a2376d5131c864dcb | b37f4d1d4738d94c453449e735699b88fd2a330c | refs/heads/master | 2020-08-17T18:57:05.906000 | 2019-10-18T03:44:08 | 2019-10-18T03:44:08 | 215,700,027 | 0 | 0 | null | false | 2019-10-17T08:46:41 | 2019-10-17T04:00:28 | 2019-10-17T08:45:42 | 2019-10-17T08:46:40 | 0 | 0 | 0 | 1 | Java | false | false | package com.engineering.bookpurchase.detail.pojo;
import com.engineering.bookpurchase.common.pojo.BookUpload;
import com.engineering.bookpurchase.type.pojo.BookType;
public class BookDetail {
private Integer bookid;
private String bookname;
private String author;
private String content;
private String price;
private String discount;
private String booktypeid;
private String bookuploadid;
private BookType bookType;
private BookUpload bookUpload;
public BookDetail() {
}
public Integer getBookid() {
return this.bookid;
}
public void setBookid(Integer bookid) {
this.bookid = bookid;
}
public String getBookname() {
return this.bookname;
}
public void setBookname(String bookname) {
this.bookname = bookname == null ? null : bookname.trim();
}
public String getAuthor() {
return this.author;
}
public void setAuthor(String author) {
this.author = author == null ? null : author.trim();
}
public String getContent() {
return this.content;
}
public void setContent(String content) {
this.content = content == null ? null : content.trim();
}
public String getPrice() {
return this.price;
}
public void setPrice(String price) {
this.price = price == null ? null : price.trim();
}
public String getDiscount() {
return this.discount;
}
public void setDiscount(String discount) {
this.discount = discount == null ? null : discount.trim();
}
public String getBooktypeid() {
return this.booktypeid;
}
public void setBooktypeid(String booktypeid) {
this.booktypeid = booktypeid == null ? null : booktypeid.trim();
}
public BookType getBookType() {
return bookType;
}
public void setBookType(BookType bookType) {
this.bookType = bookType;
}
public String getBookuploadid() {
return bookuploadid;
}
public void setBookuploadid(String bookuploadid) {
this.bookuploadid = bookuploadid;
}
public BookUpload getBookUpload() {
return bookUpload;
}
public void setBookUpload(BookUpload bookUpload) {
this.bookUpload = bookUpload;
}
} | UTF-8 | Java | 2,308 | java | BookDetail.java | Java | [] | null | [] | package com.engineering.bookpurchase.detail.pojo;
import com.engineering.bookpurchase.common.pojo.BookUpload;
import com.engineering.bookpurchase.type.pojo.BookType;
public class BookDetail {
private Integer bookid;
private String bookname;
private String author;
private String content;
private String price;
private String discount;
private String booktypeid;
private String bookuploadid;
private BookType bookType;
private BookUpload bookUpload;
public BookDetail() {
}
public Integer getBookid() {
return this.bookid;
}
public void setBookid(Integer bookid) {
this.bookid = bookid;
}
public String getBookname() {
return this.bookname;
}
public void setBookname(String bookname) {
this.bookname = bookname == null ? null : bookname.trim();
}
public String getAuthor() {
return this.author;
}
public void setAuthor(String author) {
this.author = author == null ? null : author.trim();
}
public String getContent() {
return this.content;
}
public void setContent(String content) {
this.content = content == null ? null : content.trim();
}
public String getPrice() {
return this.price;
}
public void setPrice(String price) {
this.price = price == null ? null : price.trim();
}
public String getDiscount() {
return this.discount;
}
public void setDiscount(String discount) {
this.discount = discount == null ? null : discount.trim();
}
public String getBooktypeid() {
return this.booktypeid;
}
public void setBooktypeid(String booktypeid) {
this.booktypeid = booktypeid == null ? null : booktypeid.trim();
}
public BookType getBookType() {
return bookType;
}
public void setBookType(BookType bookType) {
this.bookType = bookType;
}
public String getBookuploadid() {
return bookuploadid;
}
public void setBookuploadid(String bookuploadid) {
this.bookuploadid = bookuploadid;
}
public BookUpload getBookUpload() {
return bookUpload;
}
public void setBookUpload(BookUpload bookUpload) {
this.bookUpload = bookUpload;
}
} | 2,308 | 0.639081 | 0.639081 | 100 | 22.09 | 20.230717 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.33 | false | false | 2 |
6a788814a153a05b3ee5444f70e97ac43adf7e78 | 4,423,816,326,266 | 04e7a965eaa73f9e7a84e524c53f27f1632fd924 | /dbserver/src/main/java/com/quanmin/spring/wrapper/ObjectFactory.java | 11680c62ec27a18a7ea471746284c7d6eab44566 | [] | no_license | 823126028/GameFrame | https://github.com/823126028/GameFrame | 7023edcb00c40b0404e956244c398a31c98fc5fb | e26926d64570a811d79c8fb84e69853475bc7c4b | refs/heads/master | 2020-12-05T12:37:32.331000 | 2016-08-27T07:18:24 | 2016-08-27T07:18:24 | 66,701,593 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.quanmin.spring.wrapper;
public class ObjectFactory
{
public Object buildBean(Class<?> clazz)
throws InstantiationException, IllegalAccessException
{
Object o = clazz.newInstance();
return o;
}
}
| UTF-8 | Java | 227 | java | ObjectFactory.java | Java | [] | null | [] | package com.quanmin.spring.wrapper;
public class ObjectFactory
{
public Object buildBean(Class<?> clazz)
throws InstantiationException, IllegalAccessException
{
Object o = clazz.newInstance();
return o;
}
}
| 227 | 0.726872 | 0.726872 | 12 | 17.916666 | 19.133123 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 2 |
c74eea38b76bc8817a1a16cea548be7f40a769ab | 23,991,687,328,645 | fc4e9ad6d2acabfd80559efda9dd67183bfd9da5 | /JAVA/JAVA INDIV/SmartStart Nidhal Final/src/GUI/InscriptionFreelancerFXMLController.java | 8511de4226f070948241d42b604a4be4821b6f71 | [] | no_license | NidhalATTIA/Epsilon | https://github.com/NidhalATTIA/Epsilon | 711da40537beee4d5d5ad2abf31e8499845c1c1e | 27c7bb7b5df48b46c2b43849e43a20c4dc4e9fc9 | refs/heads/master | 2022-12-12T05:44:38.037000 | 2020-01-16T07:49:20 | 2020-01-16T07:49:20 | 211,060,325 | 0 | 0 | null | false | 2022-12-06T03:28:00 | 2019-09-26T10:14:10 | 2020-01-16T07:49:23 | 2022-12-06T03:27:58 | 82,929 | 0 | 0 | 14 | JavaScript | false | false | /*
* 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 GUI;
import Entite.Freelancer;
import Service.ServiceFreelancer;
import Service.ServiceAuthentification;
import static Service.ServiceSujet_forum.s;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.stage.FileChooser;
import javax.imageio.ImageIO;
/**
* FXML Controller class
*
* @author Arzack
*/
public class InscriptionFreelancerFXMLController implements Initializable {
@FXML
private TextField tfNom;
@FXML
private TextField tfPrenom;
@FXML
private TextField tfEmail;
@FXML
private TextField tfMotDePass;
@FXML
private TextField tfCv;
@FXML
private TextField tfNationalite;
@FXML
private Button Bconnexion;
@FXML
private Button BcontactUS;
@FXML
private Button BajouterFreelancer;
@FXML
private Button Bback;
@FXML
private TextArea tfDescription;
@FXML
private Button bAboutUs;
@FXML
private ImageView Bavatar;
Freelancer f = new Freelancer();
Image card=null;
BufferedImage image;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
@FXML
private void ajouterFreelancer(ActionEvent event) throws IOException {
f.setNom(tfNom.getText());
f.setPrenom(tfPrenom.getText());
f.setMotDePass(tfMotDePass.getText());
f.setEmail(tfEmail.getText());
f.setNationalite(tfNationalite.getText());
f.setCv(tfCv.getText());
f.setDescription(tfDescription.getText());
ServiceFreelancer sp = new ServiceFreelancer();
try {
sp.ajouterFree(f);
} catch (SQLException ex) {
Logger.getLogger(InscriptionFreelancerFXMLController.class.getName()).log(Level.SEVERE, null, ex);
}
Parent root5 = FXMLLoader.load(getClass().getResource("AcceuilFXML.fxml"));
BajouterFreelancer.getScene().setRoot(root5);
}
@FXML
private void Connexion(ActionEvent event) throws IOException {
Parent root1 = FXMLLoader.load(getClass().getResource("LoginFXML.fxml"));
Bconnexion.getScene().setRoot(root1);
}
@FXML
private void AboutUs(ActionEvent event) throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("AboutUSFXML.fxml"));
bAboutUs.getScene().setRoot(root);
}
@FXML
private void ContactUs(ActionEvent event) throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("ContactUSFXML.fxml"));
BcontactUS.getScene().setRoot(root);
}
@FXML
private void Back(ActionEvent event) throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("AcceuilFXML.fxml"));
BcontactUS.getScene().setRoot(root);
Bback.getScene().setRoot(root);
}
//imagep def
final FileChooser fileChooser = new FileChooser();
byte[] imagep=null;
@FXML
private void Avatar(MouseEvent event) throws FileNotFoundException, IOException {
final FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().addAll(
// new FileChooser.ExtensionFilter("JPG", ".jpg"),
// new FileChooser.ExtensionFilter("PNG", ".png")
);
File file = fileChooser.showOpenDialog(null);
String filename =file.getAbsolutePath();
File images= new File(filename);
FileInputStream fis = new FileInputStream (images);
ByteArrayOutputStream bis = new ByteArrayOutputStream();
byte []buf = new byte[1024];
for (int i;(i=fis.read(buf))!=-1;){
bis.write(buf, 0, i);
}
imagep=bis.toByteArray();
if (imagep!=null){
System.out.println(imagep);
f.setImage(imagep);
try {
image=ImageIO.read(new ByteArrayInputStream(f.getImage()));
card= SwingFXUtils.toFXImage(image, null );
} catch (IOException ex) {
Logger.getLogger(AcceuilFXMLController.class.getName()).log(Level.SEVERE, null, ex);
}
Bavatar.setImage(card);
}
}
}
| UTF-8 | Java | 5,260 | java | InscriptionFreelancerFXMLController.java | Java | [
{
"context": "geIO;\n\n\n/**\n * FXML Controller class\n *\n * @author Arzack\n */\n\npublic class InscriptionFreelancerFXMLContro",
"end": 1284,
"score": 0.9991178512573242,
"start": 1278,
"tag": "NAME",
"value": "Arzack"
}
] | 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 GUI;
import Entite.Freelancer;
import Service.ServiceFreelancer;
import Service.ServiceAuthentification;
import static Service.ServiceSujet_forum.s;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.stage.FileChooser;
import javax.imageio.ImageIO;
/**
* FXML Controller class
*
* @author Arzack
*/
public class InscriptionFreelancerFXMLController implements Initializable {
@FXML
private TextField tfNom;
@FXML
private TextField tfPrenom;
@FXML
private TextField tfEmail;
@FXML
private TextField tfMotDePass;
@FXML
private TextField tfCv;
@FXML
private TextField tfNationalite;
@FXML
private Button Bconnexion;
@FXML
private Button BcontactUS;
@FXML
private Button BajouterFreelancer;
@FXML
private Button Bback;
@FXML
private TextArea tfDescription;
@FXML
private Button bAboutUs;
@FXML
private ImageView Bavatar;
Freelancer f = new Freelancer();
Image card=null;
BufferedImage image;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
@FXML
private void ajouterFreelancer(ActionEvent event) throws IOException {
f.setNom(tfNom.getText());
f.setPrenom(tfPrenom.getText());
f.setMotDePass(tfMotDePass.getText());
f.setEmail(tfEmail.getText());
f.setNationalite(tfNationalite.getText());
f.setCv(tfCv.getText());
f.setDescription(tfDescription.getText());
ServiceFreelancer sp = new ServiceFreelancer();
try {
sp.ajouterFree(f);
} catch (SQLException ex) {
Logger.getLogger(InscriptionFreelancerFXMLController.class.getName()).log(Level.SEVERE, null, ex);
}
Parent root5 = FXMLLoader.load(getClass().getResource("AcceuilFXML.fxml"));
BajouterFreelancer.getScene().setRoot(root5);
}
@FXML
private void Connexion(ActionEvent event) throws IOException {
Parent root1 = FXMLLoader.load(getClass().getResource("LoginFXML.fxml"));
Bconnexion.getScene().setRoot(root1);
}
@FXML
private void AboutUs(ActionEvent event) throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("AboutUSFXML.fxml"));
bAboutUs.getScene().setRoot(root);
}
@FXML
private void ContactUs(ActionEvent event) throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("ContactUSFXML.fxml"));
BcontactUS.getScene().setRoot(root);
}
@FXML
private void Back(ActionEvent event) throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("AcceuilFXML.fxml"));
BcontactUS.getScene().setRoot(root);
Bback.getScene().setRoot(root);
}
//imagep def
final FileChooser fileChooser = new FileChooser();
byte[] imagep=null;
@FXML
private void Avatar(MouseEvent event) throws FileNotFoundException, IOException {
final FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().addAll(
// new FileChooser.ExtensionFilter("JPG", ".jpg"),
// new FileChooser.ExtensionFilter("PNG", ".png")
);
File file = fileChooser.showOpenDialog(null);
String filename =file.getAbsolutePath();
File images= new File(filename);
FileInputStream fis = new FileInputStream (images);
ByteArrayOutputStream bis = new ByteArrayOutputStream();
byte []buf = new byte[1024];
for (int i;(i=fis.read(buf))!=-1;){
bis.write(buf, 0, i);
}
imagep=bis.toByteArray();
if (imagep!=null){
System.out.println(imagep);
f.setImage(imagep);
try {
image=ImageIO.read(new ByteArrayInputStream(f.getImage()));
card= SwingFXUtils.toFXImage(image, null );
} catch (IOException ex) {
Logger.getLogger(AcceuilFXMLController.class.getName()).log(Level.SEVERE, null, ex);
}
Bavatar.setImage(card);
}
}
}
| 5,260 | 0.664068 | 0.662167 | 172 | 29.552326 | 24.012899 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.604651 | false | false | 2 |
9f704953ba06ef9cfad2b92178bc7bc2ae557ea3 | 25,701,084,311,404 | 1be80c8341a7243313d209ab39af502ff3df080d | / jinchenfly-project-projectx/ProjectX/com/projectx/bean/Archer.java | 401475fd8dc825ae6a63b972bfe9372e35facfb9 | [] | no_license | jinchenfly/jinchenfly-project-projectx | https://github.com/jinchenfly/jinchenfly-project-projectx | b1c6e7d55d9f97ae5714f693c6a496276d3017ab | f6f886b42a777139223e7022c88aff5f56a3e2b7 | refs/heads/master | 2021-01-22T20:29:25.328000 | 2013-06-26T02:09:26 | 2013-06-26T02:09:26 | 32,115,225 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.projectx.bean;
import com.projectx.base.Point;
public class Archer extends Person {
public Archer(Point p) {
super(p);
MaxHP=100;
range = 3;
str = 10;
dex = 20;
agi = 12;
mobility = 3;
keepDistance = 3;
HP = MaxHP;
luc = 5;
}
}
| UTF-8 | Java | 291 | java | Archer.java | Java | [] | null | [] | package com.projectx.bean;
import com.projectx.base.Point;
public class Archer extends Person {
public Archer(Point p) {
super(p);
MaxHP=100;
range = 3;
str = 10;
dex = 20;
agi = 12;
mobility = 3;
keepDistance = 3;
HP = MaxHP;
luc = 5;
}
}
| 291 | 0.563574 | 0.5189 | 21 | 11.857142 | 10.329273 | 36 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.761905 | false | false | 2 |
16f60d55f63bab62c02ba23069eabd94665df3c2 | 5,085,241,293,154 | a159752f6f74716bec9a676be8d1c1c42033839b | /ressvr/src/main/java/com/garyzhangscm/cwms/resources/model/PutawayInventoryFileUpload.java | 3659bf1f1145c66c4f58725550ac65bb4255d2b8 | [] | no_license | garyzhangscm/cwms | https://github.com/garyzhangscm/cwms | bdf71fd145e5f8a95cdad3520c1196b32649dd8a | 73b053bce2b86d42e16255d5fb4fe5f8f99d4665 | refs/heads/master | 2023-08-05T02:52:46.243000 | 2023-08-01T04:47:29 | 2023-08-01T04:47:29 | 199,084,976 | 1 | 0 | null | false | 2023-08-01T04:33:45 | 2019-07-26T22:01:04 | 2023-07-31T21:17:29 | 2023-08-01T04:33:43 | 77,965 | 1 | 0 | 0 | Java | false | false | package com.garyzhangscm.cwms.resources.model;
public class PutawayInventoryFileUpload extends FileUploadType {
public PutawayInventoryFileUpload(){
super("putaway-inventories", "Putaway Inventory",
"inventory/inventories/putaway-inventory/upload",
"resource/assets/file-templates/putaway-inventories.csv",
"inventory/inventories/putaway-inventory/upload/progress",
"inventory/inventories/putaway-inventory/upload/result");
setupColumns();
}
private void setupColumns() {
addColumn(new FileUploadTemplateColumn(
"client", "Client",
String.class, 100, true
));
addColumn(new FileUploadTemplateColumn(
"lpn", "LPN",
String.class, 100, true
));
addColumn(new FileUploadTemplateColumn(
"location", "location",
String.class, 100, false
));
addColumn(new FileUploadTemplateColumn(
"item", "Item Name",
String.class, 100, false
));
addColumn(new FileUploadTemplateColumn(
"itemPackageType", "Item Package Type",
String.class, 100, false
));
addColumn(new FileUploadTemplateColumn(
"quantity", "Quantity",
Long.class, 100, false
));
addColumn(new FileUploadTemplateColumn(
"unitOfMeasure", "Unit Of Measure",
String.class, 10, true
));
addColumn(new FileUploadTemplateColumn(
"inventoryStatus", "Inventory Status",
String.class, 100, false
));
addColumn(new FileUploadTemplateColumn(
"color", "Color",
String.class, 100, false
));
addColumn(new FileUploadTemplateColumn(
"productSize", "Product Size",
String.class, 100, false
));
addColumn(new FileUploadTemplateColumn(
"style", "Style",
String.class, 100, false
));
addColumn(new FileUploadTemplateColumn(
"destinationLocation", "Destination Location",
String.class, 100, false
));
}
}
| UTF-8 | Java | 2,320 | java | PutawayInventoryFileUpload.java | Java | [] | null | [] | package com.garyzhangscm.cwms.resources.model;
public class PutawayInventoryFileUpload extends FileUploadType {
public PutawayInventoryFileUpload(){
super("putaway-inventories", "Putaway Inventory",
"inventory/inventories/putaway-inventory/upload",
"resource/assets/file-templates/putaway-inventories.csv",
"inventory/inventories/putaway-inventory/upload/progress",
"inventory/inventories/putaway-inventory/upload/result");
setupColumns();
}
private void setupColumns() {
addColumn(new FileUploadTemplateColumn(
"client", "Client",
String.class, 100, true
));
addColumn(new FileUploadTemplateColumn(
"lpn", "LPN",
String.class, 100, true
));
addColumn(new FileUploadTemplateColumn(
"location", "location",
String.class, 100, false
));
addColumn(new FileUploadTemplateColumn(
"item", "Item Name",
String.class, 100, false
));
addColumn(new FileUploadTemplateColumn(
"itemPackageType", "Item Package Type",
String.class, 100, false
));
addColumn(new FileUploadTemplateColumn(
"quantity", "Quantity",
Long.class, 100, false
));
addColumn(new FileUploadTemplateColumn(
"unitOfMeasure", "Unit Of Measure",
String.class, 10, true
));
addColumn(new FileUploadTemplateColumn(
"inventoryStatus", "Inventory Status",
String.class, 100, false
));
addColumn(new FileUploadTemplateColumn(
"color", "Color",
String.class, 100, false
));
addColumn(new FileUploadTemplateColumn(
"productSize", "Product Size",
String.class, 100, false
));
addColumn(new FileUploadTemplateColumn(
"style", "Style",
String.class, 100, false
));
addColumn(new FileUploadTemplateColumn(
"destinationLocation", "Destination Location",
String.class, 100, false
));
}
}
| 2,320 | 0.549138 | 0.534052 | 79 | 28.367088 | 22.301828 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.860759 | false | false | 2 |
5ea1601d0146f1b3ee4f1741745af3ffba2d8ec0 | 34,170,759,862,419 | 6f4949ba731a8f7a460219a2e85d8ba6e418cb9f | /src/main/java/com/demo/shortenurl/controller/ApiController.java | fd1f27a6c4f86b91d4878142b9fdf54fa5caafb4 | [] | no_license | Jeffrey778/shorten-url | https://github.com/Jeffrey778/shorten-url | 3ef7ee0c6e260cbe29eedc6f228154f972566c5b | 2fc1fa7b421d06bb06612b90b56c8dafa3705ea9 | refs/heads/master | 2020-04-05T02:57:27.576000 | 2018-11-07T05:51:34 | 2018-11-07T05:51:34 | 156,495,860 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.demo.shortenurl.controller;
import com.demo.shortenurl.service.ShortenUrlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ApiController {
@Autowired
private ShortenUrlService shortenUrlService;
@GetMapping("/api")
public ResponseEntity<Object> shorten(@RequestParam("url") String url) {
// TODO url格式校验
try {
return ResponseEntity.ok("http://域名.com/" + shortenUrlService.shorten(url));
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
@GetMapping("/{shortUrl}")
public ResponseEntity<Object> restore(@PathVariable("shortUrl") String shortUrl) {
String url = shortenUrlService.restore(shortUrl);
return ResponseEntity.status(HttpStatus.MOVED_PERMANENTLY)
.header("location", url)
.build();
}
}
| UTF-8 | Java | 1,330 | java | ApiController.java | Java | [] | null | [] | package com.demo.shortenurl.controller;
import com.demo.shortenurl.service.ShortenUrlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ApiController {
@Autowired
private ShortenUrlService shortenUrlService;
@GetMapping("/api")
public ResponseEntity<Object> shorten(@RequestParam("url") String url) {
// TODO url格式校验
try {
return ResponseEntity.ok("http://域名.com/" + shortenUrlService.shorten(url));
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
@GetMapping("/{shortUrl}")
public ResponseEntity<Object> restore(@PathVariable("shortUrl") String shortUrl) {
String url = shortenUrlService.restore(shortUrl);
return ResponseEntity.status(HttpStatus.MOVED_PERMANENTLY)
.header("location", url)
.build();
}
}
| 1,330 | 0.72003 | 0.72003 | 36 | 35.611111 | 27.067076 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 2 |
034a1d7a11fc2c53587127067ec5a8d22adb2b09 | 25,537,875,596,218 | 11cba129c887fed0ff7d66a3d8268636ca2a82c3 | /org.jrebirth/core/src/main/java/org/jrebirth/core/command/AbstractPoolCommand.java | 94b00e8e34781d8f7f778bbb446d9c268fb67fb9 | [] | no_license | cbordes/JRebirth | https://github.com/cbordes/JRebirth | d44e4a05fcadcf36eb7a265e21b1ade020c6dbee | 33a8e833d8e81fa328a46c08df00ea6839c996b7 | refs/heads/master | 2020-12-25T12:18:18.143000 | 2012-03-29T20:30:35 | 2012-03-29T20:30:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.jrebirth.core.command;
import org.jrebirth.core.concurent.RunIntoType;
/**
* The class <strong>AbstractPoolCommand</strong>.
*
* Base implementation for Commands that will be run into a thread pool.
*
* @author Sébastien Bordes
*/
public abstract class AbstractPoolCommand extends AbstractBaseCommand {
/**
* Default Constructor used to run this action within the thread pool.
*/
public AbstractPoolCommand() {
super(RunIntoType.POOL);
}
}
| UTF-8 | Java | 516 | java | AbstractPoolCommand.java | Java | [
{
"context": "t will be run into a thread pool.\r\n * \r\n * @author Sébastien Bordes\r\n */\r\npublic abstract class AbstractPoolCommand e",
"end": 257,
"score": 0.999871551990509,
"start": 241,
"tag": "NAME",
"value": "Sébastien Bordes"
}
] | null | [] | package org.jrebirth.core.command;
import org.jrebirth.core.concurent.RunIntoType;
/**
* The class <strong>AbstractPoolCommand</strong>.
*
* Base implementation for Commands that will be run into a thread pool.
*
* @author <NAME>
*/
public abstract class AbstractPoolCommand extends AbstractBaseCommand {
/**
* Default Constructor used to run this action within the thread pool.
*/
public AbstractPoolCommand() {
super(RunIntoType.POOL);
}
}
| 505 | 0.683495 | 0.683495 | 21 | 22.523809 | 25.802582 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.142857 | false | false | 2 |
cdb3fef90231f6e2156f93ced2d09abd5a1727bb | 25,537,875,599,978 | c0343009b5e0bf497283f5c50fb092cdb4f85da8 | /app/src/main/java/project/letshang/Forum.java | 87e1ebd754e7aa93aa58a2d49233aeefe6e158a8 | [] | no_license | SofiaVit/LetsHang | https://github.com/SofiaVit/LetsHang | ccd741171f84060ed799c5bd1481e4690128ba0d | 011325da010207aca6da372a4d6ec2aedaba2af8 | refs/heads/master | 2020-05-04T19:33:22.703000 | 2019-06-14T10:32:45 | 2019-06-14T10:32:45 | 179,398,941 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package project.letshang;
import android.app.Activity;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Forum extends AppCompatActivity {
private ListView mListView;
private ListAdapterForum adapter;
private List<ForumForList> forumList;
private Context mContext;
private Activity mActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forum);
final String forum = getIntent().getStringExtra("forum");
final String meetingId = getIntent().getStringExtra("meetingId");
this.mActivity = this;
this.mContext = this;
if(forum.equals("noMessages")){
((TextView)findViewById(R.id.noMessagesText)).setVisibility(View.VISIBLE);
}
else {
String[] temp = forum.split("\\|\\|");
forumList = new ArrayList<>();
int i = 0;
int id = 1;
while (i < temp.length) {
forumList.add(new ForumForList(id, temp[i], temp[i + 1], temp[i + 2]));
i = i + 4;
id = id + 1;
}
mListView = (ListView) findViewById(R.id.messagesList);
adapter = new ListAdapterForum(this, forumList);
mListView.setAdapter(adapter);
}
((ImageView)findViewById(R.id.envelopeButton)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String message = ((EditText)findViewById(R.id.forumMessageText)).getText().toString();
database db = new database(mContext,mActivity);
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
db.execute("forumWriteMessage",meetingId,userInfoFile.getUserName(mContext),message,dateFormat.format(date));
}
});
}
}
| UTF-8 | Java | 2,333 | java | Forum.java | Java | [] | null | [] | package project.letshang;
import android.app.Activity;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Forum extends AppCompatActivity {
private ListView mListView;
private ListAdapterForum adapter;
private List<ForumForList> forumList;
private Context mContext;
private Activity mActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forum);
final String forum = getIntent().getStringExtra("forum");
final String meetingId = getIntent().getStringExtra("meetingId");
this.mActivity = this;
this.mContext = this;
if(forum.equals("noMessages")){
((TextView)findViewById(R.id.noMessagesText)).setVisibility(View.VISIBLE);
}
else {
String[] temp = forum.split("\\|\\|");
forumList = new ArrayList<>();
int i = 0;
int id = 1;
while (i < temp.length) {
forumList.add(new ForumForList(id, temp[i], temp[i + 1], temp[i + 2]));
i = i + 4;
id = id + 1;
}
mListView = (ListView) findViewById(R.id.messagesList);
adapter = new ListAdapterForum(this, forumList);
mListView.setAdapter(adapter);
}
((ImageView)findViewById(R.id.envelopeButton)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String message = ((EditText)findViewById(R.id.forumMessageText)).getText().toString();
database db = new database(mContext,mActivity);
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
db.execute("forumWriteMessage",meetingId,userInfoFile.getUserName(mContext),message,dateFormat.format(date));
}
});
}
}
| 2,333 | 0.638234 | 0.635234 | 63 | 36.031746 | 26.50305 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.857143 | false | false | 2 |
97ae48cb8f4974e828638382f64bc9369578e475 | 39,213,051,428,581 | 0c9f7095c15f40cd250c1b87fbf301b370241e8e | /app/src/main/java/com/example/amansingh/spinneractv/MainActivity.java | d0b92a86c8a8c8be2b62392be1458d85e6005f15 | [] | no_license | Amanksingh16/SpinnerACTV_AndroidAssignment | https://github.com/Amanksingh16/SpinnerACTV_AndroidAssignment | fb4cf835590f7fb65855356eb8a0d7d7cc6eddad | 03bd9f3881698a45f21c33e9ab32ea4f005fafbe | refs/heads/master | 2020-03-11T08:55:04.797000 | 2018-04-18T00:16:58 | 2018-04-18T00:16:58 | 129,895,978 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.amansingh.spinneractv;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
String State[] = {"Punjab","Uttar Pradesh","Madhya Pradesh","Rajasthan","Bihar","Uttarakhand"};
String punarr[] = {"Jalandhar","Patiala","Ludhiana","Amritsar","Chandigarh"};
String UParr[] = {"Lucknow","Noida","Allahbad","Kanpur","Meerut"};
String MParr[] = {"Bhopal","Indore","Jabalpur","Itarsi"};
String Rajarr[] = {"Jaipur","Ajmer","Jodhpur","Jaisalmer","Udaipur","Suratgarh"};
String Biharr[] = {"Muffarpur","Patna","Gaya","Samastipur","Katihar"};
String Uttarr[] = {"Dehradun","Haridwar","Rishikesh"};
EditText name, phone , email;
Spinner state;
Button save;
String stateval;
int value;
AutoCompleteTextView city;
ArrayAdapter<String> adapter;
ArrayAdapter<String> cityadapter;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.name);
phone = (EditText)findViewById(R.id.phone);
email = (EditText)findViewById(R.id.email);
state = (Spinner)findViewById(R.id.spinner);
city = (AutoCompleteTextView)findViewById(R.id.autoCompleteTextView);
save = (Button)findViewById(R.id.save);
intent = getIntent();
if(intent.hasExtra("Name"))
{
name.setText(""+intent.getStringExtra("Name"));
}
if(intent.hasExtra("Phone"))
{
phone.setText(""+intent.getStringExtra("Phone"));
}
if(intent.hasExtra("Email"))
{
email.setText(""+intent.getStringExtra("Email"));
}
if(intent.hasExtra("City"))
{
city.setText(""+intent.getStringExtra("City"));
}
adapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.spinner_list,State);
state.setAdapter(adapter);
state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
Toast.makeText(getApplicationContext(),"State is "+State[position]+",select the city",Toast.LENGTH_SHORT).show();
stateval = State[position];
switch (position)
{
case 0: cityadapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,punarr);
city.setAdapter(cityadapter);
break;
case 1: cityadapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,UParr);
city.setAdapter(cityadapter);
break;
case 2: cityadapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,MParr);
city.setAdapter(cityadapter);
break;
case 3: cityadapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,Rajarr);
city.setAdapter(cityadapter);
break;
case 4: cityadapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,Biharr);
city.setAdapter(cityadapter);
break;
case 5: cityadapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,Uttarr);
city.setAdapter(cityadapter);
break;
default:
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(name.length()!=0 && phone.length()!=0 && email.length()!=0 && city.length()!=0)
{
Intent i = new Intent(MainActivity.this,SecondActivity.class);
i.putExtra("name",name.getText().toString());
i.putExtra("phone",phone.getText().toString());
i.putExtra("email",email.getText().toString());
i.putExtra("state",stateval);
i.putExtra("city",city.getText().toString());
startActivity(i);
}
else
{
Toast.makeText(getApplicationContext(),"Wrong Input",Toast.LENGTH_SHORT).show();
}
}
});
}
}
| UTF-8 | Java | 5,369 | java | MainActivity.java | Java | [] | null | [] | package com.example.amansingh.spinneractv;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
String State[] = {"Punjab","Uttar Pradesh","Madhya Pradesh","Rajasthan","Bihar","Uttarakhand"};
String punarr[] = {"Jalandhar","Patiala","Ludhiana","Amritsar","Chandigarh"};
String UParr[] = {"Lucknow","Noida","Allahbad","Kanpur","Meerut"};
String MParr[] = {"Bhopal","Indore","Jabalpur","Itarsi"};
String Rajarr[] = {"Jaipur","Ajmer","Jodhpur","Jaisalmer","Udaipur","Suratgarh"};
String Biharr[] = {"Muffarpur","Patna","Gaya","Samastipur","Katihar"};
String Uttarr[] = {"Dehradun","Haridwar","Rishikesh"};
EditText name, phone , email;
Spinner state;
Button save;
String stateval;
int value;
AutoCompleteTextView city;
ArrayAdapter<String> adapter;
ArrayAdapter<String> cityadapter;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.name);
phone = (EditText)findViewById(R.id.phone);
email = (EditText)findViewById(R.id.email);
state = (Spinner)findViewById(R.id.spinner);
city = (AutoCompleteTextView)findViewById(R.id.autoCompleteTextView);
save = (Button)findViewById(R.id.save);
intent = getIntent();
if(intent.hasExtra("Name"))
{
name.setText(""+intent.getStringExtra("Name"));
}
if(intent.hasExtra("Phone"))
{
phone.setText(""+intent.getStringExtra("Phone"));
}
if(intent.hasExtra("Email"))
{
email.setText(""+intent.getStringExtra("Email"));
}
if(intent.hasExtra("City"))
{
city.setText(""+intent.getStringExtra("City"));
}
adapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.spinner_list,State);
state.setAdapter(adapter);
state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
Toast.makeText(getApplicationContext(),"State is "+State[position]+",select the city",Toast.LENGTH_SHORT).show();
stateval = State[position];
switch (position)
{
case 0: cityadapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,punarr);
city.setAdapter(cityadapter);
break;
case 1: cityadapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,UParr);
city.setAdapter(cityadapter);
break;
case 2: cityadapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,MParr);
city.setAdapter(cityadapter);
break;
case 3: cityadapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,Rajarr);
city.setAdapter(cityadapter);
break;
case 4: cityadapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,Biharr);
city.setAdapter(cityadapter);
break;
case 5: cityadapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,Uttarr);
city.setAdapter(cityadapter);
break;
default:
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(name.length()!=0 && phone.length()!=0 && email.length()!=0 && city.length()!=0)
{
Intent i = new Intent(MainActivity.this,SecondActivity.class);
i.putExtra("name",name.getText().toString());
i.putExtra("phone",phone.getText().toString());
i.putExtra("email",email.getText().toString());
i.putExtra("state",stateval);
i.putExtra("city",city.getText().toString());
startActivity(i);
}
else
{
Toast.makeText(getApplicationContext(),"Wrong Input",Toast.LENGTH_SHORT).show();
}
}
});
}
}
| 5,369 | 0.578692 | 0.575526 | 126 | 41.611111 | 33.256096 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.063492 | false | false | 2 |
9c28997affea9ccc4b03635d2fb620d662c320ee | 37,460,704,787,921 | 180552e7ad33db69dd1ec792d90c4aaf0cede793 | /livy/src/main/java/org/apache/zeppelin/livy/BaseLivyInterpreter.java | f7b576d8188f19d2ca4bd891a2e589918b32a02b | [
"BSD-3-Clause",
"EPL-1.0",
"OFL-1.1",
"MIT",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | apache/zeppelin | https://github.com/apache/zeppelin | 1fe6ff92aaddace456806f58d93a42a9245b641b | ed958b538d67539cc8bc232668cce1163f51c468 | refs/heads/master | 2023-08-29T07:01:59.940000 | 2023-08-22T06:45:44 | 2023-08-22T06:45:44 | 32,848,140 | 5,119 | 2,758 | Apache-2.0 | false | 2023-09-14T14:02:27 | 2015-03-25T07:00:06 | 2023-09-14T08:03:05 | 2023-09-14T14:02:27 | 101,465 | 6,144 | 2,767 | 146 | 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.zeppelin.livy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.auth.AuthSchemeProvider;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.impl.auth.SPNegoSchemeFactory;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.security.kerberos.client.KerberosRestTemplate;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.SSLContext;
import org.apache.zeppelin.interpreter.Interpreter;
import org.apache.zeppelin.interpreter.InterpreterContext;
import org.apache.zeppelin.interpreter.InterpreterException;
import org.apache.zeppelin.interpreter.InterpreterResult;
import org.apache.zeppelin.interpreter.InterpreterResultMessage;
import org.apache.zeppelin.interpreter.InterpreterUtils;
import org.apache.zeppelin.interpreter.thrift.InterpreterCompletion;
/**
* Base class for livy interpreters.
*/
public abstract class BaseLivyInterpreter extends Interpreter {
protected static final Logger LOGGER = LoggerFactory.getLogger(BaseLivyInterpreter.class);
private static Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
private static final String SESSION_NOT_FOUND_PATTERN = "(.*)\"Session '\\d+' not found.\"(.*)";
protected volatile SessionInfo sessionInfo;
private String livyURL;
private int sessionCreationTimeout;
private int pullStatusInterval;
private int maxLogLines;
protected boolean displayAppInfo;
private boolean restartDeadSession;
protected LivyVersion livyVersion;
private RestTemplate restTemplate;
private Map<String, String> customHeaders = new HashMap<>();
// delegate to sharedInterpreter when it is available
protected LivySharedInterpreter sharedInterpreter;
Set<Object> paragraphsToCancel = Collections.newSetFromMap(
new ConcurrentHashMap<Object, Boolean>());
private ConcurrentHashMap<String, Integer> paragraphId2StmtProgressMap =
new ConcurrentHashMap<>();
public BaseLivyInterpreter(Properties property) {
super(property);
this.livyURL = property.getProperty("zeppelin.livy.url");
this.displayAppInfo = Boolean.parseBoolean(
property.getProperty("zeppelin.livy.displayAppInfo", "true"));
this.restartDeadSession = Boolean.parseBoolean(
property.getProperty("zeppelin.livy.restart_dead_session", "false"));
this.sessionCreationTimeout = Integer.parseInt(
property.getProperty("zeppelin.livy.session.create_timeout", 120 + ""));
this.pullStatusInterval = Integer.parseInt(
property.getProperty("zeppelin.livy.pull_status.interval.millis", 1000 + ""));
this.maxLogLines = Integer.parseInt(property.getProperty("zeppelin.livy.maxLogLines",
"1000"));
this.restTemplate = createRestTemplate();
if (!StringUtils.isBlank(property.getProperty("zeppelin.livy.http.headers"))) {
String[] headers = property.getProperty("zeppelin.livy.http.headers").split(";");
for (String header : headers) {
String[] splits = header.split(":", -1);
if (splits.length != 2) {
throw new RuntimeException("Invalid format of http headers: " + header +
", valid http header format is HEADER_NAME:HEADER_VALUE");
}
customHeaders.put(splits[0].trim(), envSubstitute(splits[1].trim()));
}
}
}
private String envSubstitute(String value) {
String newValue = new String(value);
Pattern pattern = Pattern.compile("\\$\\{(.*)\\}");
Matcher matcher = pattern.matcher(value);
while (matcher.find()) {
String env = matcher.group(1);
newValue = newValue.replace("${" + env + "}", System.getenv(env));
}
return newValue;
}
// only for testing
Map<String, String> getCustomHeaders() {
return customHeaders;
}
public abstract String getSessionKind();
@Override
public void open() throws InterpreterException {
try {
this.livyVersion = getLivyVersion();
if (this.livyVersion.isSharedSupported()) {
sharedInterpreter = getInterpreterInTheSameSessionByClassName(LivySharedInterpreter.class);
}
if (sharedInterpreter == null || !sharedInterpreter.isSupported()) {
initLivySession();
}
} catch (LivyException e) {
String msg = "Fail to create session, please check livy interpreter log and " +
"livy server log";
throw new InterpreterException(msg, e);
}
}
@Override
public void close() {
if (sharedInterpreter != null && sharedInterpreter.isSupported()) {
sharedInterpreter.close();
return;
}
if (sessionInfo != null) {
closeSession(sessionInfo.id);
// reset sessionInfo to null so that we won't close it twice.
sessionInfo = null;
}
}
protected void initLivySession() throws LivyException {
this.sessionInfo = createSession(getUserName(), getSessionKind());
if (displayAppInfo) {
if (sessionInfo.appId == null) {
// livy 0.2 don't return appId and sparkUiUrl in response so that we need to get it
// explicitly by ourselves.
sessionInfo.appId = extractAppId();
}
if (sessionInfo.appInfo == null ||
StringUtils.isEmpty(sessionInfo.appInfo.get("sparkUiUrl"))) {
sessionInfo.webUIAddress = extractWebUIAddress();
} else {
sessionInfo.webUIAddress = sessionInfo.appInfo.get("sparkUiUrl");
}
LOGGER.info("Create livy session successfully with sessionId: {}, appId: {}, webUI: {}",
sessionInfo.id, sessionInfo.appId, sessionInfo.webUIAddress);
} else {
LOGGER.info("Create livy session successfully with sessionId: {}", this.sessionInfo.id);
}
}
protected abstract String extractAppId() throws LivyException;
protected abstract String extractWebUIAddress() throws LivyException;
public SessionInfo getSessionInfo() {
if (sharedInterpreter != null && sharedInterpreter.isSupported()) {
return sharedInterpreter.getSessionInfo();
}
return sessionInfo;
}
public String getCodeType() {
if (getSessionKind().equalsIgnoreCase("pyspark3")) {
return "pyspark";
}
return getSessionKind();
}
@Override
public InterpreterResult interpret(String st, InterpreterContext context) {
if (sharedInterpreter != null && sharedInterpreter.isSupported()) {
return sharedInterpreter.interpret(st, getCodeType(), context);
}
if (StringUtils.isEmpty(st)) {
return new InterpreterResult(InterpreterResult.Code.SUCCESS, "");
}
try {
return interpret(st, null, context.getParagraphId(), this.displayAppInfo, true, true);
} catch (LivyException e) {
LOGGER.error("Fail to interpret: {}", st, e);
return new InterpreterResult(InterpreterResult.Code.ERROR,
InterpreterUtils.getMostRelevantMessage(e));
}
}
@Override
public List<InterpreterCompletion> completion(String buf, int cursor,
InterpreterContext interpreterContext) {
List<InterpreterCompletion> candidates = Collections.emptyList();
try {
candidates = callCompletion(new CompletionRequest(buf, getSessionKind(), cursor));
} catch (SessionNotFoundException e) {
LOGGER.warn("Livy session {} is expired. Will return empty list of candidates.",
getSessionInfo().id);
} catch (LivyException le) {
LOGGER.error("Failed to call code completions. Will return empty list of candidates", le);
}
return candidates;
}
private List<InterpreterCompletion> callCompletion(CompletionRequest req) throws LivyException {
List<InterpreterCompletion> candidates = new ArrayList<>();
try {
CompletionResponse resp = CompletionResponse.fromJson(
callRestAPI("/sessions/" + getSessionInfo().id + "/completion", "POST", req.toJson()));
for (String candidate : resp.candidates) {
candidates.add(new InterpreterCompletion(candidate, candidate, StringUtils.EMPTY));
}
} catch (APINotFoundException e) {
LOGGER.debug("completion api seems not to be available. (available from livy 0.5)", e);
}
return candidates;
}
@Override
public void cancel(InterpreterContext context) {
if (sharedInterpreter != null && sharedInterpreter.isSupported()) {
sharedInterpreter.cancel(context);
return;
}
paragraphsToCancel.add(context.getParagraphId());
LOGGER.info("Added paragraph {} for cancellation.", context.getParagraphId());
}
@Override
public FormType getFormType() {
return FormType.NATIVE;
}
@Override
public int getProgress(InterpreterContext context) {
if (sharedInterpreter != null && sharedInterpreter.isSupported()) {
return sharedInterpreter.getProgress(context);
}
if (livyVersion.isGetProgressSupported()) {
String paraId = context.getParagraphId();
Integer progress = paragraphId2StmtProgressMap.get(paraId);
return progress == null ? 0 : progress;
}
return 0;
}
private SessionInfo createSession(String user, String kind)
throws LivyException {
try {
Map<String, String> conf = new HashMap<>();
for (Map.Entry<Object, Object> entry : getProperties().entrySet()) {
if (entry.getKey().toString().startsWith("livy.spark.") &&
!entry.getValue().toString().isEmpty()) {
conf.put(entry.getKey().toString().substring(5), entry.getValue().toString());
}
}
CreateSessionRequest request = new CreateSessionRequest(kind,
user == null || user.equals("anonymous") ? null : user, conf);
SessionInfo sessionInfo = SessionInfo.fromJson(
callRestAPI("/sessions", "POST", request.toJson()));
long start = System.currentTimeMillis();
// pull the session status until it is idle or timeout
while (!sessionInfo.isReady()) {
if ((System.currentTimeMillis() - start) / 1000 > sessionCreationTimeout) {
String msg = "The creation of session " + sessionInfo.id + " is timeout within "
+ sessionCreationTimeout + " seconds, appId: " + sessionInfo.appId
+ ", log:\n" + StringUtils.join(getSessionLog(sessionInfo.id).log, "\n");
throw new LivyException(msg);
}
Thread.sleep(pullStatusInterval);
sessionInfo = getSessionInfo(sessionInfo.id);
LOGGER.info("Session {} is in state {}, appId {}", sessionInfo.id, sessionInfo.state,
sessionInfo.appId);
if (sessionInfo.isFinished()) {
String msg = "Session " + sessionInfo.id + " is finished, appId: " + sessionInfo.appId
+ ", log:\n" + StringUtils.join(getSessionLog(sessionInfo.id).log, "\n");
throw new LivyException(msg);
}
}
return sessionInfo;
} catch (Exception e) {
LOGGER.error("Error when creating livy session for user {}", user, e);
throw new LivyException(e);
}
}
private SessionInfo getSessionInfo(int sessionId) throws LivyException {
return SessionInfo.fromJson(callRestAPI("/sessions/" + sessionId, "GET"));
}
private SessionLog getSessionLog(int sessionId) throws LivyException {
return SessionLog.fromJson(callRestAPI("/sessions/" + sessionId + "/log?size=" + maxLogLines,
"GET"));
}
public InterpreterResult interpret(String code,
String paragraphId,
boolean displayAppInfo,
boolean appendSessionExpired,
boolean appendSessionDead) throws LivyException {
return interpret(code, sharedInterpreter.isSupported() ? getSessionKind() : null,
paragraphId, displayAppInfo, appendSessionExpired, appendSessionDead);
}
public InterpreterResult interpret(String code,
String codeType,
String paragraphId,
boolean displayAppInfo,
boolean appendSessionExpired,
boolean appendSessionDead) throws LivyException {
StatementInfo stmtInfo = null;
boolean sessionExpired = false;
boolean sessionDead = false;
try {
try {
stmtInfo = executeStatement(new ExecuteRequest(code, codeType));
} catch (SessionNotFoundException e) {
LOGGER.warn("Livy session {} is expired, new session will be created.", sessionInfo.id);
sessionExpired = true;
// we don't want to create multiple sessions because it is possible to have multiple thread
// to call this method, like LivySparkSQLInterpreter which use ParallelScheduler. So we need
// to check session status again in this sync block
synchronized (this) {
if (isSessionExpired()) {
initLivySession();
}
}
stmtInfo = executeStatement(new ExecuteRequest(code, codeType));
} catch (SessionDeadException e) {
sessionDead = true;
if (restartDeadSession) {
LOGGER.warn("Livy session {} is dead, new session will be created.", sessionInfo.id);
close();
try {
open();
} catch (InterpreterException ie) {
throw new LivyException("Fail to restart livy session", ie);
}
stmtInfo = executeStatement(new ExecuteRequest(code, codeType));
} else {
throw new LivyException("%html <font color=\"red\">Livy session is dead somehow, " +
"please check log to see why it is dead, and then restart livy interpreter</font>");
}
}
// pull the statement status
while (!stmtInfo.isAvailable()) {
if (paragraphId != null && paragraphsToCancel.contains(paragraphId)) {
cancel(stmtInfo.id, paragraphId);
return new InterpreterResult(InterpreterResult.Code.ERROR, "Job is cancelled");
}
try {
Thread.sleep(pullStatusInterval);
} catch (InterruptedException e) {
LOGGER.error("InterruptedException when pulling statement status.", e);
throw new LivyException(e);
}
stmtInfo = getStatementInfo(stmtInfo.id);
if (paragraphId != null) {
paragraphId2StmtProgressMap.put(paragraphId, (int) (stmtInfo.progress * 100));
}
}
if (appendSessionExpired || appendSessionDead) {
return appendSessionExpireDead(getResultFromStatementInfo(stmtInfo, displayAppInfo),
sessionExpired, sessionDead);
} else {
return getResultFromStatementInfo(stmtInfo, displayAppInfo);
}
} finally {
if (paragraphId != null) {
paragraphId2StmtProgressMap.remove(paragraphId);
paragraphsToCancel.remove(paragraphId);
}
}
}
private void cancel(int id, String paragraphId) {
if (livyVersion.isCancelSupported()) {
try {
LOGGER.info("Cancelling statement {}", id);
cancelStatement(id);
} catch (LivyException e) {
LOGGER.error("Fail to cancel statement {} for paragraph {}", id, paragraphId, e);
} finally {
paragraphsToCancel.remove(paragraphId);
}
} else {
LOGGER.warn("cancel is not supported for this version of livy: {}", livyVersion);
paragraphsToCancel.clear();
}
}
protected LivyVersion getLivyVersion() throws LivyException {
return new LivyVersion((LivyVersionResponse.fromJson(callRestAPI("/version", "GET")).version));
}
private boolean isSessionExpired() throws LivyException {
try {
getSessionInfo(sessionInfo.id);
return false;
} catch (SessionNotFoundException e) {
return true;
} catch (LivyException e) {
throw e;
}
}
private InterpreterResult appendSessionExpireDead(InterpreterResult result,
boolean sessionExpired,
boolean sessionDead) {
InterpreterResult result2 = new InterpreterResult(result.code());
if (sessionExpired) {
result2.add(InterpreterResult.Type.HTML,
"<font color=\"red\">Previous livy session is expired, new livy session is created. " +
"Paragraphs that depend on this paragraph need to be re-executed!</font>");
}
if (sessionDead) {
result2.add(InterpreterResult.Type.HTML,
"<font color=\"red\">Previous livy session is dead, new livy session is created. " +
"Paragraphs that depend on this paragraph need to be re-executed!</font>");
}
for (InterpreterResultMessage message : result.message()) {
result2.add(message.getType(), message.getData());
}
return result2;
}
private InterpreterResult getResultFromStatementInfo(StatementInfo stmtInfo,
boolean displayAppInfo) {
if (stmtInfo.output != null && stmtInfo.output.isError()) {
InterpreterResult result = new InterpreterResult(InterpreterResult.Code.ERROR);
StringBuilder sb = new StringBuilder();
sb.append(stmtInfo.output.evalue);
// in case evalue doesn't have newline char
if (!stmtInfo.output.evalue.contains("\n")) {
sb.append("\n");
}
if (stmtInfo.output.traceback != null) {
sb.append(StringUtils.join(stmtInfo.output.traceback));
}
result.add(sb.toString());
return result;
} else if (stmtInfo.isCancelled()) {
// corner case, output might be null if it is cancelled.
return new InterpreterResult(InterpreterResult.Code.ERROR, "Job is cancelled");
} else if (stmtInfo.output == null) {
// This case should never happen, just in case
return new InterpreterResult(InterpreterResult.Code.ERROR, "Empty output");
} else {
//TODO(zjffdu) support other types of data (like json, image and etc)
String result = stmtInfo.output.data.plainText;
// check table magic result first
if (stmtInfo.output.data.applicationLivyTableJson != null) {
StringBuilder outputBuilder = new StringBuilder();
boolean notFirstColumn = false;
for (Map header : stmtInfo.output.data.applicationLivyTableJson.headers) {
if (notFirstColumn) {
outputBuilder.append("\t");
}
outputBuilder.append(header.get("name"));
notFirstColumn = true;
}
outputBuilder.append("\n");
for (List<Object> row : stmtInfo.output.data.applicationLivyTableJson.records) {
outputBuilder.append(StringUtils.join(row, "\t"));
outputBuilder.append("\n");
}
return new InterpreterResult(InterpreterResult.Code.SUCCESS,
InterpreterResult.Type.TABLE, outputBuilder.toString());
} else if (stmtInfo.output.data.imagePng != null) {
return new InterpreterResult(InterpreterResult.Code.SUCCESS,
InterpreterResult.Type.IMG, stmtInfo.output.data.imagePng);
} else if (result != null) {
result = result.trim();
if (result.startsWith("<link")
|| result.startsWith("<script")
|| result.startsWith("<style")
|| result.startsWith("<div")) {
result = "%html " + result;
}
}
if (displayAppInfo) {
InterpreterResult interpreterResult = new InterpreterResult(InterpreterResult.Code.SUCCESS);
interpreterResult.add(result);
String appInfoHtml = "<hr/>Spark Application Id: " + sessionInfo.appId + "<br/>"
+ "Spark WebUI: <a href=\"" + sessionInfo.webUIAddress + "\">"
+ sessionInfo.webUIAddress + "</a>";
interpreterResult.add(InterpreterResult.Type.HTML, appInfoHtml);
return interpreterResult;
} else {
return new InterpreterResult(InterpreterResult.Code.SUCCESS, result);
}
}
}
private StatementInfo executeStatement(ExecuteRequest executeRequest)
throws LivyException {
return StatementInfo.fromJson(callRestAPI("/sessions/" + sessionInfo.id + "/statements", "POST",
executeRequest.toJson()));
}
private StatementInfo getStatementInfo(int statementId)
throws LivyException {
return StatementInfo.fromJson(
callRestAPI("/sessions/" + sessionInfo.id + "/statements/" + statementId, "GET"));
}
private void cancelStatement(int statementId) throws LivyException {
callRestAPI("/sessions/" + sessionInfo.id + "/statements/" + statementId + "/cancel", "POST");
}
private SSLContext getSslContext() {
try {
// Build truststore
String trustStoreFile = getProperty("zeppelin.livy.ssl.trustStore");
String trustStorePassword = getProperty("zeppelin.livy.ssl.trustStorePassword");
String trustStoreType = getProperty("zeppelin.livy.ssl.trustStoreType",
KeyStore.getDefaultType());
if (StringUtils.isBlank(trustStoreFile)) {
throw new RuntimeException("No zeppelin.livy.ssl.trustStore specified for livy ssl");
}
if (StringUtils.isBlank(trustStorePassword)) {
throw new RuntimeException("No zeppelin.livy.ssl.trustStorePassword specified " +
"for livy ssl");
}
KeyStore trustStore = getStore(trustStoreFile, trustStoreType, trustStorePassword);
SSLContextBuilder builder = SSLContexts.custom();
builder.loadTrustMaterial(trustStore);
// Build keystore
String keyStoreFile = getProperty("zeppelin.livy.ssl.keyStore");
String keyStorePassword = getProperty("zeppelin.livy.ssl.keyStorePassword");
String keyPassword = getProperty("zeppelin.livy.ssl.keyPassword", keyStorePassword);
String keyStoreType = getProperty("zeppelin.livy.ssl.keyStoreType",
KeyStore.getDefaultType());
if (StringUtils.isNotBlank(keyStoreFile)) {
KeyStore keyStore = getStore(keyStoreFile, keyStoreType, keyStorePassword);
builder.loadKeyMaterial(keyStore, keyPassword.toCharArray()).useTLS();
}
return builder.build();
} catch (Exception e) {
throw new RuntimeException("Failed to create SSL Context", e);
}
}
private KeyStore getStore(String file, String type, String password) {
try (FileInputStream inputStream = new FileInputStream(file)) {
KeyStore trustStore = KeyStore.getInstance(type);
trustStore.load(inputStream, password.toCharArray());
return trustStore;
} catch (Exception e) {
throw new RuntimeException("Failed to open keystore " + file, e);
}
}
private RestTemplate createRestTemplate() {
String keytabLocation = getProperty("zeppelin.livy.keytab");
String principal = getProperty("zeppelin.livy.principal");
boolean isSpnegoEnabled = StringUtils.isNotEmpty(keytabLocation) &&
StringUtils.isNotEmpty(principal);
HttpClient httpClient = null;
if (livyURL.startsWith("https:")) {
try {
SSLContext sslContext = getSslContext();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
HttpClientBuilder httpClientBuilder = HttpClients.custom().setSSLSocketFactory(csf);
if (isSpnegoEnabled) {
RequestConfig reqConfig = new RequestConfig() {
@Override
public boolean isAuthenticationEnabled() {
return true;
}
};
httpClientBuilder.setDefaultRequestConfig(reqConfig);
Credentials credentials = new Credentials() {
@Override
public String getPassword() {
return null;
}
@Override
public Principal getUserPrincipal() {
return null;
}
};
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, credentials);
httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
Registry<AuthSchemeProvider> authSchemeProviderRegistry =
RegistryBuilder.<AuthSchemeProvider>create()
.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
.build();
httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeProviderRegistry);
}
httpClient = httpClientBuilder.build();
} catch (Exception e) {
throw new RuntimeException("Failed to create SSL HttpClient", e);
}
}
RestTemplate restTemplate;
if (isSpnegoEnabled) {
if (httpClient == null) {
restTemplate = new KerberosRestTemplate(keytabLocation, principal);
} else {
restTemplate = new KerberosRestTemplate(keytabLocation, principal, httpClient);
}
} else {
if (httpClient == null) {
restTemplate = new RestTemplate();
} else {
restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
}
}
restTemplate.getMessageConverters().add(0,
new StringHttpMessageConverter(StandardCharsets.UTF_8));
return restTemplate;
}
private String callRestAPI(String targetURL, String method) throws LivyException {
return callRestAPI(targetURL, method, "");
}
private String callRestAPI(String targetURL, String method, String jsonData)
throws LivyException {
targetURL = livyURL + targetURL;
LOGGER.debug("Call rest api in {}, method: {}, jsonData: {}", targetURL, method, jsonData);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
headers.add("X-Requested-By", "zeppelin");
for (Map.Entry<String, String> entry : customHeaders.entrySet()) {
headers.add(entry.getKey(), entry.getValue());
}
ResponseEntity<String> response = null;
try {
if (method.equals("POST")) {
HttpEntity<String> entity = new HttpEntity<>(jsonData, headers);
response = restTemplate.exchange(targetURL, HttpMethod.POST, entity, String.class);
} else if (method.equals("GET")) {
HttpEntity<String> entity = new HttpEntity<>(headers);
response = restTemplate.exchange(targetURL, HttpMethod.GET, entity, String.class);
} else if (method.equals("DELETE")) {
HttpEntity<String> entity = new HttpEntity<>(headers);
response = restTemplate.exchange(targetURL, HttpMethod.DELETE, entity, String.class);
}
} catch (HttpClientErrorException e) {
response = new ResponseEntity(e.getResponseBodyAsString(), e.getStatusCode());
LOGGER.error(String.format("Error with %s StatusCode: %s",
response.getStatusCode().value(), e.getResponseBodyAsString()));
} catch (RestClientException e) {
// Exception happens when kerberos is enabled.
if (e.getCause() instanceof HttpClientErrorException) {
HttpClientErrorException cause = (HttpClientErrorException) e.getCause();
if (cause.getResponseBodyAsString().matches(SESSION_NOT_FOUND_PATTERN)) {
throw new SessionNotFoundException(cause.getResponseBodyAsString());
}
throw new LivyException(cause.getResponseBodyAsString() + "\n"
+ ExceptionUtils.getStackTrace(ExceptionUtils.getRootCause(e)));
}
if (e instanceof HttpServerErrorException) {
HttpServerErrorException errorException = (HttpServerErrorException) e;
String errorResponse = errorException.getResponseBodyAsString();
if (errorResponse.contains("Session is in state dead")) {
throw new SessionDeadException();
}
throw new LivyException(errorResponse, e);
}
throw new LivyException(e);
}
if (response == null) {
throw new LivyException("No http response returned");
}
LOGGER.debug("Get response, StatusCode: {}, responseBody: {}", response.getStatusCode(),
response.getBody());
if (response.getStatusCode().value() == 200
|| response.getStatusCode().value() == 201) {
return response.getBody();
} else if (response.getStatusCode().value() == 404) {
if (response.getBody().matches(SESSION_NOT_FOUND_PATTERN)) {
throw new SessionNotFoundException(response.getBody());
} else {
throw new APINotFoundException("No rest api found for " + targetURL +
", " + response.getStatusCode());
}
} else {
String responseString = response.getBody();
if (responseString.contains("CreateInteractiveRequest[\\\"master\\\"]")) {
return responseString;
}
throw new LivyException(String.format("Error with %s StatusCode: %s",
response.getStatusCode().value(), responseString));
}
}
private void closeSession(int sessionId) {
try {
callRestAPI("/sessions/" + sessionId, "DELETE");
} catch (Exception e) {
LOGGER.error(String.format("Error closing session for user with session ID: %s",
sessionId), e);
}
}
/*
* We create these POJO here to accommodate livy 0.3 which is not released yet. livy rest api has
* some changes from version to version. So we create these POJO in zeppelin side to accommodate
* incompatibility between versions. Later, when livy become more stable, we could just depend on
* livy client jar.
*/
private static class CreateSessionRequest {
public final String kind;
@SerializedName("proxyUser")
public final String user;
public final Map<String, String> conf;
CreateSessionRequest(String kind, String user, Map<String, String> conf) {
this.kind = kind;
this.user = user;
this.conf = conf;
}
public String toJson() {
return gson.toJson(this);
}
}
/**
*
*/
public static class SessionInfo {
public final int id;
public String appId;
public String webUIAddress;
public final String owner;
public final String proxyUser;
public final String state;
public final String kind;
public final Map<String, String> appInfo;
public final List<String> log;
public SessionInfo(int id, String appId, String owner, String proxyUser, String state,
String kind, Map<String, String> appInfo, List<String> log) {
this.id = id;
this.appId = appId;
this.owner = owner;
this.proxyUser = proxyUser;
this.state = state;
this.kind = kind;
this.appInfo = appInfo;
this.log = log;
}
public boolean isReady() {
return state.equals("idle");
}
public boolean isFinished() {
return state.equals("error") || state.equals("dead") || state.equals("success");
}
public static SessionInfo fromJson(String json) {
return gson.fromJson(json, SessionInfo.class);
}
}
private static class SessionLog {
public int id;
public int from;
public int size;
public List<String> log;
SessionLog() {
}
public static SessionLog fromJson(String json) {
return gson.fromJson(json, SessionLog.class);
}
}
static class ExecuteRequest {
public final String code;
public final String kind;
ExecuteRequest(String code, String kind) {
this.code = code;
this.kind = kind;
}
public String toJson() {
return gson.toJson(this);
}
}
private static class StatementInfo {
public Integer id;
public String state;
public double progress;
public StatementOutput output;
StatementInfo() {
}
public static StatementInfo fromJson(String json) {
String rightJson = "";
try {
gson.fromJson(json, StatementInfo.class);
rightJson = json;
} catch (Exception e) {
if (json.contains("\"traceback\":{}")) {
LOGGER.debug("traceback type mismatch, replacing the mismatching part ");
rightJson = json.replace("\"traceback\":{}", "\"traceback\":[]");
LOGGER.debug("new json string is {}", rightJson);
}
}
return gson.fromJson(rightJson, StatementInfo.class);
}
public boolean isAvailable() {
return state.equals("available") || state.equals("cancelled");
}
public boolean isCancelled() {
return state.equals("cancelled");
}
private static class StatementOutput {
public String status;
public String executionCount;
public Data data;
public String ename;
public String evalue;
public String[] traceback;
public TableMagic tableMagic;
public boolean isError() {
return status.equals("error");
}
public String toJson() {
return gson.toJson(this);
}
private static class Data {
@SerializedName("text/plain")
public String plainText;
@SerializedName("image/png")
public String imagePng;
@SerializedName("application/json")
public String applicationJson;
@SerializedName("application/vnd.livy.table.v1+json")
public TableMagic applicationLivyTableJson;
}
private static class TableMagic {
@SerializedName("headers")
List<Map> headers;
@SerializedName("data")
List<List> records;
}
}
}
static class CompletionRequest {
public final String code;
public final String kind;
public final int cursor;
CompletionRequest(String code, String kind, int cursor) {
this.code = code;
this.kind = kind;
this.cursor = cursor;
}
public String toJson() {
return gson.toJson(this);
}
}
static class CompletionResponse {
public final String[] candidates;
CompletionResponse(String[] candidates) {
this.candidates = candidates;
}
public static CompletionResponse fromJson(String json) {
return gson.fromJson(json, CompletionResponse.class);
}
}
private static class LivyVersionResponse {
public String url;
public String branch;
public String revision;
public String version;
public String date;
public String user;
public static LivyVersionResponse fromJson(String json) {
return gson.fromJson(json, LivyVersionResponse.class);
}
}
}
| UTF-8 | Java | 36,757 | java | BaseLivyInterpreter.java | Java | [
{
"context": ";\n this.owner = owner;\n this.proxyUser = proxyUser;\n this.state = state;\n this.kind = kind",
"end": 32917,
"score": 0.7526419758796692,
"start": 32908,
"tag": "USERNAME",
"value": "proxyUser"
}
] | 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.zeppelin.livy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.auth.AuthSchemeProvider;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.impl.auth.SPNegoSchemeFactory;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.security.kerberos.client.KerberosRestTemplate;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.SSLContext;
import org.apache.zeppelin.interpreter.Interpreter;
import org.apache.zeppelin.interpreter.InterpreterContext;
import org.apache.zeppelin.interpreter.InterpreterException;
import org.apache.zeppelin.interpreter.InterpreterResult;
import org.apache.zeppelin.interpreter.InterpreterResultMessage;
import org.apache.zeppelin.interpreter.InterpreterUtils;
import org.apache.zeppelin.interpreter.thrift.InterpreterCompletion;
/**
* Base class for livy interpreters.
*/
public abstract class BaseLivyInterpreter extends Interpreter {
protected static final Logger LOGGER = LoggerFactory.getLogger(BaseLivyInterpreter.class);
private static Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
private static final String SESSION_NOT_FOUND_PATTERN = "(.*)\"Session '\\d+' not found.\"(.*)";
protected volatile SessionInfo sessionInfo;
private String livyURL;
private int sessionCreationTimeout;
private int pullStatusInterval;
private int maxLogLines;
protected boolean displayAppInfo;
private boolean restartDeadSession;
protected LivyVersion livyVersion;
private RestTemplate restTemplate;
private Map<String, String> customHeaders = new HashMap<>();
// delegate to sharedInterpreter when it is available
protected LivySharedInterpreter sharedInterpreter;
Set<Object> paragraphsToCancel = Collections.newSetFromMap(
new ConcurrentHashMap<Object, Boolean>());
private ConcurrentHashMap<String, Integer> paragraphId2StmtProgressMap =
new ConcurrentHashMap<>();
public BaseLivyInterpreter(Properties property) {
super(property);
this.livyURL = property.getProperty("zeppelin.livy.url");
this.displayAppInfo = Boolean.parseBoolean(
property.getProperty("zeppelin.livy.displayAppInfo", "true"));
this.restartDeadSession = Boolean.parseBoolean(
property.getProperty("zeppelin.livy.restart_dead_session", "false"));
this.sessionCreationTimeout = Integer.parseInt(
property.getProperty("zeppelin.livy.session.create_timeout", 120 + ""));
this.pullStatusInterval = Integer.parseInt(
property.getProperty("zeppelin.livy.pull_status.interval.millis", 1000 + ""));
this.maxLogLines = Integer.parseInt(property.getProperty("zeppelin.livy.maxLogLines",
"1000"));
this.restTemplate = createRestTemplate();
if (!StringUtils.isBlank(property.getProperty("zeppelin.livy.http.headers"))) {
String[] headers = property.getProperty("zeppelin.livy.http.headers").split(";");
for (String header : headers) {
String[] splits = header.split(":", -1);
if (splits.length != 2) {
throw new RuntimeException("Invalid format of http headers: " + header +
", valid http header format is HEADER_NAME:HEADER_VALUE");
}
customHeaders.put(splits[0].trim(), envSubstitute(splits[1].trim()));
}
}
}
private String envSubstitute(String value) {
String newValue = new String(value);
Pattern pattern = Pattern.compile("\\$\\{(.*)\\}");
Matcher matcher = pattern.matcher(value);
while (matcher.find()) {
String env = matcher.group(1);
newValue = newValue.replace("${" + env + "}", System.getenv(env));
}
return newValue;
}
// only for testing
Map<String, String> getCustomHeaders() {
return customHeaders;
}
public abstract String getSessionKind();
@Override
public void open() throws InterpreterException {
try {
this.livyVersion = getLivyVersion();
if (this.livyVersion.isSharedSupported()) {
sharedInterpreter = getInterpreterInTheSameSessionByClassName(LivySharedInterpreter.class);
}
if (sharedInterpreter == null || !sharedInterpreter.isSupported()) {
initLivySession();
}
} catch (LivyException e) {
String msg = "Fail to create session, please check livy interpreter log and " +
"livy server log";
throw new InterpreterException(msg, e);
}
}
@Override
public void close() {
if (sharedInterpreter != null && sharedInterpreter.isSupported()) {
sharedInterpreter.close();
return;
}
if (sessionInfo != null) {
closeSession(sessionInfo.id);
// reset sessionInfo to null so that we won't close it twice.
sessionInfo = null;
}
}
protected void initLivySession() throws LivyException {
this.sessionInfo = createSession(getUserName(), getSessionKind());
if (displayAppInfo) {
if (sessionInfo.appId == null) {
// livy 0.2 don't return appId and sparkUiUrl in response so that we need to get it
// explicitly by ourselves.
sessionInfo.appId = extractAppId();
}
if (sessionInfo.appInfo == null ||
StringUtils.isEmpty(sessionInfo.appInfo.get("sparkUiUrl"))) {
sessionInfo.webUIAddress = extractWebUIAddress();
} else {
sessionInfo.webUIAddress = sessionInfo.appInfo.get("sparkUiUrl");
}
LOGGER.info("Create livy session successfully with sessionId: {}, appId: {}, webUI: {}",
sessionInfo.id, sessionInfo.appId, sessionInfo.webUIAddress);
} else {
LOGGER.info("Create livy session successfully with sessionId: {}", this.sessionInfo.id);
}
}
protected abstract String extractAppId() throws LivyException;
protected abstract String extractWebUIAddress() throws LivyException;
public SessionInfo getSessionInfo() {
if (sharedInterpreter != null && sharedInterpreter.isSupported()) {
return sharedInterpreter.getSessionInfo();
}
return sessionInfo;
}
public String getCodeType() {
if (getSessionKind().equalsIgnoreCase("pyspark3")) {
return "pyspark";
}
return getSessionKind();
}
@Override
public InterpreterResult interpret(String st, InterpreterContext context) {
if (sharedInterpreter != null && sharedInterpreter.isSupported()) {
return sharedInterpreter.interpret(st, getCodeType(), context);
}
if (StringUtils.isEmpty(st)) {
return new InterpreterResult(InterpreterResult.Code.SUCCESS, "");
}
try {
return interpret(st, null, context.getParagraphId(), this.displayAppInfo, true, true);
} catch (LivyException e) {
LOGGER.error("Fail to interpret: {}", st, e);
return new InterpreterResult(InterpreterResult.Code.ERROR,
InterpreterUtils.getMostRelevantMessage(e));
}
}
@Override
public List<InterpreterCompletion> completion(String buf, int cursor,
InterpreterContext interpreterContext) {
List<InterpreterCompletion> candidates = Collections.emptyList();
try {
candidates = callCompletion(new CompletionRequest(buf, getSessionKind(), cursor));
} catch (SessionNotFoundException e) {
LOGGER.warn("Livy session {} is expired. Will return empty list of candidates.",
getSessionInfo().id);
} catch (LivyException le) {
LOGGER.error("Failed to call code completions. Will return empty list of candidates", le);
}
return candidates;
}
private List<InterpreterCompletion> callCompletion(CompletionRequest req) throws LivyException {
List<InterpreterCompletion> candidates = new ArrayList<>();
try {
CompletionResponse resp = CompletionResponse.fromJson(
callRestAPI("/sessions/" + getSessionInfo().id + "/completion", "POST", req.toJson()));
for (String candidate : resp.candidates) {
candidates.add(new InterpreterCompletion(candidate, candidate, StringUtils.EMPTY));
}
} catch (APINotFoundException e) {
LOGGER.debug("completion api seems not to be available. (available from livy 0.5)", e);
}
return candidates;
}
@Override
public void cancel(InterpreterContext context) {
if (sharedInterpreter != null && sharedInterpreter.isSupported()) {
sharedInterpreter.cancel(context);
return;
}
paragraphsToCancel.add(context.getParagraphId());
LOGGER.info("Added paragraph {} for cancellation.", context.getParagraphId());
}
@Override
public FormType getFormType() {
return FormType.NATIVE;
}
@Override
public int getProgress(InterpreterContext context) {
if (sharedInterpreter != null && sharedInterpreter.isSupported()) {
return sharedInterpreter.getProgress(context);
}
if (livyVersion.isGetProgressSupported()) {
String paraId = context.getParagraphId();
Integer progress = paragraphId2StmtProgressMap.get(paraId);
return progress == null ? 0 : progress;
}
return 0;
}
private SessionInfo createSession(String user, String kind)
throws LivyException {
try {
Map<String, String> conf = new HashMap<>();
for (Map.Entry<Object, Object> entry : getProperties().entrySet()) {
if (entry.getKey().toString().startsWith("livy.spark.") &&
!entry.getValue().toString().isEmpty()) {
conf.put(entry.getKey().toString().substring(5), entry.getValue().toString());
}
}
CreateSessionRequest request = new CreateSessionRequest(kind,
user == null || user.equals("anonymous") ? null : user, conf);
SessionInfo sessionInfo = SessionInfo.fromJson(
callRestAPI("/sessions", "POST", request.toJson()));
long start = System.currentTimeMillis();
// pull the session status until it is idle or timeout
while (!sessionInfo.isReady()) {
if ((System.currentTimeMillis() - start) / 1000 > sessionCreationTimeout) {
String msg = "The creation of session " + sessionInfo.id + " is timeout within "
+ sessionCreationTimeout + " seconds, appId: " + sessionInfo.appId
+ ", log:\n" + StringUtils.join(getSessionLog(sessionInfo.id).log, "\n");
throw new LivyException(msg);
}
Thread.sleep(pullStatusInterval);
sessionInfo = getSessionInfo(sessionInfo.id);
LOGGER.info("Session {} is in state {}, appId {}", sessionInfo.id, sessionInfo.state,
sessionInfo.appId);
if (sessionInfo.isFinished()) {
String msg = "Session " + sessionInfo.id + " is finished, appId: " + sessionInfo.appId
+ ", log:\n" + StringUtils.join(getSessionLog(sessionInfo.id).log, "\n");
throw new LivyException(msg);
}
}
return sessionInfo;
} catch (Exception e) {
LOGGER.error("Error when creating livy session for user {}", user, e);
throw new LivyException(e);
}
}
private SessionInfo getSessionInfo(int sessionId) throws LivyException {
return SessionInfo.fromJson(callRestAPI("/sessions/" + sessionId, "GET"));
}
private SessionLog getSessionLog(int sessionId) throws LivyException {
return SessionLog.fromJson(callRestAPI("/sessions/" + sessionId + "/log?size=" + maxLogLines,
"GET"));
}
public InterpreterResult interpret(String code,
String paragraphId,
boolean displayAppInfo,
boolean appendSessionExpired,
boolean appendSessionDead) throws LivyException {
return interpret(code, sharedInterpreter.isSupported() ? getSessionKind() : null,
paragraphId, displayAppInfo, appendSessionExpired, appendSessionDead);
}
public InterpreterResult interpret(String code,
String codeType,
String paragraphId,
boolean displayAppInfo,
boolean appendSessionExpired,
boolean appendSessionDead) throws LivyException {
StatementInfo stmtInfo = null;
boolean sessionExpired = false;
boolean sessionDead = false;
try {
try {
stmtInfo = executeStatement(new ExecuteRequest(code, codeType));
} catch (SessionNotFoundException e) {
LOGGER.warn("Livy session {} is expired, new session will be created.", sessionInfo.id);
sessionExpired = true;
// we don't want to create multiple sessions because it is possible to have multiple thread
// to call this method, like LivySparkSQLInterpreter which use ParallelScheduler. So we need
// to check session status again in this sync block
synchronized (this) {
if (isSessionExpired()) {
initLivySession();
}
}
stmtInfo = executeStatement(new ExecuteRequest(code, codeType));
} catch (SessionDeadException e) {
sessionDead = true;
if (restartDeadSession) {
LOGGER.warn("Livy session {} is dead, new session will be created.", sessionInfo.id);
close();
try {
open();
} catch (InterpreterException ie) {
throw new LivyException("Fail to restart livy session", ie);
}
stmtInfo = executeStatement(new ExecuteRequest(code, codeType));
} else {
throw new LivyException("%html <font color=\"red\">Livy session is dead somehow, " +
"please check log to see why it is dead, and then restart livy interpreter</font>");
}
}
// pull the statement status
while (!stmtInfo.isAvailable()) {
if (paragraphId != null && paragraphsToCancel.contains(paragraphId)) {
cancel(stmtInfo.id, paragraphId);
return new InterpreterResult(InterpreterResult.Code.ERROR, "Job is cancelled");
}
try {
Thread.sleep(pullStatusInterval);
} catch (InterruptedException e) {
LOGGER.error("InterruptedException when pulling statement status.", e);
throw new LivyException(e);
}
stmtInfo = getStatementInfo(stmtInfo.id);
if (paragraphId != null) {
paragraphId2StmtProgressMap.put(paragraphId, (int) (stmtInfo.progress * 100));
}
}
if (appendSessionExpired || appendSessionDead) {
return appendSessionExpireDead(getResultFromStatementInfo(stmtInfo, displayAppInfo),
sessionExpired, sessionDead);
} else {
return getResultFromStatementInfo(stmtInfo, displayAppInfo);
}
} finally {
if (paragraphId != null) {
paragraphId2StmtProgressMap.remove(paragraphId);
paragraphsToCancel.remove(paragraphId);
}
}
}
private void cancel(int id, String paragraphId) {
if (livyVersion.isCancelSupported()) {
try {
LOGGER.info("Cancelling statement {}", id);
cancelStatement(id);
} catch (LivyException e) {
LOGGER.error("Fail to cancel statement {} for paragraph {}", id, paragraphId, e);
} finally {
paragraphsToCancel.remove(paragraphId);
}
} else {
LOGGER.warn("cancel is not supported for this version of livy: {}", livyVersion);
paragraphsToCancel.clear();
}
}
protected LivyVersion getLivyVersion() throws LivyException {
return new LivyVersion((LivyVersionResponse.fromJson(callRestAPI("/version", "GET")).version));
}
private boolean isSessionExpired() throws LivyException {
try {
getSessionInfo(sessionInfo.id);
return false;
} catch (SessionNotFoundException e) {
return true;
} catch (LivyException e) {
throw e;
}
}
private InterpreterResult appendSessionExpireDead(InterpreterResult result,
boolean sessionExpired,
boolean sessionDead) {
InterpreterResult result2 = new InterpreterResult(result.code());
if (sessionExpired) {
result2.add(InterpreterResult.Type.HTML,
"<font color=\"red\">Previous livy session is expired, new livy session is created. " +
"Paragraphs that depend on this paragraph need to be re-executed!</font>");
}
if (sessionDead) {
result2.add(InterpreterResult.Type.HTML,
"<font color=\"red\">Previous livy session is dead, new livy session is created. " +
"Paragraphs that depend on this paragraph need to be re-executed!</font>");
}
for (InterpreterResultMessage message : result.message()) {
result2.add(message.getType(), message.getData());
}
return result2;
}
private InterpreterResult getResultFromStatementInfo(StatementInfo stmtInfo,
boolean displayAppInfo) {
if (stmtInfo.output != null && stmtInfo.output.isError()) {
InterpreterResult result = new InterpreterResult(InterpreterResult.Code.ERROR);
StringBuilder sb = new StringBuilder();
sb.append(stmtInfo.output.evalue);
// in case evalue doesn't have newline char
if (!stmtInfo.output.evalue.contains("\n")) {
sb.append("\n");
}
if (stmtInfo.output.traceback != null) {
sb.append(StringUtils.join(stmtInfo.output.traceback));
}
result.add(sb.toString());
return result;
} else if (stmtInfo.isCancelled()) {
// corner case, output might be null if it is cancelled.
return new InterpreterResult(InterpreterResult.Code.ERROR, "Job is cancelled");
} else if (stmtInfo.output == null) {
// This case should never happen, just in case
return new InterpreterResult(InterpreterResult.Code.ERROR, "Empty output");
} else {
//TODO(zjffdu) support other types of data (like json, image and etc)
String result = stmtInfo.output.data.plainText;
// check table magic result first
if (stmtInfo.output.data.applicationLivyTableJson != null) {
StringBuilder outputBuilder = new StringBuilder();
boolean notFirstColumn = false;
for (Map header : stmtInfo.output.data.applicationLivyTableJson.headers) {
if (notFirstColumn) {
outputBuilder.append("\t");
}
outputBuilder.append(header.get("name"));
notFirstColumn = true;
}
outputBuilder.append("\n");
for (List<Object> row : stmtInfo.output.data.applicationLivyTableJson.records) {
outputBuilder.append(StringUtils.join(row, "\t"));
outputBuilder.append("\n");
}
return new InterpreterResult(InterpreterResult.Code.SUCCESS,
InterpreterResult.Type.TABLE, outputBuilder.toString());
} else if (stmtInfo.output.data.imagePng != null) {
return new InterpreterResult(InterpreterResult.Code.SUCCESS,
InterpreterResult.Type.IMG, stmtInfo.output.data.imagePng);
} else if (result != null) {
result = result.trim();
if (result.startsWith("<link")
|| result.startsWith("<script")
|| result.startsWith("<style")
|| result.startsWith("<div")) {
result = "%html " + result;
}
}
if (displayAppInfo) {
InterpreterResult interpreterResult = new InterpreterResult(InterpreterResult.Code.SUCCESS);
interpreterResult.add(result);
String appInfoHtml = "<hr/>Spark Application Id: " + sessionInfo.appId + "<br/>"
+ "Spark WebUI: <a href=\"" + sessionInfo.webUIAddress + "\">"
+ sessionInfo.webUIAddress + "</a>";
interpreterResult.add(InterpreterResult.Type.HTML, appInfoHtml);
return interpreterResult;
} else {
return new InterpreterResult(InterpreterResult.Code.SUCCESS, result);
}
}
}
private StatementInfo executeStatement(ExecuteRequest executeRequest)
throws LivyException {
return StatementInfo.fromJson(callRestAPI("/sessions/" + sessionInfo.id + "/statements", "POST",
executeRequest.toJson()));
}
private StatementInfo getStatementInfo(int statementId)
throws LivyException {
return StatementInfo.fromJson(
callRestAPI("/sessions/" + sessionInfo.id + "/statements/" + statementId, "GET"));
}
private void cancelStatement(int statementId) throws LivyException {
callRestAPI("/sessions/" + sessionInfo.id + "/statements/" + statementId + "/cancel", "POST");
}
private SSLContext getSslContext() {
try {
// Build truststore
String trustStoreFile = getProperty("zeppelin.livy.ssl.trustStore");
String trustStorePassword = getProperty("zeppelin.livy.ssl.trustStorePassword");
String trustStoreType = getProperty("zeppelin.livy.ssl.trustStoreType",
KeyStore.getDefaultType());
if (StringUtils.isBlank(trustStoreFile)) {
throw new RuntimeException("No zeppelin.livy.ssl.trustStore specified for livy ssl");
}
if (StringUtils.isBlank(trustStorePassword)) {
throw new RuntimeException("No zeppelin.livy.ssl.trustStorePassword specified " +
"for livy ssl");
}
KeyStore trustStore = getStore(trustStoreFile, trustStoreType, trustStorePassword);
SSLContextBuilder builder = SSLContexts.custom();
builder.loadTrustMaterial(trustStore);
// Build keystore
String keyStoreFile = getProperty("zeppelin.livy.ssl.keyStore");
String keyStorePassword = getProperty("zeppelin.livy.ssl.keyStorePassword");
String keyPassword = getProperty("zeppelin.livy.ssl.keyPassword", keyStorePassword);
String keyStoreType = getProperty("zeppelin.livy.ssl.keyStoreType",
KeyStore.getDefaultType());
if (StringUtils.isNotBlank(keyStoreFile)) {
KeyStore keyStore = getStore(keyStoreFile, keyStoreType, keyStorePassword);
builder.loadKeyMaterial(keyStore, keyPassword.toCharArray()).useTLS();
}
return builder.build();
} catch (Exception e) {
throw new RuntimeException("Failed to create SSL Context", e);
}
}
private KeyStore getStore(String file, String type, String password) {
try (FileInputStream inputStream = new FileInputStream(file)) {
KeyStore trustStore = KeyStore.getInstance(type);
trustStore.load(inputStream, password.toCharArray());
return trustStore;
} catch (Exception e) {
throw new RuntimeException("Failed to open keystore " + file, e);
}
}
private RestTemplate createRestTemplate() {
String keytabLocation = getProperty("zeppelin.livy.keytab");
String principal = getProperty("zeppelin.livy.principal");
boolean isSpnegoEnabled = StringUtils.isNotEmpty(keytabLocation) &&
StringUtils.isNotEmpty(principal);
HttpClient httpClient = null;
if (livyURL.startsWith("https:")) {
try {
SSLContext sslContext = getSslContext();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
HttpClientBuilder httpClientBuilder = HttpClients.custom().setSSLSocketFactory(csf);
if (isSpnegoEnabled) {
RequestConfig reqConfig = new RequestConfig() {
@Override
public boolean isAuthenticationEnabled() {
return true;
}
};
httpClientBuilder.setDefaultRequestConfig(reqConfig);
Credentials credentials = new Credentials() {
@Override
public String getPassword() {
return null;
}
@Override
public Principal getUserPrincipal() {
return null;
}
};
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, credentials);
httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
Registry<AuthSchemeProvider> authSchemeProviderRegistry =
RegistryBuilder.<AuthSchemeProvider>create()
.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
.build();
httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeProviderRegistry);
}
httpClient = httpClientBuilder.build();
} catch (Exception e) {
throw new RuntimeException("Failed to create SSL HttpClient", e);
}
}
RestTemplate restTemplate;
if (isSpnegoEnabled) {
if (httpClient == null) {
restTemplate = new KerberosRestTemplate(keytabLocation, principal);
} else {
restTemplate = new KerberosRestTemplate(keytabLocation, principal, httpClient);
}
} else {
if (httpClient == null) {
restTemplate = new RestTemplate();
} else {
restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
}
}
restTemplate.getMessageConverters().add(0,
new StringHttpMessageConverter(StandardCharsets.UTF_8));
return restTemplate;
}
private String callRestAPI(String targetURL, String method) throws LivyException {
return callRestAPI(targetURL, method, "");
}
private String callRestAPI(String targetURL, String method, String jsonData)
throws LivyException {
targetURL = livyURL + targetURL;
LOGGER.debug("Call rest api in {}, method: {}, jsonData: {}", targetURL, method, jsonData);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
headers.add("X-Requested-By", "zeppelin");
for (Map.Entry<String, String> entry : customHeaders.entrySet()) {
headers.add(entry.getKey(), entry.getValue());
}
ResponseEntity<String> response = null;
try {
if (method.equals("POST")) {
HttpEntity<String> entity = new HttpEntity<>(jsonData, headers);
response = restTemplate.exchange(targetURL, HttpMethod.POST, entity, String.class);
} else if (method.equals("GET")) {
HttpEntity<String> entity = new HttpEntity<>(headers);
response = restTemplate.exchange(targetURL, HttpMethod.GET, entity, String.class);
} else if (method.equals("DELETE")) {
HttpEntity<String> entity = new HttpEntity<>(headers);
response = restTemplate.exchange(targetURL, HttpMethod.DELETE, entity, String.class);
}
} catch (HttpClientErrorException e) {
response = new ResponseEntity(e.getResponseBodyAsString(), e.getStatusCode());
LOGGER.error(String.format("Error with %s StatusCode: %s",
response.getStatusCode().value(), e.getResponseBodyAsString()));
} catch (RestClientException e) {
// Exception happens when kerberos is enabled.
if (e.getCause() instanceof HttpClientErrorException) {
HttpClientErrorException cause = (HttpClientErrorException) e.getCause();
if (cause.getResponseBodyAsString().matches(SESSION_NOT_FOUND_PATTERN)) {
throw new SessionNotFoundException(cause.getResponseBodyAsString());
}
throw new LivyException(cause.getResponseBodyAsString() + "\n"
+ ExceptionUtils.getStackTrace(ExceptionUtils.getRootCause(e)));
}
if (e instanceof HttpServerErrorException) {
HttpServerErrorException errorException = (HttpServerErrorException) e;
String errorResponse = errorException.getResponseBodyAsString();
if (errorResponse.contains("Session is in state dead")) {
throw new SessionDeadException();
}
throw new LivyException(errorResponse, e);
}
throw new LivyException(e);
}
if (response == null) {
throw new LivyException("No http response returned");
}
LOGGER.debug("Get response, StatusCode: {}, responseBody: {}", response.getStatusCode(),
response.getBody());
if (response.getStatusCode().value() == 200
|| response.getStatusCode().value() == 201) {
return response.getBody();
} else if (response.getStatusCode().value() == 404) {
if (response.getBody().matches(SESSION_NOT_FOUND_PATTERN)) {
throw new SessionNotFoundException(response.getBody());
} else {
throw new APINotFoundException("No rest api found for " + targetURL +
", " + response.getStatusCode());
}
} else {
String responseString = response.getBody();
if (responseString.contains("CreateInteractiveRequest[\\\"master\\\"]")) {
return responseString;
}
throw new LivyException(String.format("Error with %s StatusCode: %s",
response.getStatusCode().value(), responseString));
}
}
private void closeSession(int sessionId) {
try {
callRestAPI("/sessions/" + sessionId, "DELETE");
} catch (Exception e) {
LOGGER.error(String.format("Error closing session for user with session ID: %s",
sessionId), e);
}
}
/*
* We create these POJO here to accommodate livy 0.3 which is not released yet. livy rest api has
* some changes from version to version. So we create these POJO in zeppelin side to accommodate
* incompatibility between versions. Later, when livy become more stable, we could just depend on
* livy client jar.
*/
private static class CreateSessionRequest {
public final String kind;
@SerializedName("proxyUser")
public final String user;
public final Map<String, String> conf;
CreateSessionRequest(String kind, String user, Map<String, String> conf) {
this.kind = kind;
this.user = user;
this.conf = conf;
}
public String toJson() {
return gson.toJson(this);
}
}
/**
*
*/
public static class SessionInfo {
public final int id;
public String appId;
public String webUIAddress;
public final String owner;
public final String proxyUser;
public final String state;
public final String kind;
public final Map<String, String> appInfo;
public final List<String> log;
public SessionInfo(int id, String appId, String owner, String proxyUser, String state,
String kind, Map<String, String> appInfo, List<String> log) {
this.id = id;
this.appId = appId;
this.owner = owner;
this.proxyUser = proxyUser;
this.state = state;
this.kind = kind;
this.appInfo = appInfo;
this.log = log;
}
public boolean isReady() {
return state.equals("idle");
}
public boolean isFinished() {
return state.equals("error") || state.equals("dead") || state.equals("success");
}
public static SessionInfo fromJson(String json) {
return gson.fromJson(json, SessionInfo.class);
}
}
private static class SessionLog {
public int id;
public int from;
public int size;
public List<String> log;
SessionLog() {
}
public static SessionLog fromJson(String json) {
return gson.fromJson(json, SessionLog.class);
}
}
static class ExecuteRequest {
public final String code;
public final String kind;
ExecuteRequest(String code, String kind) {
this.code = code;
this.kind = kind;
}
public String toJson() {
return gson.toJson(this);
}
}
private static class StatementInfo {
public Integer id;
public String state;
public double progress;
public StatementOutput output;
StatementInfo() {
}
public static StatementInfo fromJson(String json) {
String rightJson = "";
try {
gson.fromJson(json, StatementInfo.class);
rightJson = json;
} catch (Exception e) {
if (json.contains("\"traceback\":{}")) {
LOGGER.debug("traceback type mismatch, replacing the mismatching part ");
rightJson = json.replace("\"traceback\":{}", "\"traceback\":[]");
LOGGER.debug("new json string is {}", rightJson);
}
}
return gson.fromJson(rightJson, StatementInfo.class);
}
public boolean isAvailable() {
return state.equals("available") || state.equals("cancelled");
}
public boolean isCancelled() {
return state.equals("cancelled");
}
private static class StatementOutput {
public String status;
public String executionCount;
public Data data;
public String ename;
public String evalue;
public String[] traceback;
public TableMagic tableMagic;
public boolean isError() {
return status.equals("error");
}
public String toJson() {
return gson.toJson(this);
}
private static class Data {
@SerializedName("text/plain")
public String plainText;
@SerializedName("image/png")
public String imagePng;
@SerializedName("application/json")
public String applicationJson;
@SerializedName("application/vnd.livy.table.v1+json")
public TableMagic applicationLivyTableJson;
}
private static class TableMagic {
@SerializedName("headers")
List<Map> headers;
@SerializedName("data")
List<List> records;
}
}
}
static class CompletionRequest {
public final String code;
public final String kind;
public final int cursor;
CompletionRequest(String code, String kind, int cursor) {
this.code = code;
this.kind = kind;
this.cursor = cursor;
}
public String toJson() {
return gson.toJson(this);
}
}
static class CompletionResponse {
public final String[] candidates;
CompletionResponse(String[] candidates) {
this.candidates = candidates;
}
public static CompletionResponse fromJson(String json) {
return gson.fromJson(json, CompletionResponse.class);
}
}
private static class LivyVersionResponse {
public String url;
public String branch;
public String revision;
public String version;
public String date;
public String user;
public static LivyVersionResponse fromJson(String json) {
return gson.fromJson(json, LivyVersionResponse.class);
}
}
}
| 36,757 | 0.669151 | 0.667437 | 969 | 36.932922 | 28.54368 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.659443 | false | false | 2 |
fd2a921f68ebfb5047b05908a45878cbb557d3af | 28,449,863,427,845 | fb5c3640bfdf1895cface5eaaeeec5f7964505c9 | /WELLBROAD3/src/com/wellbroad/action/member/IdCheckAction.java | 61623ab9ad075e3c356945d580cd1eec78f6e6cb | [] | no_license | leeyoonah/WELLBROAD | https://github.com/leeyoonah/WELLBROAD | 69268aebfcda88ba084fcac1894e943d130d0c2f | 7d7d04e6f70be6de1362dc6c75bb89df5e7f1449 | refs/heads/master | 2020-03-08T13:03:11.038000 | 2018-05-05T10:54:32 | 2018-05-05T10:54:32 | 125,336,472 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wellbroad.action.member;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.wellbroad.action.controller.BaseAction;
import com.wellbroad.db.beans.member.MemberDAO;
public class IdCheckAction implements BaseAction{
@Override
public String requestPro(HttpServletRequest request, HttpServletResponse resonpse) throws Throwable {
//script.js->idCheck(id)->IdCheck.jsp?mem_id='nup'
String id=request.getParameter("id");
System.out.println("IdCheckAction 에 전달된 id=>"+id);//null
//DB접속
MemberDAO memMgr=new MemberDAO();
boolean check=memMgr.checkDuplicationId(id);
System.out.println("IdCheck.jsp의 check=>"+check);
request.setAttribute("id",id);
request.setAttribute("check", check);
return "IdCheck.jsp";
}
}
| UTF-8 | Java | 905 | java | IdCheckAction.java | Java | [] | null | [] | package com.wellbroad.action.member;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.wellbroad.action.controller.BaseAction;
import com.wellbroad.db.beans.member.MemberDAO;
public class IdCheckAction implements BaseAction{
@Override
public String requestPro(HttpServletRequest request, HttpServletResponse resonpse) throws Throwable {
//script.js->idCheck(id)->IdCheck.jsp?mem_id='nup'
String id=request.getParameter("id");
System.out.println("IdCheckAction 에 전달된 id=>"+id);//null
//DB접속
MemberDAO memMgr=new MemberDAO();
boolean check=memMgr.checkDuplicationId(id);
System.out.println("IdCheck.jsp의 check=>"+check);
request.setAttribute("id",id);
request.setAttribute("check", check);
return "IdCheck.jsp";
}
}
| 905 | 0.691358 | 0.691358 | 25 | 33.639999 | 26.176142 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.64 | false | false | 2 |
8decca43ce8101f9bad7de55f4272fc8a825053f | 34,428,457,899,438 | 400f90a3594490d64df396f3bf9bcad4d307d384 | /Servlets/Day2/Code/servlet-app-day2/src/main/java/ro/teamnet/zth/web/HttpServletLogin.java | 930fe5b02f9571eedb8da710eb8c9aafd72f2941 | [] | no_license | radufurculesteanu/JavaDocs | https://github.com/radufurculesteanu/JavaDocs | 0a04977afa3aed49298681add5b569be9cbf3cb6 | 3b69de2c22c1ca584d0983310b333a1821bd088d | refs/heads/master | 2020-12-02T22:47:51.033000 | 2017-07-19T14:16:46 | 2017-07-19T14:16:47 | 96,183,463 | 0 | 0 | null | true | 2017-07-04T06:32:44 | 2017-07-04T06:32:44 | 2017-06-23T12:36:41 | 2017-07-03T21:32:49 | 2,913 | 0 | 0 | 0 | null | null | null | package ro.teamnet.zth.web;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Created by Radu.Furculesteanu on 7/19/2017.
*/
public class HttpServletLogin extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String user = req.getParameter("username");
String password = req.getParameter("password");
Cookie[] cookies = req.getCookies();
if(user.equals("admin") && password.equals("admin"))
{
PrintWriter pw = resp.getWriter();
pw.write("Welcome back, " + user + "!");
for (Cookie cookie : cookies) {
pw.write(cookie.getName() + ":" + cookie.getValue());
}
}
else
{
HttpSession session = req.getSession();
session.setAttribute("user", user);
session.setAttribute("session",session);
RequestDispatcher dispatcher = req.getRequestDispatcher("/views/loginFail.jsp");
dispatcher.forward(req, resp);
}
}
}
| UTF-8 | Java | 1,222 | java | HttpServletLogin.java | Java | [
{
"context": "on;\nimport java.io.PrintWriter;\n\n/**\n * Created by Radu.Furculesteanu on 7/19/2017.\n */\npublic class HttpServletLogin e",
"end": 230,
"score": 0.9998343586921692,
"start": 212,
"tag": "NAME",
"value": "Radu.Furculesteanu"
},
{
"context": "ception {\n String... | null | [] | package ro.teamnet.zth.web;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Created by Radu.Furculesteanu on 7/19/2017.
*/
public class HttpServletLogin extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String user = req.getParameter("username");
String password = req.getParameter("password");
Cookie[] cookies = req.getCookies();
if(user.equals("admin") && password.equals("<PASSWORD>"))
{
PrintWriter pw = resp.getWriter();
pw.write("Welcome back, " + user + "!");
for (Cookie cookie : cookies) {
pw.write(cookie.getName() + ":" + cookie.getValue());
}
}
else
{
HttpSession session = req.getSession();
session.setAttribute("user", user);
session.setAttribute("session",session);
RequestDispatcher dispatcher = req.getRequestDispatcher("/views/loginFail.jsp");
dispatcher.forward(req, resp);
}
}
}
| 1,227 | 0.626023 | 0.620295 | 35 | 33.914288 | 26.498919 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.657143 | false | false | 2 |
5c380493ebb493163d7ce8ad4a5adfcdf7fbe2b5 | 39,281,770,937,097 | 716cacfffd2c9b48beab28481fc1cbcdb1d7e8c0 | /src/isoccer.java | db5b71131810b3b2889be52b81d399e2493c34e7 | [] | no_license | samuel0072/isoccer2 | https://github.com/samuel0072/isoccer2 | 7335db95b3c33c860e34ef4e742e27ffbb3cc37e | 7bd6025713770dd8dd4168ffe7a548b0a1910b9d | refs/heads/master | 2020-03-30T18:37:42.699000 | 2018-10-04T02:24:19 | 2018-10-04T02:24:19 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.IOException;
import java.util.Scanner;
import pessoa.funcionario.*;
import pessoa.*;
public class isoccer {
static Administrador adm = new Administrador (100100 );
static Scanner leitor = new Scanner ( System.in );
public static void main(String[] args) throws IOException {
while (!adm.entrar ()) {
limpar ();
}
//adm.carragarDados ();
System.out.println("\t\t------------------------------------------------\n\n\n\n\n\n\n\n\n\n\n\n\t\t------------------------------------------");
menu ();
}
//Auxiliares
public static void limpar() {
for (int i = 0; i < 100; i++) {
System.out.println ();
}
}
public static void menu() throws IOException {
int d = 0;
while (d <= 0 || d > 9) {
limpar ();
System.out.println ( "\t\t--------------------------Bem vindo-----------------------------" );
System.out.println ( "\t\t|O que deseja fazer? |" );
System.out.println ( "\t\t|1\tAdicionar um funcionario |" );
System.out.println ( "\t\t|2\tAdicionar um socio torcedor |" );
System.out.println ( "\t\t|3\tAdicionar um recurso |" );
System.out.println ( "\t\t|4\tGerir um funcionario |" );
System.out.println ( "\t\t|5\tGerir um recurso |" );
System.out.println ( "\t\t|6\tGerir um socio-torcedor |" );
System.out.println ( "\t\t|7\tGerar um relatorio geral |" );
System.out.println ( "\t\t|8\tGerar um relatorio mais especifico |" );
System.out.println ( "\t\t|9\tsair |" );
d = adm.lerNumero ();
System.out.println ( "\t\t-----------------------------------------------------------------" );
}
}
}
| UTF-8 | Java | 2,250 | java | isoccer.java | Java | [] | null | [] | import java.io.IOException;
import java.util.Scanner;
import pessoa.funcionario.*;
import pessoa.*;
public class isoccer {
static Administrador adm = new Administrador (100100 );
static Scanner leitor = new Scanner ( System.in );
public static void main(String[] args) throws IOException {
while (!adm.entrar ()) {
limpar ();
}
//adm.carragarDados ();
System.out.println("\t\t------------------------------------------------\n\n\n\n\n\n\n\n\n\n\n\n\t\t------------------------------------------");
menu ();
}
//Auxiliares
public static void limpar() {
for (int i = 0; i < 100; i++) {
System.out.println ();
}
}
public static void menu() throws IOException {
int d = 0;
while (d <= 0 || d > 9) {
limpar ();
System.out.println ( "\t\t--------------------------Bem vindo-----------------------------" );
System.out.println ( "\t\t|O que deseja fazer? |" );
System.out.println ( "\t\t|1\tAdicionar um funcionario |" );
System.out.println ( "\t\t|2\tAdicionar um socio torcedor |" );
System.out.println ( "\t\t|3\tAdicionar um recurso |" );
System.out.println ( "\t\t|4\tGerir um funcionario |" );
System.out.println ( "\t\t|5\tGerir um recurso |" );
System.out.println ( "\t\t|6\tGerir um socio-torcedor |" );
System.out.println ( "\t\t|7\tGerar um relatorio geral |" );
System.out.println ( "\t\t|8\tGerar um relatorio mais especifico |" );
System.out.println ( "\t\t|9\tsair |" );
d = adm.lerNumero ();
System.out.println ( "\t\t-----------------------------------------------------------------" );
}
}
}
| 2,250 | 0.380444 | 0.370667 | 49 | 43.918365 | 43.299545 | 153 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.020408 | false | false | 2 |
cd2c3a190fb19ada4d89fed29fefce3888910b84 | 39,651,138,106,413 | e36e319047057c72449cf3d59144119602a1846d | /src/main/java/com/example/demo/controllers/ItemController.java | 4e29691a3fa2cfd994c2b789e6ddf9be0a51333a | [] | no_license | gabrielifeliz/EcommerceSiteWeek7Challenge | https://github.com/gabrielifeliz/EcommerceSiteWeek7Challenge | f89b3fe47d82092687d022e400ef3973d2294efb | 45c041990032c33f495547b363c9b05eb6f13975 | refs/heads/master | 2020-03-23T00:23:49.342000 | 2018-07-16T05:37:14 | 2018-07-16T05:37:14 | 140,860,675 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.demo.controllers;
import com.cloudinary.utils.ObjectUtils;
import com.example.demo.configurations.CloudinaryConfig;
import com.example.demo.models.Item;
import com.example.demo.repositories.AppRoleRepository;
import com.example.demo.repositories.AppUserRepository;
import com.example.demo.repositories.ItemRepository;
import com.example.demo.services.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
@Controller
@RequestMapping("/items")
public class ItemController {
@Autowired
ItemRepository items;
@Autowired
ItemService myItems;
@Autowired
CloudinaryConfig cloudc;
@RequestMapping("/")
public String allitems(Model model)
{
model.addAttribute("items",items.findAllByListedOrderByPublicationDateDesc(true));
return "allitems";
}
@GetMapping("/additem")
public String addItem(Model model)
{
model.addAttribute("item", new Item());
return "newitem";
}
@PostMapping("/saveitem")
public String saveItem(@Valid @ModelAttribute("item") Item item,
BindingResult result, Authentication getDetails,
@RequestParam("file")MultipartFile file, Model model) {
if (result.hasErrors()) {
return "newitem";
}
if (item.getPrice() < 0.01) {
model.addAttribute("pricevalidation", "Please enter a number greater than zero");
return "newitem";
}
if (file.isEmpty()) {
item.setPublicationDate();
myItems.save(item, getDetails);
return "redirect:/items/";
}
try {
Map uploadResult = cloudc.upload(file.getBytes(),
ObjectUtils.asMap("resourcetype", "auto"));
item.setImage(uploadResult.get("url").toString());
item.setPublicationDate();
myItems.save(item, getDetails);
} catch (IOException e) {
e.printStackTrace();
return "redirect:/items/additem";
}
return "redirect:/items/myitems";
}
@RequestMapping("/myitems")
public String displayHome(Model model, Authentication authentication) {
model.addAttribute("items", myItems.orderMyItems(authentication));
return "myitems";
}
@RequestMapping("/update/{id}")
public String updatePost(@PathVariable("id") long id, Model model){
model.addAttribute("item", items.findById(id).get());
return "newitem";
}
@RequestMapping("/delete/{id}")
public String deletePost(@PathVariable("id") long id){
items.deleteById(id);
return "redirect:/items/";
}
@RequestMapping("/available/{id}")
public String availableItem(@PathVariable("id") long id){
Item item = items.findById(id).get();
item.setAvailable(true);
items.save(item);
return "redirect:/items/";
}
@RequestMapping("/sold/{id}")
public String soldItem(@PathVariable("id") long id){
Item item = items.findById(id).get();
item.setAvailable(false);
items.save(item);
return "redirect:/items/";
}
@RequestMapping("/listed/{id}")
public String listedItem(@PathVariable("id") long id){
Item item = items.findById(id).get();
item.setListed(true);
items.save(item);
return "redirect:/items/";
}
@RequestMapping("/delisted/{id}")
public String delistedItem(@PathVariable("id") long id){
Item item = items.findById(id).get();
item.setListed(false);
items.save(item);
return "redirect:/items/";
}
@RequestMapping("/buyitem/{id}")
public String buyItem(@PathVariable("id") long id){
Item item = items.findById(id).get();
final double TAX = 1.06;
item.setItemsSold(item.getItemsSold() + 1);
item.setTotalEarnedItem(item.getItemsSold() * item.getPrice() * TAX);
items.save(item);
return "redirect:/";
}
/*@PostConstruct
public void fillTables()
{
ItemTag c;
ArrayList<String> someColors = new ArrayList<>(Arrays
.asList("White", "Black", "Grey", "Yellow", "Red",
"Blue", "Green", "Brown", "Pink", "Orange", "Purple"));
for (String s: someColors) {
c = new ItemTag();
c.setTagName(s);
tags.save(c);
}
}*/
@RequestMapping("items/search/itemname")
public String searchByItemName(HttpServletRequest request, Model model)
{
//Get the search string from the result form
String searchString = request.getParameter("search");
model.addAttribute("search", searchString);
model.addAttribute("items",
items.findAllByItemNameContainingIgnoreCase(searchString));
return "allitems";
}
@RequestMapping("items/search/itemtag")
public String searchByItemTags(HttpServletRequest request, Model model)
{
//Get the search string from the result form
String searchString = request.getParameter("search");
model.addAttribute("search", searchString);
model.addAttribute("items",
items.findAllByItemTagsContainingIgnoreCase(searchString));
return "allitems";
}
}
| UTF-8 | Java | 5,980 | java | ItemController.java | Java | [] | null | [] | package com.example.demo.controllers;
import com.cloudinary.utils.ObjectUtils;
import com.example.demo.configurations.CloudinaryConfig;
import com.example.demo.models.Item;
import com.example.demo.repositories.AppRoleRepository;
import com.example.demo.repositories.AppUserRepository;
import com.example.demo.repositories.ItemRepository;
import com.example.demo.services.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
@Controller
@RequestMapping("/items")
public class ItemController {
@Autowired
ItemRepository items;
@Autowired
ItemService myItems;
@Autowired
CloudinaryConfig cloudc;
@RequestMapping("/")
public String allitems(Model model)
{
model.addAttribute("items",items.findAllByListedOrderByPublicationDateDesc(true));
return "allitems";
}
@GetMapping("/additem")
public String addItem(Model model)
{
model.addAttribute("item", new Item());
return "newitem";
}
@PostMapping("/saveitem")
public String saveItem(@Valid @ModelAttribute("item") Item item,
BindingResult result, Authentication getDetails,
@RequestParam("file")MultipartFile file, Model model) {
if (result.hasErrors()) {
return "newitem";
}
if (item.getPrice() < 0.01) {
model.addAttribute("pricevalidation", "Please enter a number greater than zero");
return "newitem";
}
if (file.isEmpty()) {
item.setPublicationDate();
myItems.save(item, getDetails);
return "redirect:/items/";
}
try {
Map uploadResult = cloudc.upload(file.getBytes(),
ObjectUtils.asMap("resourcetype", "auto"));
item.setImage(uploadResult.get("url").toString());
item.setPublicationDate();
myItems.save(item, getDetails);
} catch (IOException e) {
e.printStackTrace();
return "redirect:/items/additem";
}
return "redirect:/items/myitems";
}
@RequestMapping("/myitems")
public String displayHome(Model model, Authentication authentication) {
model.addAttribute("items", myItems.orderMyItems(authentication));
return "myitems";
}
@RequestMapping("/update/{id}")
public String updatePost(@PathVariable("id") long id, Model model){
model.addAttribute("item", items.findById(id).get());
return "newitem";
}
@RequestMapping("/delete/{id}")
public String deletePost(@PathVariable("id") long id){
items.deleteById(id);
return "redirect:/items/";
}
@RequestMapping("/available/{id}")
public String availableItem(@PathVariable("id") long id){
Item item = items.findById(id).get();
item.setAvailable(true);
items.save(item);
return "redirect:/items/";
}
@RequestMapping("/sold/{id}")
public String soldItem(@PathVariable("id") long id){
Item item = items.findById(id).get();
item.setAvailable(false);
items.save(item);
return "redirect:/items/";
}
@RequestMapping("/listed/{id}")
public String listedItem(@PathVariable("id") long id){
Item item = items.findById(id).get();
item.setListed(true);
items.save(item);
return "redirect:/items/";
}
@RequestMapping("/delisted/{id}")
public String delistedItem(@PathVariable("id") long id){
Item item = items.findById(id).get();
item.setListed(false);
items.save(item);
return "redirect:/items/";
}
@RequestMapping("/buyitem/{id}")
public String buyItem(@PathVariable("id") long id){
Item item = items.findById(id).get();
final double TAX = 1.06;
item.setItemsSold(item.getItemsSold() + 1);
item.setTotalEarnedItem(item.getItemsSold() * item.getPrice() * TAX);
items.save(item);
return "redirect:/";
}
/*@PostConstruct
public void fillTables()
{
ItemTag c;
ArrayList<String> someColors = new ArrayList<>(Arrays
.asList("White", "Black", "Grey", "Yellow", "Red",
"Blue", "Green", "Brown", "Pink", "Orange", "Purple"));
for (String s: someColors) {
c = new ItemTag();
c.setTagName(s);
tags.save(c);
}
}*/
@RequestMapping("items/search/itemname")
public String searchByItemName(HttpServletRequest request, Model model)
{
//Get the search string from the result form
String searchString = request.getParameter("search");
model.addAttribute("search", searchString);
model.addAttribute("items",
items.findAllByItemNameContainingIgnoreCase(searchString));
return "allitems";
}
@RequestMapping("items/search/itemtag")
public String searchByItemTags(HttpServletRequest request, Model model)
{
//Get the search string from the result form
String searchString = request.getParameter("search");
model.addAttribute("search", searchString);
model.addAttribute("items",
items.findAllByItemTagsContainingIgnoreCase(searchString));
return "allitems";
}
}
| 5,980 | 0.637291 | 0.63612 | 187 | 30.978609 | 23.365946 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.620321 | false | false | 2 |
d98c2570c22891eb37ffc9ce5bf6fd2fd0abf498 | 9,526,237,530,225 | 8ac41b94abeaa8494c7f628ec4a1a896a7a0cbb7 | /DaaS/src/test/java/com/mcd/gdw/test/daas/mapreduce/CostsMapper.java | 3d2d0749730bc1ee2a30c28b31713590dd0b5796 | [] | no_license | khajaasmath786/SparkItVarsityExamples | https://github.com/khajaasmath786/SparkItVarsityExamples | edae64cbe9520a00a6bfbfc090a390332f3d173d | d69479daa0dd6d8b1c85bbc775019c9bf9546edd | refs/heads/master | 2016-09-13T21:52:42.355000 | 2016-04-25T19:06:31 | 2016-04-25T19:06:31 | 57,067,941 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mcd.gdw.test.daas.mapreduce;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import com.mcd.gdw.daas.DaaSConstants;
public class CostsMapper extends Mapper<LongWritable, Text, Text, Text> {
private String inFileName;
private String[] parts;
private StringBuffer outputKey = new StringBuffer();
private StringBuffer outputValue = new StringBuffer();
private StringBuffer outputValuePrefix = new StringBuffer();
private Text mapKey = new Text();
private Text mapValue = new Text();
private DocumentBuilderFactory docFactory = null;
private DocumentBuilder docBuilder = null;
private InputSource xmlSource = null;
private Document doc = null;
private StringReader strReader = null;
private HashMap<String,String> orderKeyMap = new HashMap<String,String>();
private Element eleRoot;
private Element eleNode;
private Element eleEvent;
private Element eleTrxSale;
private Element eleOrder;
private String posBusnDt;
private String mcdGbalLcatIdNu;
private String posOrdKey;
private String posTrnStrtTs;
private String posTotNetTrnAm;
private int seqNum;
private StringBuffer childItems = new StringBuffer();
@Override
public void setup(Context context) {
try {
inFileName = ((FileSplit) context.getInputSplit()).getPath().getName();
docFactory = DocumentBuilderFactory.newInstance();
docBuilder = docFactory.newDocumentBuilder();
} catch (Exception ex) {
ex.printStackTrace(System.err);
System.exit(8);
}
}
@Override
public void map(LongWritable key, Text value,Context context) throws IOException, InterruptedException {
parts = value.toString().split("\t");
if ( inFileName.toUpperCase().contains("COST") ) {
getCosts(context);
} else {
mcdGbalLcatIdNu = parts[DaaSConstants.XML_REC_MCD_GBAL_LCAT_ID_NU_POS];
posBusnDt = parts[DaaSConstants.XML_REC_POS_BUSN_DT_POS].substring(0, 4) + "-" + parts[DaaSConstants.XML_REC_POS_BUSN_DT_POS].substring(4, 6) + "-" + parts[DaaSConstants.XML_REC_POS_BUSN_DT_POS].substring(6, 8);
if ( parts[DaaSConstants.XML_REC_FILE_TYPE_POS].equalsIgnoreCase("STLD") ) {
getTldData(parts[DaaSConstants.XML_REC_XML_TEXT_POS],context);
}
}
}
private void getCosts(Context context) {
try {
outputKey.setLength(0);
outputKey.append(parts[2]);
outputKey.append(parts[3]);
//outputKey.append("201203");
outputKey.append(parts[1]);
outputValue.setLength(0);
outputValue.append("C");
outputValue.append(parts[4]);
outputValue.append("|");
//outputValue.append(parts[5]);
//outputValue.append("\t");
outputValue.append(parts[6]);
outputValue.append("\t");
outputValue.append(parts[7]);
outputValue.append("\t");
outputValue.append(parts[8]);
outputValue.append("\t");
outputValue.append(parts[9]);
mapKey.clear();
mapKey.set(outputKey.toString());
mapValue.clear();
mapValue.set(outputValue.toString());
context.write(mapKey, mapValue);
context.getCounter("DaaS","Costs").increment(1);
} catch (Exception ex) {
ex.printStackTrace(System.err);
System.exit(8);
}
}
private void getTldData(String xmlText
,Context context) {
try {
try {
strReader = new StringReader(xmlText);
xmlSource = new InputSource(strReader);
doc = docBuilder.parse(xmlSource);
} catch (Exception ex1) {
strReader = new StringReader(xmlText.replaceAll("" , "_"));
xmlSource = new InputSource(strReader);
doc = docBuilder.parse(xmlSource);
}
orderKeyMap.clear();
eleRoot = (Element) doc.getFirstChild();
if ( eleRoot.getNodeName().equals("TLD") ) {
processNode(eleRoot.getChildNodes(),context);
}
} catch (Exception ex) {
ex.printStackTrace(System.err);
System.exit(8);
}
}
private void processNode(NodeList nlNode
,Context context) {
if (nlNode != null && nlNode.getLength() > 0 ) {
for (int idxNode=0; idxNode < nlNode.getLength(); idxNode++ ) {
if ( nlNode.item(idxNode).getNodeType() == Node.ELEMENT_NODE ) {
eleNode = (Element)nlNode.item(idxNode);
if ( eleNode.getNodeName().equals("Node") ) {
processEvent(eleNode.getChildNodes(),context);
}
}
}
}
}
private void processEvent(NodeList nlEvent
,Context context) {
if (nlEvent != null && nlEvent.getLength() > 0 ) {
for (int idxEvent=0; idxEvent < nlEvent.getLength(); idxEvent++ ) {
if ( nlEvent.item(idxEvent).getNodeType() == Node.ELEMENT_NODE ) {
eleEvent = (Element)nlEvent.item(idxEvent);
if ( eleEvent.getNodeName().equals("Event") &&
eleEvent.getAttribute("Type").equals("TRX_Sale") ) {
processTrxSale(eleEvent.getChildNodes(),context);
}
}
}
}
}
private void processTrxSale(NodeList nlTrxSale
,Context context) {
if (nlTrxSale != null && nlTrxSale.getLength() > 0 ) {
for (int idxTrxSale=0; idxTrxSale < nlTrxSale.getLength(); idxTrxSale++ ) {
if ( nlTrxSale.item(idxTrxSale).getNodeType() == Node.ELEMENT_NODE ) {
eleTrxSale = (Element)nlTrxSale.item(idxTrxSale);
if ( eleTrxSale.getAttribute("status").equals("Paid") ) {
processOrder(eleTrxSale.getChildNodes(),context);
}
}
}
}
}
private void processOrder(NodeList nlOrder
,Context context) {
try {
if (nlOrder != null && nlOrder.getLength() > 0 ) {
for (int idxOrder=0; idxOrder < nlOrder.getLength(); idxOrder++ ) {
if ( nlOrder.item(idxOrder).getNodeType() == Node.ELEMENT_NODE ) {
eleOrder = (Element)nlOrder.item(idxOrder);
posOrdKey = getValue(eleOrder,"key");
if ( !orderKeyMap.containsKey(posOrdKey) ) {
orderKeyMap.put(posOrdKey, "");
posTrnStrtTs = formatAsTs(getValue(eleOrder,"Timestamp"));
posTotNetTrnAm = getValue(eleOrder,"totalAmount");
outputKey.setLength(0);
outputKey.append(posBusnDt.substring(0, 4));
outputKey.append(posBusnDt.substring(5, 7));
outputKey.append(mcdGbalLcatIdNu);
outputValuePrefix.setLength(0);
outputValuePrefix.append("T");
outputValuePrefix.append(posBusnDt);
outputValuePrefix.append("\t");
outputValuePrefix.append(posOrdKey);
outputValuePrefix.append("\t");
outputValuePrefix.append(posTrnStrtTs);
outputValuePrefix.append("\t");
outputValuePrefix.append(posTotNetTrnAm);
mapKey.clear();
mapKey.set(outputKey.toString());
context.getCounter("DaaS","TLD TRANS").increment(1);
seqNum = 0;
procesItem(eleOrder.getChildNodes(),context);
}
}
}
}
} catch (Exception ex) {
ex.printStackTrace(System.err);
System.exit(8);
}
}
private void procesItem(NodeList nlItem
,Context context) {
Element eleItem;
int qty;
String type;
try {
if (nlItem != null && nlItem.getLength() > 0 ) {
for (int idxItem=0; idxItem < nlItem.getLength(); idxItem++ ) {
if ( nlItem.item(idxItem).getNodeType() == Node.ELEMENT_NODE ) {
eleItem = (Element)nlItem.item(idxItem);
if ( eleItem.getNodeName().equals("Item") ) {
try {
qty = Integer.parseInt(getValue(eleItem,"qty"));
} catch (Exception ex1) {
qty = 0;
}
type = getValue(eleItem,"type");
if ( qty > 0 && (type.equalsIgnoreCase("VALUE_MEAL") || type.equalsIgnoreCase("PRODUCT")) ) {
if ( getValue(eleItem,"level").equals("0") ) {
childItems.setLength(0);
} else {
childItems.append(getValue(eleItem,"code"));
childItems.append("~");
}
seqNum++;
procesItem(eleItem.getChildNodes(),context);
outputValue.setLength(0);
outputValue.append(outputValuePrefix);
outputValue.append("\t");
outputValue.append(seqNum);
outputValue.append("\t");
outputValue.append(getValue(eleItem,"code"));
outputValue.append("\t");
outputValue.append(getValue(eleItem,"description"));
outputValue.append("\t");
outputValue.append(getValue(eleItem,"level"));
outputValue.append("\t");
outputValue.append(getValue(eleItem,"id"));
outputValue.append("\t");
outputValue.append(qty);
outputValue.append("\t");
outputValue.append(getValue(eleItem,"totalPrice"));
outputValue.append("\t");
if ( getValue(eleItem,"level").equals("0") ) {
outputValue.append(childItems);
}
mapValue.clear();
mapValue.set(outputValue.toString());
context.write(mapKey, mapValue);
context.getCounter("DaaS","TLD ITEM").increment(1);
}
}
}
}
}
} catch (Exception ex) {
ex.printStackTrace(System.err);
System.exit(8);
}
}
private String formatAsTs(String in) {
String retTs = "";
if ( in.length() >= 14 ) {
retTs = in.substring(0, 4) + "-" + in.substring(4, 6) + "-" + in.substring(6, 8) + " " + in.substring(8, 10) + ":" + in.substring(10, 12) + ":" + in.substring(12, 14);
} else {
retTs = "0000-00-00 00:00:00";
}
return(retTs);
}
private String getValue(Element ele
,String attribute) {
String retValue = "";
try {
retValue = ele.getAttribute(attribute);
} catch (Exception ex) {
}
return(retValue.trim());
}
}
| UTF-8 | Java | 10,333 | java | CostsMapper.java | Java | [
{
"context": "tputKey.append(parts[3]);\r\n\t\t\t//outputKey.append(\"201203\");\r\n\t\t\toutputKey.append(parts[1]);\r\n\t\t\t\r\n\t\t\toutpu",
"end": 2906,
"score": 0.9959015846252441,
"start": 2900,
"tag": "KEY",
"value": "201203"
},
{
"context": "BusnDt.substring(5, 7));\r\n\t\t\... | null | [] | package com.mcd.gdw.test.daas.mapreduce;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import com.mcd.gdw.daas.DaaSConstants;
public class CostsMapper extends Mapper<LongWritable, Text, Text, Text> {
private String inFileName;
private String[] parts;
private StringBuffer outputKey = new StringBuffer();
private StringBuffer outputValue = new StringBuffer();
private StringBuffer outputValuePrefix = new StringBuffer();
private Text mapKey = new Text();
private Text mapValue = new Text();
private DocumentBuilderFactory docFactory = null;
private DocumentBuilder docBuilder = null;
private InputSource xmlSource = null;
private Document doc = null;
private StringReader strReader = null;
private HashMap<String,String> orderKeyMap = new HashMap<String,String>();
private Element eleRoot;
private Element eleNode;
private Element eleEvent;
private Element eleTrxSale;
private Element eleOrder;
private String posBusnDt;
private String mcdGbalLcatIdNu;
private String posOrdKey;
private String posTrnStrtTs;
private String posTotNetTrnAm;
private int seqNum;
private StringBuffer childItems = new StringBuffer();
@Override
public void setup(Context context) {
try {
inFileName = ((FileSplit) context.getInputSplit()).getPath().getName();
docFactory = DocumentBuilderFactory.newInstance();
docBuilder = docFactory.newDocumentBuilder();
} catch (Exception ex) {
ex.printStackTrace(System.err);
System.exit(8);
}
}
@Override
public void map(LongWritable key, Text value,Context context) throws IOException, InterruptedException {
parts = value.toString().split("\t");
if ( inFileName.toUpperCase().contains("COST") ) {
getCosts(context);
} else {
mcdGbalLcatIdNu = parts[DaaSConstants.XML_REC_MCD_GBAL_LCAT_ID_NU_POS];
posBusnDt = parts[DaaSConstants.XML_REC_POS_BUSN_DT_POS].substring(0, 4) + "-" + parts[DaaSConstants.XML_REC_POS_BUSN_DT_POS].substring(4, 6) + "-" + parts[DaaSConstants.XML_REC_POS_BUSN_DT_POS].substring(6, 8);
if ( parts[DaaSConstants.XML_REC_FILE_TYPE_POS].equalsIgnoreCase("STLD") ) {
getTldData(parts[DaaSConstants.XML_REC_XML_TEXT_POS],context);
}
}
}
private void getCosts(Context context) {
try {
outputKey.setLength(0);
outputKey.append(parts[2]);
outputKey.append(parts[3]);
//outputKey.append("201203");
outputKey.append(parts[1]);
outputValue.setLength(0);
outputValue.append("C");
outputValue.append(parts[4]);
outputValue.append("|");
//outputValue.append(parts[5]);
//outputValue.append("\t");
outputValue.append(parts[6]);
outputValue.append("\t");
outputValue.append(parts[7]);
outputValue.append("\t");
outputValue.append(parts[8]);
outputValue.append("\t");
outputValue.append(parts[9]);
mapKey.clear();
mapKey.set(outputKey.toString());
mapValue.clear();
mapValue.set(outputValue.toString());
context.write(mapKey, mapValue);
context.getCounter("DaaS","Costs").increment(1);
} catch (Exception ex) {
ex.printStackTrace(System.err);
System.exit(8);
}
}
private void getTldData(String xmlText
,Context context) {
try {
try {
strReader = new StringReader(xmlText);
xmlSource = new InputSource(strReader);
doc = docBuilder.parse(xmlSource);
} catch (Exception ex1) {
strReader = new StringReader(xmlText.replaceAll("" , "_"));
xmlSource = new InputSource(strReader);
doc = docBuilder.parse(xmlSource);
}
orderKeyMap.clear();
eleRoot = (Element) doc.getFirstChild();
if ( eleRoot.getNodeName().equals("TLD") ) {
processNode(eleRoot.getChildNodes(),context);
}
} catch (Exception ex) {
ex.printStackTrace(System.err);
System.exit(8);
}
}
private void processNode(NodeList nlNode
,Context context) {
if (nlNode != null && nlNode.getLength() > 0 ) {
for (int idxNode=0; idxNode < nlNode.getLength(); idxNode++ ) {
if ( nlNode.item(idxNode).getNodeType() == Node.ELEMENT_NODE ) {
eleNode = (Element)nlNode.item(idxNode);
if ( eleNode.getNodeName().equals("Node") ) {
processEvent(eleNode.getChildNodes(),context);
}
}
}
}
}
private void processEvent(NodeList nlEvent
,Context context) {
if (nlEvent != null && nlEvent.getLength() > 0 ) {
for (int idxEvent=0; idxEvent < nlEvent.getLength(); idxEvent++ ) {
if ( nlEvent.item(idxEvent).getNodeType() == Node.ELEMENT_NODE ) {
eleEvent = (Element)nlEvent.item(idxEvent);
if ( eleEvent.getNodeName().equals("Event") &&
eleEvent.getAttribute("Type").equals("TRX_Sale") ) {
processTrxSale(eleEvent.getChildNodes(),context);
}
}
}
}
}
private void processTrxSale(NodeList nlTrxSale
,Context context) {
if (nlTrxSale != null && nlTrxSale.getLength() > 0 ) {
for (int idxTrxSale=0; idxTrxSale < nlTrxSale.getLength(); idxTrxSale++ ) {
if ( nlTrxSale.item(idxTrxSale).getNodeType() == Node.ELEMENT_NODE ) {
eleTrxSale = (Element)nlTrxSale.item(idxTrxSale);
if ( eleTrxSale.getAttribute("status").equals("Paid") ) {
processOrder(eleTrxSale.getChildNodes(),context);
}
}
}
}
}
private void processOrder(NodeList nlOrder
,Context context) {
try {
if (nlOrder != null && nlOrder.getLength() > 0 ) {
for (int idxOrder=0; idxOrder < nlOrder.getLength(); idxOrder++ ) {
if ( nlOrder.item(idxOrder).getNodeType() == Node.ELEMENT_NODE ) {
eleOrder = (Element)nlOrder.item(idxOrder);
posOrdKey = getValue(eleOrder,"key");
if ( !orderKeyMap.containsKey(posOrdKey) ) {
orderKeyMap.put(posOrdKey, "");
posTrnStrtTs = formatAsTs(getValue(eleOrder,"Timestamp"));
posTotNetTrnAm = getValue(eleOrder,"totalAmount");
outputKey.setLength(0);
outputKey.append(posBusnDt.substring(0, 4));
outputKey.append(posBusnDt.substring(5, 7));
outputKey.append(mcdGbalLcatIdNu);
outputValuePrefix.setLength(0);
outputValuePrefix.append("T");
outputValuePrefix.append(posBusnDt);
outputValuePrefix.append("\t");
outputValuePrefix.append(posOrdKey);
outputValuePrefix.append("\t");
outputValuePrefix.append(posTrnStrtTs);
outputValuePrefix.append("\t");
outputValuePrefix.append(posTotNetTrnAm);
mapKey.clear();
mapKey.set(outputKey.toString());
context.getCounter("DaaS","TLD TRANS").increment(1);
seqNum = 0;
procesItem(eleOrder.getChildNodes(),context);
}
}
}
}
} catch (Exception ex) {
ex.printStackTrace(System.err);
System.exit(8);
}
}
private void procesItem(NodeList nlItem
,Context context) {
Element eleItem;
int qty;
String type;
try {
if (nlItem != null && nlItem.getLength() > 0 ) {
for (int idxItem=0; idxItem < nlItem.getLength(); idxItem++ ) {
if ( nlItem.item(idxItem).getNodeType() == Node.ELEMENT_NODE ) {
eleItem = (Element)nlItem.item(idxItem);
if ( eleItem.getNodeName().equals("Item") ) {
try {
qty = Integer.parseInt(getValue(eleItem,"qty"));
} catch (Exception ex1) {
qty = 0;
}
type = getValue(eleItem,"type");
if ( qty > 0 && (type.equalsIgnoreCase("VALUE_MEAL") || type.equalsIgnoreCase("PRODUCT")) ) {
if ( getValue(eleItem,"level").equals("0") ) {
childItems.setLength(0);
} else {
childItems.append(getValue(eleItem,"code"));
childItems.append("~");
}
seqNum++;
procesItem(eleItem.getChildNodes(),context);
outputValue.setLength(0);
outputValue.append(outputValuePrefix);
outputValue.append("\t");
outputValue.append(seqNum);
outputValue.append("\t");
outputValue.append(getValue(eleItem,"code"));
outputValue.append("\t");
outputValue.append(getValue(eleItem,"description"));
outputValue.append("\t");
outputValue.append(getValue(eleItem,"level"));
outputValue.append("\t");
outputValue.append(getValue(eleItem,"id"));
outputValue.append("\t");
outputValue.append(qty);
outputValue.append("\t");
outputValue.append(getValue(eleItem,"totalPrice"));
outputValue.append("\t");
if ( getValue(eleItem,"level").equals("0") ) {
outputValue.append(childItems);
}
mapValue.clear();
mapValue.set(outputValue.toString());
context.write(mapKey, mapValue);
context.getCounter("DaaS","TLD ITEM").increment(1);
}
}
}
}
}
} catch (Exception ex) {
ex.printStackTrace(System.err);
System.exit(8);
}
}
private String formatAsTs(String in) {
String retTs = "";
if ( in.length() >= 14 ) {
retTs = in.substring(0, 4) + "-" + in.substring(4, 6) + "-" + in.substring(6, 8) + " " + in.substring(8, 10) + ":" + in.substring(10, 12) + ":" + in.substring(12, 14);
} else {
retTs = "0000-00-00 00:00:00";
}
return(retTs);
}
private String getValue(Element ele
,String attribute) {
String retValue = "";
try {
retValue = ele.getAttribute(attribute);
} catch (Exception ex) {
}
return(retValue.trim());
}
}
| 10,333 | 0.616471 | 0.607374 | 360 | 26.702778 | 25.537945 | 214 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.661111 | false | false | 2 |
6f1da7ea4adf4ac4d462a1e75c12ccf2d2d3770f | 37,323,265,838,671 | db823d4b4cca5a375a7c9acc0c763f1f7e16c762 | /HealthCare_Internet/src/Business/Patient/PatientTreatment.java | 31bc7d641982618763a38fb45ca220f2d20f31fc | [] | no_license | janhvi-c/Application-Engineering-And-Development-Project | https://github.com/janhvi-c/Application-Engineering-And-Development-Project | e6118836434c8b9cdd6e2a48f1076b967fe04ad8 | ed2c6697bf1c502e7dfbe0e9de94e366ea03d610 | refs/heads/master | 2016-08-10T19:30:24.578000 | 2016-02-03T14:38:52 | 2016-02-03T14:38:52 | 51,005,580 | 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 Business.Patient;
import java.util.ArrayList;
/**
*
* @author Janhvi
*/
public class PatientTreatment {
private String PatientDiagnosis;
private ArrayList<Test> testArray;
private ArrayList<PatientIllness> patientIllnesses;
private ArrayList<PrescribedDrug> prescribedDrug;
public PatientTreatment(){
testArray = new ArrayList<>();
patientIllnesses = new ArrayList<>();
prescribedDrug = new ArrayList<>();
}
public ArrayList<PrescribedDrug> getPrescribedDrug() {
return prescribedDrug;
}
public void setPrescribedDrug(ArrayList<PrescribedDrug> prescribedDrug) {
this.prescribedDrug = prescribedDrug;
}
public String getPatientDiagnosis() {
return PatientDiagnosis;
}
public void setPatientDiagnosis(String PatientDiagnosis) {
this.PatientDiagnosis = PatientDiagnosis;
}
public ArrayList<PatientIllness> getPatientIllnesses() {
return patientIllnesses;
}
public void setPatientIllnesses(ArrayList<PatientIllness> patientIllnesses) {
this.patientIllnesses = patientIllnesses;
}
public ArrayList<Test> getTestArray() {
return testArray;
}
public void setTestArray(ArrayList<Test> testArray) {
this.testArray = testArray;
}
public Test addNewTest(){
Test test = new Test();
testArray.add(test);
return test;
}
public PatientIllness addNewIllness(){
PatientIllness patientIllness = new PatientIllness();
patientIllnesses.add(patientIllness);
return patientIllness;
}
public PrescribedDrug addNewPrescribedDrug(){
PrescribedDrug pd = new PrescribedDrug();
prescribedDrug.add(pd);
return pd;
}
}
| UTF-8 | Java | 2,086 | java | PatientTreatment.java | Java | [
{
"context": "import java.util.ArrayList;\r\n\r\n/**\r\n *\r\n * @author Janhvi\r\n */\r\npublic class PatientTreatment {\r\n \r\n pr",
"end": 278,
"score": 0.9571429491043091,
"start": 272,
"tag": "NAME",
"value": "Janhvi"
}
] | 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 Business.Patient;
import java.util.ArrayList;
/**
*
* @author Janhvi
*/
public class PatientTreatment {
private String PatientDiagnosis;
private ArrayList<Test> testArray;
private ArrayList<PatientIllness> patientIllnesses;
private ArrayList<PrescribedDrug> prescribedDrug;
public PatientTreatment(){
testArray = new ArrayList<>();
patientIllnesses = new ArrayList<>();
prescribedDrug = new ArrayList<>();
}
public ArrayList<PrescribedDrug> getPrescribedDrug() {
return prescribedDrug;
}
public void setPrescribedDrug(ArrayList<PrescribedDrug> prescribedDrug) {
this.prescribedDrug = prescribedDrug;
}
public String getPatientDiagnosis() {
return PatientDiagnosis;
}
public void setPatientDiagnosis(String PatientDiagnosis) {
this.PatientDiagnosis = PatientDiagnosis;
}
public ArrayList<PatientIllness> getPatientIllnesses() {
return patientIllnesses;
}
public void setPatientIllnesses(ArrayList<PatientIllness> patientIllnesses) {
this.patientIllnesses = patientIllnesses;
}
public ArrayList<Test> getTestArray() {
return testArray;
}
public void setTestArray(ArrayList<Test> testArray) {
this.testArray = testArray;
}
public Test addNewTest(){
Test test = new Test();
testArray.add(test);
return test;
}
public PatientIllness addNewIllness(){
PatientIllness patientIllness = new PatientIllness();
patientIllnesses.add(patientIllness);
return patientIllness;
}
public PrescribedDrug addNewPrescribedDrug(){
PrescribedDrug pd = new PrescribedDrug();
prescribedDrug.add(pd);
return pd;
}
}
| 2,086 | 0.645254 | 0.645254 | 79 | 24.405064 | 22.782137 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.367089 | false | false | 2 |
5abbccfb6bcfc6475a49cd332f4f4063300c622c | 1,142,461,349,670 | 15bed28e4d2635295549f8679cbcd166bef57770 | /src/main/java/net/reini/rabbitmq/cdi/EventKey.java | 2e09630ec332c948953eb4836abdea5162da8b49 | [
"MIT"
] | permissive | tgiachi/rabbitmq-cdi | https://github.com/tgiachi/rabbitmq-cdi | 4a2d15ce67293af8b3be79cd024b224cae263a1d | 8e18d28e3caea6b6bfc4016e1fc9bd97c349b894 | refs/heads/master | 2020-05-15T13:21:56.995000 | 2019-04-16T12:20:22 | 2019-04-16T12:20:22 | 182,298,494 | 0 | 0 | null | true | 2019-04-19T17:02:21 | 2019-04-19T17:02:21 | 2019-04-16T12:20:31 | 2019-04-16T12:20:29 | 751 | 0 | 0 | 0 | null | false | false | package net.reini.rabbitmq.cdi;
import java.util.StringJoiner;
import javax.enterprise.event.TransactionPhase;
final class EventKey<T> {
private final Class<T> type;
private final TransactionPhase phase;
static <T> EventKey<T> of(Class<T> type, TransactionPhase phase) {
return new EventKey<>(type, phase);
}
private EventKey(Class<T> type, TransactionPhase phase) {
this.phase = phase;
this.type = type;
}
@Override
public String toString() {
return new StringJoiner(", ", "EventKey[", "]").add(type.getSimpleName()).add(phase.name())
.toString();
}
@Override
public int hashCode() {
return type.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
} else if (!(obj instanceof EventKey)) {
return false;
}
EventKey<?> other = (EventKey<?>) obj;
return phase.equals(other.phase) && type.equals(other.type);
}
}
| UTF-8 | Java | 948 | java | EventKey.java | Java | [] | null | [] | package net.reini.rabbitmq.cdi;
import java.util.StringJoiner;
import javax.enterprise.event.TransactionPhase;
final class EventKey<T> {
private final Class<T> type;
private final TransactionPhase phase;
static <T> EventKey<T> of(Class<T> type, TransactionPhase phase) {
return new EventKey<>(type, phase);
}
private EventKey(Class<T> type, TransactionPhase phase) {
this.phase = phase;
this.type = type;
}
@Override
public String toString() {
return new StringJoiner(", ", "EventKey[", "]").add(type.getSimpleName()).add(phase.name())
.toString();
}
@Override
public int hashCode() {
return type.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
} else if (!(obj instanceof EventKey)) {
return false;
}
EventKey<?> other = (EventKey<?>) obj;
return phase.equals(other.phase) && type.equals(other.type);
}
}
| 948 | 0.651899 | 0.651899 | 41 | 22.121952 | 22.074369 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.487805 | false | false | 2 |
7ce15dfa61355e45b9c4c9d41b862e96b75a9357 | 21,208,548,557,367 | 0e593d56d5a3bd5f52022d20da2c700e28f0a8ad | /Test1/src/Thread/MyThread/MyThread.java | d06fd89371e2f605dc95d8995e218c7434aa7ce6 | [] | no_license | qingmou312/Java_Daily_Learning | https://github.com/qingmou312/Java_Daily_Learning | f7a4a02c0a0b31bcbc4476b99e01bb04e514e2f2 | 9c61e4ce5e4a00c958d4b2d7a55b7c39d6f10844 | refs/heads/master | 2022-07-15T00:51:16.392000 | 2019-09-16T04:33:53 | 2019-09-16T04:33:53 | 160,303,101 | 0 | 0 | null | false | 2022-06-21T01:44:14 | 2018-12-04T05:25:32 | 2019-09-16T04:34:29 | 2022-06-21T01:44:10 | 6,447 | 0 | 0 | 11 | Python | false | false | package Thread.MyThread;
/**
* Author:lidan
* Created:2019/2/19
*/
public class MyThread extends Thread {
// public static void main(String[] args) {
// MyThread myThread1 = new MyThread();
// MyThread myThread2 = new MyThread();
// MyThread myThread3 = new MyThread();
// myThread1.start();
// myThread2.start();
// myThread3.start();
// }
private static int Piao = 10;
// Object obj =new Object();
public void run() {//所有的线程从此处开始执行
while (true) {
synchronized (this) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (Piao > 0) {
System.out.println(Thread.currentThread().getName() + "正在出售" + (Piao--));
}
}
}
}
}
//class MyThread extends Thread{//线程主体
// private String title;
// public MyThread1(String title){
// this.title= title;
// }
// public void run() {//所有的线程从此处开始执行
// for (int i = 0; i < 5; i++) {
// System.out.println(this.title + " i=" + i);
// }
// }
// private static int Piao=100;
// Object obj =new Object();
// public void run() {//所有的线程从此处开始执行
// while(true){
// synchronized (obj){
// if(Piao>0){
// try {
// Thread.sleep(100);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// System.out.println(Thread.currentThread().getName()+"正在出售"+(Piao--));
// }
// }
// }
// }
//}
| UTF-8 | Java | 1,823 | java | MyThread.java | Java | [
{
"context": "package Thread.MyThread;\n\n/**\n * Author:lidan\n * Created:2019/2/19\n */\npublic class MyThread ex",
"end": 45,
"score": 0.9984133243560791,
"start": 40,
"tag": "USERNAME",
"value": "lidan"
}
] | null | [] | package Thread.MyThread;
/**
* Author:lidan
* Created:2019/2/19
*/
public class MyThread extends Thread {
// public static void main(String[] args) {
// MyThread myThread1 = new MyThread();
// MyThread myThread2 = new MyThread();
// MyThread myThread3 = new MyThread();
// myThread1.start();
// myThread2.start();
// myThread3.start();
// }
private static int Piao = 10;
// Object obj =new Object();
public void run() {//所有的线程从此处开始执行
while (true) {
synchronized (this) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (Piao > 0) {
System.out.println(Thread.currentThread().getName() + "正在出售" + (Piao--));
}
}
}
}
}
//class MyThread extends Thread{//线程主体
// private String title;
// public MyThread1(String title){
// this.title= title;
// }
// public void run() {//所有的线程从此处开始执行
// for (int i = 0; i < 5; i++) {
// System.out.println(this.title + " i=" + i);
// }
// }
// private static int Piao=100;
// Object obj =new Object();
// public void run() {//所有的线程从此处开始执行
// while(true){
// synchronized (obj){
// if(Piao>0){
// try {
// Thread.sleep(100);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// System.out.println(Thread.currentThread().getName()+"正在出售"+(Piao--));
// }
// }
// }
// }
//}
| 1,823 | 0.461494 | 0.444702 | 62 | 26.838709 | 19.18601 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.354839 | false | false | 2 |
b6a5a399cfb47a00130caee684d3bd9d419c10d3 | 26,268,019,992,183 | e288182bf579799bdb053e9f48b452dd75bcf4d0 | /rabbitmq/src/main/java/cn/conque/producer/FanoutProducer.java | 930b5cd886a888865d3e7439e7df340b9845dac7 | [
"Apache-2.0"
] | permissive | gwh2008/SpringBoot-Dubbo | https://github.com/gwh2008/SpringBoot-Dubbo | 221f349bcc88e3773e563b4a20dfef0f919b1774 | 2cea2b12a57068c6c99c9db3a90ccf5673544c81 | refs/heads/master | 2022-10-31T18:30:50.996000 | 2019-12-06T04:02:44 | 2019-12-06T04:02:44 | 222,908,316 | 3 | 1 | Apache-2.0 | false | 2022-10-05T18:20:56 | 2019-11-20T10:10:35 | 2019-12-06T04:03:10 | 2022-10-05T18:20:53 | 628 | 3 | 1 | 5 | Java | false | false | package cn.conque.producer;
import cn.conque.bean.Message;
import cn.conque.config.RabbitmqFanoutConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
*
* 交换机,有类型,发布订阅:fanout
*
*/
@Component
public class FanoutProducer {
private static final Logger logger = LoggerFactory.getLogger(FanoutProducer.class);
@Autowired
private AmqpTemplate amqpTemplate;
public void fanoutSendMessage(Message message) {
logger.info("[===========> FanoutExchange Send Message] body: " + message.toString());
amqpTemplate.convertAndSend(RabbitmqFanoutConfig.FANOUT_EXCHANGE, "", message);
}
}
| UTF-8 | Java | 813 | java | FanoutProducer.java | Java | [] | null | [] | package cn.conque.producer;
import cn.conque.bean.Message;
import cn.conque.config.RabbitmqFanoutConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
*
* 交换机,有类型,发布订阅:fanout
*
*/
@Component
public class FanoutProducer {
private static final Logger logger = LoggerFactory.getLogger(FanoutProducer.class);
@Autowired
private AmqpTemplate amqpTemplate;
public void fanoutSendMessage(Message message) {
logger.info("[===========> FanoutExchange Send Message] body: " + message.toString());
amqpTemplate.convertAndSend(RabbitmqFanoutConfig.FANOUT_EXCHANGE, "", message);
}
}
| 813 | 0.75662 | 0.754098 | 27 | 28.370371 | 28.481506 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.592593 | false | false | 2 |
d56811d4aa50e2adf717c4c63bd58640f3b51300 | 17,471,926,997,720 | d7ebaca65d7ccc6673b458105f94349b841561da | /src/main/java/pl/asie/charset/storage/ModCharsetStorage.java | 84bea9cca7622516f34249151f28577a029b0cdd | [] | no_license | SoniEx2/CharsetMC | https://github.com/SoniEx2/CharsetMC | 3d0a222e4652cc0397f3473a8fdd16b644a39188 | 18f4b409d38c8091ef17d3dbc183e39a81193dea | refs/heads/1.9 | 2021-01-13T06:49:18.333000 | 2016-05-14T19:35:03 | 2016-05-14T19:35:17 | 58,892,754 | 0 | 0 | null | true | 2016-05-16T00:51:27 | 2016-05-16T00:51:25 | 2016-05-15T22:57:42 | 2016-05-14T19:34:54 | 742 | 0 | 0 | 0 | null | null | null | package pl.asie.charset.storage;
import com.google.common.base.Predicate;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import net.minecraftforge.oredict.RecipeSorter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.oredict.ShapedOreRecipe;
import pl.asie.charset.audio.tape.RecipeTape;
import pl.asie.charset.audio.tape.RecipeTapeReel;
import pl.asie.charset.lib.ModCharsetLib;
import pl.asie.charset.lib.network.PacketRegistry;
import pl.asie.charset.storage.backpack.HandlerBackpack;
import pl.asie.charset.storage.backpack.BlockBackpack;
import pl.asie.charset.storage.backpack.ItemBackpack;
import pl.asie.charset.storage.backpack.PacketBackpackOpen;
import pl.asie.charset.storage.backpack.TileBackpack;
import pl.asie.charset.storage.locking.*;
import javax.annotation.Nullable;
import java.util.Random;
import java.util.UUID;
@Mod(modid = ModCharsetStorage.MODID, name = ModCharsetStorage.NAME, version = ModCharsetStorage.VERSION,
dependencies = ModCharsetLib.DEP_NO_MCMP, updateJSON = ModCharsetLib.UPDATE_URL)
public class ModCharsetStorage {
public static final String MODID = "CharsetStorage";
public static final String NAME = "#";
public static final String VERSION = "@VERSION@";
public static final int DEFAULT_LOCKING_COLOR = 0xFBDB6A;
private static final Random rand = new Random();
@Mod.Instance(MODID)
public static ModCharsetStorage instance;
@SidedProxy(clientSide = "pl.asie.charset.storage.ProxyClient", serverSide = "pl.asie.charset.storage.ProxyCommon")
public static ProxyCommon proxy;
public static PacketRegistry packet;
public static Logger logger;
public static BlockBackpack backpackBlock;
public static ItemMasterKey masterKeyItem;
public static ItemKey keyItem;
public static ItemLock lockItem;
public static boolean enableBackpackOpenKey;
public static boolean enableKeyKeepInventory;
private Configuration config;
@Mod.EventHandler
public void preInit(FMLPreInitializationEvent event) {
logger = LogManager.getLogger(ModCharsetStorage.MODID);
config = new Configuration(ModCharsetLib.instance.getConfigFile("storage.cfg"));
backpackBlock = new BlockBackpack();
GameRegistry.register(backpackBlock.setRegistryName("backpack"));
GameRegistry.register(new ItemBackpack(backpackBlock).setRegistryName("backpack"));
masterKeyItem = new ItemMasterKey();
GameRegistry.register(masterKeyItem.setRegistryName("masterKey"));
keyItem = new ItemKey();
GameRegistry.register(keyItem.setRegistryName("key"));
lockItem = new ItemLock();
GameRegistry.register(lockItem.setRegistryName("lock"));
ModCharsetLib.proxy.registerItemModel(backpackBlock, 0, "charsetstorage:backpack");
ModCharsetLib.proxy.registerItemModel(masterKeyItem, 0, "charsetstorage:masterKey");
ModCharsetLib.proxy.registerItemModel(keyItem, 0, "charsetstorage:key");
ModCharsetLib.proxy.registerItemModel(lockItem, 0, "charsetstorage:lock");
MinecraftForge.EVENT_BUS.register(proxy);
enableBackpackOpenKey = config.getBoolean("enableOpenKeyBinding", "backpack", true, "Should backpacks be openable with a key binding?");
enableKeyKeepInventory = config.getBoolean("keepKeysOnDeath", "locks", true, "Should keys be kept in inventory on death?");
config.save();
proxy.preInit();
}
@Mod.EventHandler
public void init(FMLInitializationEvent event) {
GameRegistry.registerTileEntity(TileBackpack.class, "charset:backpack");
EntityRegistry.registerModEntity(EntityLock.class, "charsetstorage:lock", 1, this, 64, 3, true);
proxy.init();
packet = new PacketRegistry(ModCharsetStorage.MODID);
packet.registerPacket(0x01, PacketBackpackOpen.class);
NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandlerStorage());
MinecraftForge.EVENT_BUS.register(new HandlerBackpack());
MinecraftForge.EVENT_BUS.register(new LockEventHandler());
if (enableKeyKeepInventory) {
ModCharsetLib.deathHandler.addPredicate(new Predicate<ItemStack>() {
@Override
public boolean apply(@Nullable ItemStack input) {
return input != null && input.getItem() instanceof ItemKey;
}
});
}
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(backpackBlock), "lgl", "scs", "lwl",
'l', Items.LEATHER, 'c', "chestWood", 's', "stickWood", 'g', "ingotGold", 'w', Blocks.WOOL));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(keyItem), "ng", "ng", " g", 'n', "nuggetGold", 'g', "ingotGold") {
@Override
public ItemStack getCraftingResult(InventoryCrafting inv) {
ItemStack result = output.copy();
result.setTagCompound(new NBTTagCompound());
result.getTagCompound().setString("key", new UUID(rand.nextLong(), rand.nextLong()).toString());
return result;
}
});
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(keyItem), "ng", "ng", "kg", 'n', "nuggetGold", 'g', "ingotGold", 'k', keyItem) {
@Override
public ItemStack getCraftingResult(InventoryCrafting inv) {
ItemStack key = inv.getStackInRowAndColumn(0, 2);
if (key == null) {
key = inv.getStackInRowAndColumn(1, 2);
}
if (key != null && key.getItem() instanceof ItemKey) {
ItemStack result = output.copy();
result.setTagCompound(new NBTTagCompound());
result.getTagCompound().setString("key", ((ItemKey) key.getItem()).getRawKey(key));
return result;
}
return null;
}
});
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lockItem), " g ", "gkg", "gig", 'i', "ingotIron", 'g', "ingotGold", 'k', keyItem) {
@Override
public ItemStack getCraftingResult(InventoryCrafting inv) {
ItemStack key = inv.getStackInRowAndColumn(1, 1);
if (key != null && key.getItem() instanceof ItemKey) {
ItemStack result = output.copy();
result.setTagCompound(new NBTTagCompound());
result.getTagCompound().setString("key", ((ItemKey) key.getItem()).getRawKey(key));
return result;
}
return null;
}
});
GameRegistry.addRecipe(new RecipeDyeLock());
RecipeSorter.register("charsetstorage:lockDye", RecipeDyeLock.class, RecipeSorter.Category.SHAPED, "after:minecraft:shaped");
}
}
| UTF-8 | Java | 6,812 | java | ModCharsetStorage.java | Java | [] | null | [] | package pl.asie.charset.storage;
import com.google.common.base.Predicate;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import net.minecraftforge.oredict.RecipeSorter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.oredict.ShapedOreRecipe;
import pl.asie.charset.audio.tape.RecipeTape;
import pl.asie.charset.audio.tape.RecipeTapeReel;
import pl.asie.charset.lib.ModCharsetLib;
import pl.asie.charset.lib.network.PacketRegistry;
import pl.asie.charset.storage.backpack.HandlerBackpack;
import pl.asie.charset.storage.backpack.BlockBackpack;
import pl.asie.charset.storage.backpack.ItemBackpack;
import pl.asie.charset.storage.backpack.PacketBackpackOpen;
import pl.asie.charset.storage.backpack.TileBackpack;
import pl.asie.charset.storage.locking.*;
import javax.annotation.Nullable;
import java.util.Random;
import java.util.UUID;
@Mod(modid = ModCharsetStorage.MODID, name = ModCharsetStorage.NAME, version = ModCharsetStorage.VERSION,
dependencies = ModCharsetLib.DEP_NO_MCMP, updateJSON = ModCharsetLib.UPDATE_URL)
public class ModCharsetStorage {
public static final String MODID = "CharsetStorage";
public static final String NAME = "#";
public static final String VERSION = "@VERSION@";
public static final int DEFAULT_LOCKING_COLOR = 0xFBDB6A;
private static final Random rand = new Random();
@Mod.Instance(MODID)
public static ModCharsetStorage instance;
@SidedProxy(clientSide = "pl.asie.charset.storage.ProxyClient", serverSide = "pl.asie.charset.storage.ProxyCommon")
public static ProxyCommon proxy;
public static PacketRegistry packet;
public static Logger logger;
public static BlockBackpack backpackBlock;
public static ItemMasterKey masterKeyItem;
public static ItemKey keyItem;
public static ItemLock lockItem;
public static boolean enableBackpackOpenKey;
public static boolean enableKeyKeepInventory;
private Configuration config;
@Mod.EventHandler
public void preInit(FMLPreInitializationEvent event) {
logger = LogManager.getLogger(ModCharsetStorage.MODID);
config = new Configuration(ModCharsetLib.instance.getConfigFile("storage.cfg"));
backpackBlock = new BlockBackpack();
GameRegistry.register(backpackBlock.setRegistryName("backpack"));
GameRegistry.register(new ItemBackpack(backpackBlock).setRegistryName("backpack"));
masterKeyItem = new ItemMasterKey();
GameRegistry.register(masterKeyItem.setRegistryName("masterKey"));
keyItem = new ItemKey();
GameRegistry.register(keyItem.setRegistryName("key"));
lockItem = new ItemLock();
GameRegistry.register(lockItem.setRegistryName("lock"));
ModCharsetLib.proxy.registerItemModel(backpackBlock, 0, "charsetstorage:backpack");
ModCharsetLib.proxy.registerItemModel(masterKeyItem, 0, "charsetstorage:masterKey");
ModCharsetLib.proxy.registerItemModel(keyItem, 0, "charsetstorage:key");
ModCharsetLib.proxy.registerItemModel(lockItem, 0, "charsetstorage:lock");
MinecraftForge.EVENT_BUS.register(proxy);
enableBackpackOpenKey = config.getBoolean("enableOpenKeyBinding", "backpack", true, "Should backpacks be openable with a key binding?");
enableKeyKeepInventory = config.getBoolean("keepKeysOnDeath", "locks", true, "Should keys be kept in inventory on death?");
config.save();
proxy.preInit();
}
@Mod.EventHandler
public void init(FMLInitializationEvent event) {
GameRegistry.registerTileEntity(TileBackpack.class, "charset:backpack");
EntityRegistry.registerModEntity(EntityLock.class, "charsetstorage:lock", 1, this, 64, 3, true);
proxy.init();
packet = new PacketRegistry(ModCharsetStorage.MODID);
packet.registerPacket(0x01, PacketBackpackOpen.class);
NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandlerStorage());
MinecraftForge.EVENT_BUS.register(new HandlerBackpack());
MinecraftForge.EVENT_BUS.register(new LockEventHandler());
if (enableKeyKeepInventory) {
ModCharsetLib.deathHandler.addPredicate(new Predicate<ItemStack>() {
@Override
public boolean apply(@Nullable ItemStack input) {
return input != null && input.getItem() instanceof ItemKey;
}
});
}
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(backpackBlock), "lgl", "scs", "lwl",
'l', Items.LEATHER, 'c', "chestWood", 's', "stickWood", 'g', "ingotGold", 'w', Blocks.WOOL));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(keyItem), "ng", "ng", " g", 'n', "nuggetGold", 'g', "ingotGold") {
@Override
public ItemStack getCraftingResult(InventoryCrafting inv) {
ItemStack result = output.copy();
result.setTagCompound(new NBTTagCompound());
result.getTagCompound().setString("key", new UUID(rand.nextLong(), rand.nextLong()).toString());
return result;
}
});
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(keyItem), "ng", "ng", "kg", 'n', "nuggetGold", 'g', "ingotGold", 'k', keyItem) {
@Override
public ItemStack getCraftingResult(InventoryCrafting inv) {
ItemStack key = inv.getStackInRowAndColumn(0, 2);
if (key == null) {
key = inv.getStackInRowAndColumn(1, 2);
}
if (key != null && key.getItem() instanceof ItemKey) {
ItemStack result = output.copy();
result.setTagCompound(new NBTTagCompound());
result.getTagCompound().setString("key", ((ItemKey) key.getItem()).getRawKey(key));
return result;
}
return null;
}
});
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lockItem), " g ", "gkg", "gig", 'i', "ingotIron", 'g', "ingotGold", 'k', keyItem) {
@Override
public ItemStack getCraftingResult(InventoryCrafting inv) {
ItemStack key = inv.getStackInRowAndColumn(1, 1);
if (key != null && key.getItem() instanceof ItemKey) {
ItemStack result = output.copy();
result.setTagCompound(new NBTTagCompound());
result.getTagCompound().setString("key", ((ItemKey) key.getItem()).getRawKey(key));
return result;
}
return null;
}
});
GameRegistry.addRecipe(new RecipeDyeLock());
RecipeSorter.register("charsetstorage:lockDye", RecipeDyeLock.class, RecipeSorter.Category.SHAPED, "after:minecraft:shaped");
}
}
| 6,812 | 0.765267 | 0.762184 | 172 | 38.604652 | 33.296513 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.540698 | false | false | 2 |
e1280279312212d0e0d983415940eb0053560edc | 6,476,810,686,994 | fffaadbcd8225c14912abbe960fe1500ded5f5a6 | /apps/icona/src/main/java/org/onosproject/icona/store/BackupInterLink.java | 80a0387e74ae8c55503b906f97c0b5ac1bd64fa6 | [
"Apache-2.0"
] | permissive | SmartInfrastructures/dreamer | https://github.com/SmartInfrastructures/dreamer | 5708bc028c36fc9454d10ea125fbb1cffd683dd8 | ae78b0a366a9d41669eb48c20cddcd959caa940c | refs/heads/icona | 2020-12-24T15:40:48.153000 | 2015-03-30T12:54:12 | 2015-03-30T12:54:12 | 29,966,399 | 3 | 2 | null | false | 2016-03-09T18:35:48 | 2015-01-28T12:24:46 | 2015-08-11T12:47:57 | 2015-06-05T13:08:12 | 16,685 | 0 | 2 | 1 | Java | null | null | package org.onosproject.icona.store;
import org.onosproject.icona.InterClusterPath;
import org.onosproject.icona.store.PseudoWire.PathInstallationStatus;
import org.onosproject.net.ConnectPoint;
public class BackupInterLink {
private InterLink il;
InterClusterPath path;
BackupMasterPseudoWire pw;
private ConnectPoint src;
private ConnectPoint dst;
private String srcClusterName;
private String dstClusterName;
public BackupInterLink(InterLink il, InterClusterPath path) {
this.il = il;
this.path = path;
this.srcClusterName = il.srcClusterName();
this.dstClusterName = il.dstClusterName();
this.src = this.path.getInterlinks().get(0).src();
this.dst = this.path.getInterlinks().get(this.path.getInterlinks().size()-1).dst();
this.pw = new BackupMasterPseudoWire(this.src, this.dst, path, PathInstallationStatus.RECEIVED);
}
public void setPW(BackupMasterPseudoWire pw) {
this.pw = pw;
}
public BackupMasterPseudoWire getPW() {
return this.pw;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((dst == null) ? 0 : dst.hashCode());
result = prime * result
+ ((dstClusterName == null) ? 0 : dstClusterName.hashCode());
result = prime * result + ((src == null) ? 0 : src.hashCode());
result = prime * result
+ ((srcClusterName == null) ? 0 : srcClusterName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BackupInterLink other = (BackupInterLink) obj;
if (dst == null) {
if (other.dst != null)
return false;
} else if (!dst.equals(other.dst))
return false;
if (dstClusterName == null) {
if (other.dstClusterName != null)
return false;
} else if (!dstClusterName.equals(other.dstClusterName))
return false;
if (src == null) {
if (other.src != null)
return false;
} else if (!src.equals(other.src))
return false;
if (srcClusterName == null) {
if (other.srcClusterName != null)
return false;
} else if (!srcClusterName.equals(other.srcClusterName))
return false;
return true;
}
}
| UTF-8 | Java | 2,539 | java | BackupInterLink.java | Java | [] | null | [] | package org.onosproject.icona.store;
import org.onosproject.icona.InterClusterPath;
import org.onosproject.icona.store.PseudoWire.PathInstallationStatus;
import org.onosproject.net.ConnectPoint;
public class BackupInterLink {
private InterLink il;
InterClusterPath path;
BackupMasterPseudoWire pw;
private ConnectPoint src;
private ConnectPoint dst;
private String srcClusterName;
private String dstClusterName;
public BackupInterLink(InterLink il, InterClusterPath path) {
this.il = il;
this.path = path;
this.srcClusterName = il.srcClusterName();
this.dstClusterName = il.dstClusterName();
this.src = this.path.getInterlinks().get(0).src();
this.dst = this.path.getInterlinks().get(this.path.getInterlinks().size()-1).dst();
this.pw = new BackupMasterPseudoWire(this.src, this.dst, path, PathInstallationStatus.RECEIVED);
}
public void setPW(BackupMasterPseudoWire pw) {
this.pw = pw;
}
public BackupMasterPseudoWire getPW() {
return this.pw;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((dst == null) ? 0 : dst.hashCode());
result = prime * result
+ ((dstClusterName == null) ? 0 : dstClusterName.hashCode());
result = prime * result + ((src == null) ? 0 : src.hashCode());
result = prime * result
+ ((srcClusterName == null) ? 0 : srcClusterName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BackupInterLink other = (BackupInterLink) obj;
if (dst == null) {
if (other.dst != null)
return false;
} else if (!dst.equals(other.dst))
return false;
if (dstClusterName == null) {
if (other.dstClusterName != null)
return false;
} else if (!dstClusterName.equals(other.dstClusterName))
return false;
if (src == null) {
if (other.src != null)
return false;
} else if (!src.equals(other.src))
return false;
if (srcClusterName == null) {
if (other.srcClusterName != null)
return false;
} else if (!srcClusterName.equals(other.srcClusterName))
return false;
return true;
}
}
| 2,539 | 0.601024 | 0.597479 | 83 | 29.590361 | 22.152287 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.819277 | false | false | 2 |
caf77b9492ebeb721ed09f91f08503726aaf82e1 | 27,127,013,492,641 | 57a7b3581a2427dcd48df94edb80a7c395d0d397 | /app/src/main/java/com/android/fik/filterrecyclerview/SelectLocationData.java | 0b1ce19530ad9e4fa2b8c2a8c410b673ab8f1b08 | [] | no_license | ashokp123/Filterable-RecyclerView-master | https://github.com/ashokp123/Filterable-RecyclerView-master | 200bf0fcd92a43a71f8b2a6db6fbf2ec87b869a2 | d6641a8dfb3bc6b5f5be7e3e406e27ebb4f78250 | refs/heads/master | 2020-09-26T13:46:52.002000 | 2019-12-06T07:05:52 | 2019-12-06T07:05:52 | 226,267,280 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.android.fik.filterrecyclerview;
public class SelectLocationData {
static String[] location_array = {"2500 E 2nd St, Reno, NV 89595", "N Victory Blvd Burbunk, CA", "San Jose Store #3"};
}
| UTF-8 | Java | 206 | java | SelectLocationData.java | Java | [] | null | [] | package com.android.fik.filterrecyclerview;
public class SelectLocationData {
static String[] location_array = {"2500 E 2nd St, Reno, NV 89595", "N Victory Blvd Burbunk, CA", "San Jose Store #3"};
}
| 206 | 0.713592 | 0.660194 | 7 | 28.428572 | 41.688839 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 2 |
d07dfeeed4cde25fa8187b6e35abee498f434209 | 18,081,812,371,798 | c183204811f8dd5723727a5be5d61daad365a464 | /app/src/main/java/com/suncreate/pressuresensor/fragment/me/MyFinancialCenterPaymentDetailListFragment.java | 5fd5b869f4fc1c020a1ef03bb4b51977cca163fd | [
"Apache-2.0"
] | permissive | linking123/PressureSensor | https://github.com/linking123/PressureSensor | cdd18e0065c77023607c917564d31aca589160be | 2ee09422eeda207a3a99ad24d389061fc176a2b4 | refs/heads/master | 2018-09-21T08:16:47.757000 | 2018-07-28T14:47:25 | 2018-07-28T14:47:25 | 110,442,896 | 1 | 0 | Apache-2.0 | false | 2018-05-28T14:06:16 | 2017-11-12T15:15:00 | 2017-11-12T15:32:31 | 2018-05-28T14:06:14 | 14,674 | 0 | 0 | 4 | Java | false | null | package com.suncreate.pressuresensor.fragment.me;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import com.google.gson.reflect.TypeToken;
import com.suncreate.pressuresensor.AppContext;
import com.suncreate.pressuresensor.R;
import com.suncreate.pressuresensor.adapter.base.BaseListAdapter;
import com.suncreate.pressuresensor.adapter.general.MyFinancialCenterPaymentDetailListAdapter;
import com.suncreate.pressuresensor.api.remote.MonkeyApi;
import com.suncreate.pressuresensor.base.BaseListFragment;
import com.suncreate.pressuresensor.bean.SimpleBackPage;
import com.suncreate.pressuresensor.bean.base.PageBean;
import com.suncreate.pressuresensor.bean.base.ResultBean;
import com.suncreate.pressuresensor.bean.user.Pay;
import com.suncreate.pressuresensor.cache.CacheManager;
import com.suncreate.pressuresensor.fragment.general.GeneralListFragment;
import com.suncreate.pressuresensor.ui.empty.EmptyLayout;
import com.suncreate.pressuresensor.util.UIHelper;
import java.lang.reflect.Type;
import java.util.ArrayList;
/**
* 收支明细列表
*/
public class MyFinancialCenterPaymentDetailListFragment extends GeneralListFragment<Pay> {
/**
* 收支明细的状态:总的分两大类,
* 收入(下级分类有 充值,退款,服务订单费,工位订单费)
* 与
* 支出(下级分类有 提现,服务订单费,工位订单费,配件订单费),
* 明细列表只以以上下级分类名称显示;
* 在详情页面体现更细节的状态分类,体现订单号、时间、金额、种类;
*/
public static final String TAG = "PaymentDetailListFragment";
private static final String CACHE_KEY_PREFIX = "financial_center_inout_list_";
private int mCatalog = 0;
//消费标识(0支出 1收入,默认全部)
String consumeCost = "";
private ConnectivityManager connectivityManager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args != null) {
mCatalog = args.getInt(BaseListFragment.BUNDLE_KEY_CATALOG, 0);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
}
@Override
protected int getLayoutId() {
return R.layout.fragment_my_financial_center_in_out_detail_list;
}
@Override
protected void initWidget(View root) {
super.initWidget(root);
}
/**
* request local cache
*/
@SuppressWarnings("unchecked")
private void requestLocalCache() {
mBean = (PageBean<Pay>) CacheManager.readObject(getActivity(), CACHE_NAME);
if (mBean != null) {
mAdapter.clear();
mAdapter.addItem(mBean.getItems());
mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
mRefreshLayout.setVisibility(View.VISIBLE);
mRefreshLayout.setCanLoadMore();
} else {
mBean = new PageBean<>();
mBean.setItems(new ArrayList<Pay>());
}
}
@Override
protected void initData() {
CACHE_NAME = CACHE_KEY_PREFIX + mCatalog;
super.initData();
}
@Override
protected void onRequestError(int code) {
super.onRequestError(code);
requestLocalCache();
}
@Override
protected void requestData() {
super.requestData();
MonkeyApi.getPayList(getPayTypeByCatalog(mCatalog), mBean != null ? mBean.getPageNum() + 1 : 1, AppContext.PAGE_SIZE, mHandler);
}
@Override
protected void setListData(ResultBean<PageBean<Pay>> resultBean) {
super.setListData(resultBean);
}
@Override
protected BaseListAdapter<Pay> getListAdapter() {
return new MyFinancialCenterPaymentDetailListAdapter(this);
}
private String getPayTypeByCatalog(int catagory) {
switch (catagory) {
case 0:
consumeCost = "";
break;
case 1:
consumeCost = "1";
break;
case 2:
consumeCost = "0";
break;
}
return consumeCost;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
super.onItemClick(parent, view, position, id);
Pay pay = mAdapter.getItem(position);
if (pay != null) {
Bundle b = new Bundle();
b.putString("id", pay.getId());
b.putString("addtime", pay.getAddtime());
b.putString("amount", pay.getAmount());
b.putString("payType", pay.getPayType());
b.putString("consumeCost", pay.getConsumeCost());
b.putString("consumeSn", pay.getConsumeSn());
UIHelper.showSimpleBack(getActivity(), SimpleBackPage.MY_FINANCIAL_CENTER_PAYMENT_DETAIL_DETAIL, b);
}
}
@Override
protected Type getType() {
return new TypeToken<ResultBean<PageBean<Pay>>>() {
}.getType();
}
}
| UTF-8 | Java | 5,273 | java | MyFinancialCenterPaymentDetailListFragment.java | Java | [] | null | [] | package com.suncreate.pressuresensor.fragment.me;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import com.google.gson.reflect.TypeToken;
import com.suncreate.pressuresensor.AppContext;
import com.suncreate.pressuresensor.R;
import com.suncreate.pressuresensor.adapter.base.BaseListAdapter;
import com.suncreate.pressuresensor.adapter.general.MyFinancialCenterPaymentDetailListAdapter;
import com.suncreate.pressuresensor.api.remote.MonkeyApi;
import com.suncreate.pressuresensor.base.BaseListFragment;
import com.suncreate.pressuresensor.bean.SimpleBackPage;
import com.suncreate.pressuresensor.bean.base.PageBean;
import com.suncreate.pressuresensor.bean.base.ResultBean;
import com.suncreate.pressuresensor.bean.user.Pay;
import com.suncreate.pressuresensor.cache.CacheManager;
import com.suncreate.pressuresensor.fragment.general.GeneralListFragment;
import com.suncreate.pressuresensor.ui.empty.EmptyLayout;
import com.suncreate.pressuresensor.util.UIHelper;
import java.lang.reflect.Type;
import java.util.ArrayList;
/**
* 收支明细列表
*/
public class MyFinancialCenterPaymentDetailListFragment extends GeneralListFragment<Pay> {
/**
* 收支明细的状态:总的分两大类,
* 收入(下级分类有 充值,退款,服务订单费,工位订单费)
* 与
* 支出(下级分类有 提现,服务订单费,工位订单费,配件订单费),
* 明细列表只以以上下级分类名称显示;
* 在详情页面体现更细节的状态分类,体现订单号、时间、金额、种类;
*/
public static final String TAG = "PaymentDetailListFragment";
private static final String CACHE_KEY_PREFIX = "financial_center_inout_list_";
private int mCatalog = 0;
//消费标识(0支出 1收入,默认全部)
String consumeCost = "";
private ConnectivityManager connectivityManager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args != null) {
mCatalog = args.getInt(BaseListFragment.BUNDLE_KEY_CATALOG, 0);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
}
@Override
protected int getLayoutId() {
return R.layout.fragment_my_financial_center_in_out_detail_list;
}
@Override
protected void initWidget(View root) {
super.initWidget(root);
}
/**
* request local cache
*/
@SuppressWarnings("unchecked")
private void requestLocalCache() {
mBean = (PageBean<Pay>) CacheManager.readObject(getActivity(), CACHE_NAME);
if (mBean != null) {
mAdapter.clear();
mAdapter.addItem(mBean.getItems());
mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
mRefreshLayout.setVisibility(View.VISIBLE);
mRefreshLayout.setCanLoadMore();
} else {
mBean = new PageBean<>();
mBean.setItems(new ArrayList<Pay>());
}
}
@Override
protected void initData() {
CACHE_NAME = CACHE_KEY_PREFIX + mCatalog;
super.initData();
}
@Override
protected void onRequestError(int code) {
super.onRequestError(code);
requestLocalCache();
}
@Override
protected void requestData() {
super.requestData();
MonkeyApi.getPayList(getPayTypeByCatalog(mCatalog), mBean != null ? mBean.getPageNum() + 1 : 1, AppContext.PAGE_SIZE, mHandler);
}
@Override
protected void setListData(ResultBean<PageBean<Pay>> resultBean) {
super.setListData(resultBean);
}
@Override
protected BaseListAdapter<Pay> getListAdapter() {
return new MyFinancialCenterPaymentDetailListAdapter(this);
}
private String getPayTypeByCatalog(int catagory) {
switch (catagory) {
case 0:
consumeCost = "";
break;
case 1:
consumeCost = "1";
break;
case 2:
consumeCost = "0";
break;
}
return consumeCost;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
super.onItemClick(parent, view, position, id);
Pay pay = mAdapter.getItem(position);
if (pay != null) {
Bundle b = new Bundle();
b.putString("id", pay.getId());
b.putString("addtime", pay.getAddtime());
b.putString("amount", pay.getAmount());
b.putString("payType", pay.getPayType());
b.putString("consumeCost", pay.getConsumeCost());
b.putString("consumeSn", pay.getConsumeSn());
UIHelper.showSimpleBack(getActivity(), SimpleBackPage.MY_FINANCIAL_CENTER_PAYMENT_DETAIL_DETAIL, b);
}
}
@Override
protected Type getType() {
return new TypeToken<ResultBean<PageBean<Pay>>>() {
}.getType();
}
}
| 5,273 | 0.661597 | 0.659396 | 155 | 31.23871 | 26.109468 | 136 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.574194 | false | false | 2 |
e35039b6969577f1e4ea5c7aa8f2675a74bec2bb | 31,310,311,639,034 | 199b29912fe8e2c1dda7eb73414f5e401ad6e8f9 | /src/main/java/br/pegz/ciandt/service/dto/package-info.java | 1457eb398d79ed1a57a274a466977b836ab2b707 | [] | no_license | BulkSecurityGeneratorProject/prog-ferias-anuais | https://github.com/BulkSecurityGeneratorProject/prog-ferias-anuais | 2f690d6d24e1140c4a2260a09c4a400fe44c6c08 | 85ba62f4ee123fba7cf5bfa23bbec77834c432ab | refs/heads/master | 2022-12-15T22:30:51.744000 | 2017-01-16T13:48:11 | 2017-01-16T13:48:11 | 296,578,665 | 0 | 0 | null | true | 2020-09-18T09:40:11 | 2020-09-18T09:40:11 | 2017-01-16T10:18:24 | 2017-01-16T13:48:18 | 83,034 | 0 | 0 | 0 | null | false | false | /**
* Data Transfer Objects.
*/
package br.pegz.ciandt.service.dto;
| UTF-8 | Java | 70 | java | package-info.java | Java | [] | null | [] | /**
* Data Transfer Objects.
*/
package br.pegz.ciandt.service.dto;
| 70 | 0.685714 | 0.685714 | 4 | 16.5 | 13.955286 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 2 |
11912e77e7791df932c69362daf8102361e545ed | 6,966,437,015,741 | 0939acb5ce83828a52b56671445549f6203ddbfc | /app/src/main/java/com/andin/game/tictactoe/data/Constants.java | f86616d3bcc9d67ca27ac60c02c14788d5c0d16c | [] | no_license | andinicolescu/tictactoe | https://github.com/andinicolescu/tictactoe | add0cf9ed8c4503af4cdf4550c889331110b22a1 | f34a590aff24ca5797c9247a423224ddfe9e2927 | refs/heads/master | 2021-01-11T05:16:06.437000 | 2016-10-31T15:44:59 | 2016-10-31T15:44:59 | 71,707,848 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.andin.game.tictactoe.data;
/**
* Created by Andi N on 10/22/2016.
*/
public class Constants {
public final static String DIFFICULTY = "difficulty";
public final static String COINS = "coins";
public final static String PREFERENCES = "preferences";
public final static String PROGRESS = "progress";
public final static String MUSIC = "music";
public final static String MEDIUM = "medium";
public final static String IMPOSSIBLE = "impossible";
public static final int HARD = 0;
public static final int NORMAL = 1;
public static final int EASY = 2;
public static final int PVP = 3;
public static final int PVC_WIN = 0;
public static final int PVC_LOSE = 1;
public static final int TIE = 2;
public static final int PVP_WIN2 = 3;
public static final int PVP_WIN1 = 4;
}
| UTF-8 | Java | 846 | java | Constants.java | Java | [
{
"context": " com.andin.game.tictactoe.data;\n\n/**\n * Created by Andi N on 10/22/2016.\n */\n\npublic class Constants {\n\n ",
"end": 64,
"score": 0.9997187256813049,
"start": 58,
"tag": "NAME",
"value": "Andi N"
}
] | null | [] | package com.andin.game.tictactoe.data;
/**
* Created by <NAME> on 10/22/2016.
*/
public class Constants {
public final static String DIFFICULTY = "difficulty";
public final static String COINS = "coins";
public final static String PREFERENCES = "preferences";
public final static String PROGRESS = "progress";
public final static String MUSIC = "music";
public final static String MEDIUM = "medium";
public final static String IMPOSSIBLE = "impossible";
public static final int HARD = 0;
public static final int NORMAL = 1;
public static final int EASY = 2;
public static final int PVP = 3;
public static final int PVC_WIN = 0;
public static final int PVC_LOSE = 1;
public static final int TIE = 2;
public static final int PVP_WIN2 = 3;
public static final int PVP_WIN1 = 4;
}
| 846 | 0.689125 | 0.666667 | 25 | 32.84 | 19.394184 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.68 | false | false | 2 |
eeb4298d72343cf1f7efb905bd89d16486191aa8 | 4,647,154,670,261 | 2c1081390d4b996f11f90f61a08ee4c7c2562f95 | /src/com/alk/kucoinsdk/business/assetsOperation/BalanceList.java | 68a7f4fc7744ea4593ce7167bc5d9dc91277690c | [
"MIT"
] | permissive | rx754pilot/KuCoin_SDK_ALK | https://github.com/rx754pilot/KuCoin_SDK_ALK | f93d72cb0947bbcf15b940ad593fe3128aaaa487 | be893cc4d1abb8622dd19616c8193428e72b1041 | refs/heads/master | 2021-10-08T10:03:53.606000 | 2018-12-09T15:41:17 | 2018-12-09T15:41:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.alk.kucoinsdk.business.assetsOperation;
import com.alk.kucoinsdk.business.KucoinResponse;
/**
* Created by alksentrs (aleksander medella) on 12/07/18.
*/
public class BalanceList extends KucoinResponse {
BalanceListData data;
public BalanceListData getData() {
return data;
}
public void setData(BalanceListData data) {
this.data = data;
}
@Override
public String toString() {
return "{" +
"msg:" + msg + "," +
"timestamp:" + timestamp + "," +
"success:" + success + "," +
"code:" + code + "," +
"data:" + data +
"}";
}
}
| UTF-8 | Java | 694 | java | BalanceList.java | Java | [
{
"context": "oinsdk.business.KucoinResponse;\n\n/**\n * Created by alksentrs (aleksander medella) on 12/07/18.\n */\npublic clas",
"end": 131,
"score": 0.9996724724769592,
"start": 122,
"tag": "USERNAME",
"value": "alksentrs"
},
{
"context": "ess.KucoinResponse;\n\n/**\n * Created b... | null | [] | package com.alk.kucoinsdk.business.assetsOperation;
import com.alk.kucoinsdk.business.KucoinResponse;
/**
* Created by alksentrs (<NAME>) on 12/07/18.
*/
public class BalanceList extends KucoinResponse {
BalanceListData data;
public BalanceListData getData() {
return data;
}
public void setData(BalanceListData data) {
this.data = data;
}
@Override
public String toString() {
return "{" +
"msg:" + msg + "," +
"timestamp:" + timestamp + "," +
"success:" + success + "," +
"code:" + code + "," +
"data:" + data +
"}";
}
}
| 682 | 0.528818 | 0.520173 | 30 | 22.133333 | 19.34379 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 2 |
fd1b403618dfcb8541770b7538a1620211642b8d | 4,647,154,670,524 | c5af0e700ab791384ff379a27c37d8c688a27f70 | /app/src/main/java/com/gr/light/patterns/proxy/ProxyGamePlayer.java | 0f2087c5bbeca1ba54e0a85eae48ead686905973 | [] | no_license | wss711/Light | https://github.com/wss711/Light | fb412c9c1466a6b37a1edba844692a5d083f2651 | b3186beb460856e0049e0a7d3763de0fef5f14bf | refs/heads/master | 2020-12-28T15:16:52.710000 | 2020-03-25T12:41:13 | 2020-03-25T12:41:13 | 238,384,611 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.gr.light.patterns.proxy;
/**
* TODO
* <p>
* Created by WSS on 2020-02-16
**/
public class ProxyGamePlayer implements IGamePlayer {
private IGamePlayer gamePlayer = null;
public ProxyGamePlayer(IGamePlayer gamePlayer) {
this.gamePlayer = gamePlayer;
}
@Override
public void login(String user, String password) {
this.gamePlayer.login(user,password);
}
@Override
public void killBoss() {
this.gamePlayer.killBoss();
}
@Override
public void upgrade() {
this.gamePlayer.upgrade();
}
}
| UTF-8 | Java | 584 | java | ProxyGamePlayer.java | Java | [
{
"context": ".patterns.proxy;\n\n/**\n * TODO\n * <p>\n * Created by WSS on 2020-02-16\n **/\npublic class ProxyGamePlayer ",
"end": 74,
"score": 0.9980989694595337,
"start": 71,
"tag": "USERNAME",
"value": "WSS"
}
] | null | [] | package com.gr.light.patterns.proxy;
/**
* TODO
* <p>
* Created by WSS on 2020-02-16
**/
public class ProxyGamePlayer implements IGamePlayer {
private IGamePlayer gamePlayer = null;
public ProxyGamePlayer(IGamePlayer gamePlayer) {
this.gamePlayer = gamePlayer;
}
@Override
public void login(String user, String password) {
this.gamePlayer.login(user,password);
}
@Override
public void killBoss() {
this.gamePlayer.killBoss();
}
@Override
public void upgrade() {
this.gamePlayer.upgrade();
}
}
| 584 | 0.640411 | 0.626712 | 30 | 18.466667 | 18.422329 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.266667 | false | false | 2 |
68131619c72b36442bdfae130846dc373eb97a11 | 9,105,330,673,099 | e4d17666563ffb339eb36c890c219956f2ba52f3 | /src/servlets/ListPurchasesServlet.java | d1174cffd1ad4c00d16ed66bb919a7f7e0144166 | [] | no_license | macrozone/zhaw_secure_marketplace_lab1 | https://github.com/macrozone/zhaw_secure_marketplace_lab1 | 048c746ccc71f9579263dee329cd89ae96f94020 | cff93cc952d101e20b85ac8f31460dfa2055994f | refs/heads/master | 2021-01-10T07:48:22.604000 | 2016-01-04T20:24:22 | 2016-01-04T20:24:22 | 47,414,924 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package servlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.HttpMethodConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.ServletSecurity.EmptyRoleSemantic;
import javax.servlet.annotation.ServletSecurity.TransportGuarantee;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.util.ArrayList;
import beans.Purchase;
import data.*;
@WebServlet("/admin/listpurchases")
@ServletSecurity(
value = @HttpConstraint(value = EmptyRoleSemantic.DENY),
httpMethodConstraints = {@HttpMethodConstraint(value = "GET",
rolesAllowed = {"marketing", "sales"},
transportGuarantee = TransportGuarantee.CONFIDENTIAL),
@HttpMethodConstraint(value = "POST",
rolesAllowed = {"marketing", "sales"},
transportGuarantee = TransportGuarantee.CONFIDENTIAL)})
public class ListPurchasesServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Handles the HTTP GET method.
* @param request servlet request
* @param response servlet response
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP POST method.
* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Processes requests for both HTTP GET and POST methods.
* @param request servlet request
* @param response servlet response
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Get all purchases from DB
ArrayList<Purchase> purchases = PurchaseDB.getPurchases();
// Store the purchases in the request
request.setAttribute("purchases", purchases);
// Check if the user is allowed to complete purchases
if (request.isUserInRole("sales")) {
request.setAttribute("completeAllowed", true);
} else {
request.setAttribute("completeAllowed", false);
}
// Forward to JSP
String url = "/WEB-INF/pages/admin/purchases.jsp";
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
} | UTF-8 | Java | 2,716 | java | ListPurchasesServlet.java | Java | [] | null | [] | package servlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.HttpMethodConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.ServletSecurity.EmptyRoleSemantic;
import javax.servlet.annotation.ServletSecurity.TransportGuarantee;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.util.ArrayList;
import beans.Purchase;
import data.*;
@WebServlet("/admin/listpurchases")
@ServletSecurity(
value = @HttpConstraint(value = EmptyRoleSemantic.DENY),
httpMethodConstraints = {@HttpMethodConstraint(value = "GET",
rolesAllowed = {"marketing", "sales"},
transportGuarantee = TransportGuarantee.CONFIDENTIAL),
@HttpMethodConstraint(value = "POST",
rolesAllowed = {"marketing", "sales"},
transportGuarantee = TransportGuarantee.CONFIDENTIAL)})
public class ListPurchasesServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Handles the HTTP GET method.
* @param request servlet request
* @param response servlet response
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP POST method.
* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Processes requests for both HTTP GET and POST methods.
* @param request servlet request
* @param response servlet response
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Get all purchases from DB
ArrayList<Purchase> purchases = PurchaseDB.getPurchases();
// Store the purchases in the request
request.setAttribute("purchases", purchases);
// Check if the user is allowed to complete purchases
if (request.isUserInRole("sales")) {
request.setAttribute("completeAllowed", true);
} else {
request.setAttribute("completeAllowed", false);
}
// Forward to JSP
String url = "/WEB-INF/pages/admin/purchases.jsp";
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
} | 2,716 | 0.69109 | 0.690722 | 79 | 33.392406 | 24.550344 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.037975 | false | false | 2 |
5c572beca3fdf46f75b82c30d6d9e73c87fdc5d2 | 21,191,368,692,185 | 6f672fb72caedccb841ee23f53e32aceeaf1895e | /whatsapp/src/org/whispersystems/U.java | a5fcb0ccd9557e698e772c627a285a405568d4e4 | [] | no_license | cha63506/CompSecurity | https://github.com/cha63506/CompSecurity | 5c69743f660b9899146ed3cf21eceabe3d5f4280 | eee7e74f4088b9c02dd711c061fc04fb1e4e2654 | refs/heads/master | 2018-03-23T04:15:18.480000 | 2015-12-19T01:29:58 | 2015-12-19T01:29:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package org.whispersystems;
import java.io.Serializable;
import java.util.Set;
// Referenced classes of package org.whispersystems:
// W, b1, V, J,
// as
public abstract class U
implements Serializable
{
public static int a;
private static final long serialVersionUID = 0L;
U()
{
}
public static U a(Object obj)
{
if (obj == null)
{
return c();
} else
{
return new W(obj);
}
}
public static U b(Object obj)
{
return new W(b1.a(obj));
}
public static U c()
{
return V.b;
}
public abstract Object a();
public abstract Object a(J j);
public abstract U a(U u);
public abstract U a(as as);
public abstract boolean b();
public abstract Object c(Object obj);
public abstract Set d();
public abstract Object e();
public abstract boolean equals(Object obj);
public abstract int hashCode();
public abstract String toString();
}
| UTF-8 | Java | 1,219 | java | U.java | Java | [
{
"context": "// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://www.geocities.com/kpdus",
"end": 61,
"score": 0.9996842741966248,
"start": 45,
"tag": "NAME",
"value": "Pavel Kouznetsov"
}
] | null | [] | // Decompiled by Jad v1.5.8e. Copyright 2001 <NAME>.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package org.whispersystems;
import java.io.Serializable;
import java.util.Set;
// Referenced classes of package org.whispersystems:
// W, b1, V, J,
// as
public abstract class U
implements Serializable
{
public static int a;
private static final long serialVersionUID = 0L;
U()
{
}
public static U a(Object obj)
{
if (obj == null)
{
return c();
} else
{
return new W(obj);
}
}
public static U b(Object obj)
{
return new W(b1.a(obj));
}
public static U c()
{
return V.b;
}
public abstract Object a();
public abstract Object a(J j);
public abstract U a(U u);
public abstract U a(as as);
public abstract boolean b();
public abstract Object c(Object obj);
public abstract Set d();
public abstract Object e();
public abstract boolean equals(Object obj);
public abstract int hashCode();
public abstract String toString();
}
| 1,209 | 0.59475 | 0.586546 | 67 | 17.194031 | 17.365465 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.358209 | false | false | 2 |
cd420802bfc20a79ab981a6eb3671113924bff9f | 25,460,566,191,313 | bdfa75eae8414798c29a78bb8e9c0311caed5bdb | /src/MyRectangle.java | 1c377db410ea4ec92f2be1dc10c4795e3c167a72 | [] | no_license | Rabia1995/Drawing-Application | https://github.com/Rabia1995/Drawing-Application | 6c49cfa2973a48ecec513884a87ac2fd544b69e8 | 97c025bb52616cc30171941afb721905ab3e34cb | refs/heads/master | 2020-05-03T06:30:49.971000 | 2019-03-29T21:11:49 | 2019-03-29T21:11:49 | 178,474,794 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.awt.Color;
import java.awt.Graphics;
public class MyRectangle extends MyBoundedShape {
//Constructor
public MyRectangle() {
super();
setUnFilled(false);
}
public MyRectangle(int x1, int y1, int x2, int y2, Color color,boolean notFill)
{
super(x1, y1, x2, y2, color, notFill);
}
public void draw(Graphics g) {g.setColor(getColor());
//Check if it is filled
if (filled()) {
g.fillRect(getUpperLeftX(), getUpperLeftY(), getWidth(), getHeight());
}
else
{
g.drawRect(getUpperLeftX(), getUpperLeftY(), getWidth(), getHeight());
}
}
} | UTF-8 | Java | 589 | java | MyRectangle.java | Java | [] | null | [] |
import java.awt.Color;
import java.awt.Graphics;
public class MyRectangle extends MyBoundedShape {
//Constructor
public MyRectangle() {
super();
setUnFilled(false);
}
public MyRectangle(int x1, int y1, int x2, int y2, Color color,boolean notFill)
{
super(x1, y1, x2, y2, color, notFill);
}
public void draw(Graphics g) {g.setColor(getColor());
//Check if it is filled
if (filled()) {
g.fillRect(getUpperLeftX(), getUpperLeftY(), getWidth(), getHeight());
}
else
{
g.drawRect(getUpperLeftX(), getUpperLeftY(), getWidth(), getHeight());
}
}
} | 589 | 0.662139 | 0.648557 | 32 | 17.375 | 23.634918 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.78125 | false | false | 2 |
8534b2f5c848b15578a9069c06e0ae604c00766d | 29,145,648,113,132 | f2b89d70649759fd0f6239aa49df1e80e780ad98 | /src/main/java/com/hogwartsRules/api/repositories/TestVaritaRepository.java | 7086777732832e14658ad0024eff3c0181514ad0 | [] | no_license | mikelape11/HogwartsRulesAPI | https://github.com/mikelape11/HogwartsRulesAPI | 7627e378ed4302c54211bfa41b5bcbd7a3a8c378 | 92e06523bb7005be3bb43b1b1d324fe34b507e03 | refs/heads/main | 2023-04-25T05:36:14.007000 | 2021-05-13T16:19:05 | 2021-05-13T16:19:05 | 347,921,878 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hogwartsRules.api.repositories;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.hogwartsRules.api.models.Test;
import com.hogwartsRules.api.models.TestVarita;
public interface TestVaritaRepository extends MongoRepository<TestVarita, String> {
TestVarita findTop1ByOrderByNumPreguntaDesc();
List<TestVarita> findByOrderByNumPreguntaAsc();
TestVarita findByNumPregunta(int numero);
}
| UTF-8 | Java | 459 | java | TestVaritaRepository.java | Java | [] | null | [] | package com.hogwartsRules.api.repositories;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.hogwartsRules.api.models.Test;
import com.hogwartsRules.api.models.TestVarita;
public interface TestVaritaRepository extends MongoRepository<TestVarita, String> {
TestVarita findTop1ByOrderByNumPreguntaDesc();
List<TestVarita> findByOrderByNumPreguntaAsc();
TestVarita findByNumPregunta(int numero);
}
| 459 | 0.836601 | 0.834423 | 18 | 24.5 | 26.951088 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 2 |
a76d448d78f68d7ee41d481959234100e89b54d8 | 31,447,750,555,572 | a41635e3b6a500f64365e79a389b3d997824c138 | /src/main/java/com/markdown/api/vo/PicVO.java | 6107312ab98cfb7f9d9016208766a99a1ce0083e | [] | no_license | melodyjerry/markdown-nice-api | https://github.com/melodyjerry/markdown-nice-api | 19d85c0fd1e0c35ae44d6c6b0f498dac989afb89 | 721174b61db24d7840c5748211826a027ef889f9 | refs/heads/master | 2021-01-09T14:10:22.030000 | 2019-12-27T14:04:07 | 2019-12-27T14:04:07 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.markdown.api.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @author lirui
*/
@Data
@ApiModel(description = "图床返回模型")
public class PicVO {
@ApiModelProperty(value = "图片地址")
String url;
}
| UTF-8 | Java | 302 | java | PicVO.java | Java | [
{
"context": "ModelProperty;\nimport lombok.Data;\n\n/**\n * @author lirui\n */\n@Data\n@ApiModel(description = \"图床返回模型\")\npubli",
"end": 159,
"score": 0.9993863105773926,
"start": 154,
"tag": "USERNAME",
"value": "lirui"
}
] | null | [] | package com.markdown.api.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @author lirui
*/
@Data
@ApiModel(description = "图床返回模型")
public class PicVO {
@ApiModelProperty(value = "图片地址")
String url;
}
| 302 | 0.72695 | 0.72695 | 16 | 16.625 | 15.483358 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3125 | false | false | 2 |
0a4b77a6d937d114e967842f08c541cc9406baa2 | 644,245,146,800 | 5b7b137f0b7c79a45bddd67c57861d0c8b60330f | /Server/GenerateClient/src/main/java/Managers/GenerateManager.java | 1cbd720c656842d6e0522fcaf39255d82590fca2 | [] | no_license | abcdaramgi/90kg | https://github.com/abcdaramgi/90kg | 39286a655e5395053f0753a5c98a19db5816f46a | 07bc7b0aa89e036a9975974e832268bc6549a00e | refs/heads/master | 2023-07-16T06:31:58.427000 | 2021-09-06T08:50:31 | 2021-09-06T08:50:31 | 383,513,066 | 3 | 2 | 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 Managers;
import Network.ClientSocket;
import Util.Debug;
import Data.MatchingCondition;
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.ArrayList;
import org.json.JSONObject;
/**
*
* @author ssy02
*/
public class GenerateManager {
int numberOfClient;
boolean premium = false;
ArrayList<ClientSocket> clients;
public GenerateManager() {
clients = ClientSocketManager.getInstance().clients;
}
public void matching() {
System.out.println("매칭을 진행할 클라이언트 수를 입력하세요.");
int numOfMatchingClient = getInteger();
for (int i = 0; i < numOfMatchingClient; i++) {
String matchingCondition = setMatchingCondition();
sendFrom(i, matchingCondition, "###");
}
}
public String setMatchingCondition() {
System.out.println("매칭 조건을 입력하세요. ");
System.out.println("1. random ");
System.out.println("2. age");
System.out.println("3. gender");
int matchingCondition = getInteger();
switch (matchingCondition) {
case 1:
return "random";
case 2:
// 10 ~ 20
System.out.println("최소 나이");
int minAge = getInteger();
System.out.println("최대 나이");
int maxAge = getInteger();
return "age/" + minAge + "/" + maxAge;
case 3:
// F : 여자 또는 M : 남자
String gender = getString();
return "gender/" + gender;
default:
return "random";
}
}
public void setUser() {
System.out.println("세팅할 클라이언트 인덱스를 입력하세요.");
int clientIdx = getInteger();
System.out.print("user id : ");
String userId = getString();
System.out.print("nickname : ");
String nickname = getString();
}
public void setTargetClient() {
System.out.println("메시지를 보낼 클라이언트 인덱스를 입력하세요.");
int targetClientIdx = getInteger();
String message = setMessage();
sendFrom(targetClientIdx, message, "");
}
public void sendFrom(int idx, String msg, String type) {
ClientSocket cs = ClientSocketManager.getInstance().clients.get(idx);
String clientId = cs.getUser().getId();
String message = type + clientId + ":" + msg + type;
Debug.log(message);
cs.getWriter().println(message);
}
public String setMessage() {
System.out.println("메시지를 입력하세요.");
String message = getString();
return message;
}
public void IsPremium(boolean premium) { // ~~premium을 봉인해제하면 프리미엄을 true로 바꿔저서 신호를 준다
// if(true){ //premium을 봉인해제 하는 조건 : premium매칭을 하시겠습니까?에서 확인을 누르면
// //this.premium = true;
// MatchingCondition mc = new MatchingCondition();
// mc.setCondition();
// mc.setMinAge();
// mc.setMaxAge();
// mc.setGender();
// mc.setUniv();
// mc.setMajor();
// }
// else
// this.premium = false;
}
public void match(){
}
public void matchAllClient() {
for (ClientSocket client : clients) {
client.match();
}
}
public void setNumOfClients() {
System.out.println("클라이언트 수를 입력하세요.");
numberOfClient = getInteger();
for (int i = 0; i < numberOfClient; i++) {
ClientSocket cs = new ClientSocket();
ClientSocketManager.getInstance().add(cs);
}
}
// ------------------------------------------------------------------------//
//
// ------------------------------------------------------------------------//
public static int getInteger() {
int input = 0;
while (true) {
try {
Scanner sc = new Scanner(System.in);
input = sc.nextInt();
break;
} catch (InputMismatchException exception) {
System.out.println("정수만 입력 가능합니다..");
}
}
return input;
}
// ------------------------------------------------------------------------//
//
// ------------------------------------------------------------------------//
private String getString() {
String input = "";
while (true) {
try {
Scanner sc = new Scanner(System.in);
input = sc.nextLine();
break;
} catch (Exception exception) {
exception.printStackTrace();
}
}
return input;
}
}
| UTF-8 | Java | 5,158 | java | GenerateManager.java | Java | [
{
"context": "st;\nimport org.json.JSONObject;\n\n/**\n *\n * @author ssy02\n */\n\npublic class GenerateManager {\n int numbe",
"end": 431,
"score": 0.9994632601737976,
"start": 426,
"tag": "USERNAME",
"value": "ssy02"
}
] | 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 Managers;
import Network.ClientSocket;
import Util.Debug;
import Data.MatchingCondition;
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.ArrayList;
import org.json.JSONObject;
/**
*
* @author ssy02
*/
public class GenerateManager {
int numberOfClient;
boolean premium = false;
ArrayList<ClientSocket> clients;
public GenerateManager() {
clients = ClientSocketManager.getInstance().clients;
}
public void matching() {
System.out.println("매칭을 진행할 클라이언트 수를 입력하세요.");
int numOfMatchingClient = getInteger();
for (int i = 0; i < numOfMatchingClient; i++) {
String matchingCondition = setMatchingCondition();
sendFrom(i, matchingCondition, "###");
}
}
public String setMatchingCondition() {
System.out.println("매칭 조건을 입력하세요. ");
System.out.println("1. random ");
System.out.println("2. age");
System.out.println("3. gender");
int matchingCondition = getInteger();
switch (matchingCondition) {
case 1:
return "random";
case 2:
// 10 ~ 20
System.out.println("최소 나이");
int minAge = getInteger();
System.out.println("최대 나이");
int maxAge = getInteger();
return "age/" + minAge + "/" + maxAge;
case 3:
// F : 여자 또는 M : 남자
String gender = getString();
return "gender/" + gender;
default:
return "random";
}
}
public void setUser() {
System.out.println("세팅할 클라이언트 인덱스를 입력하세요.");
int clientIdx = getInteger();
System.out.print("user id : ");
String userId = getString();
System.out.print("nickname : ");
String nickname = getString();
}
public void setTargetClient() {
System.out.println("메시지를 보낼 클라이언트 인덱스를 입력하세요.");
int targetClientIdx = getInteger();
String message = setMessage();
sendFrom(targetClientIdx, message, "");
}
public void sendFrom(int idx, String msg, String type) {
ClientSocket cs = ClientSocketManager.getInstance().clients.get(idx);
String clientId = cs.getUser().getId();
String message = type + clientId + ":" + msg + type;
Debug.log(message);
cs.getWriter().println(message);
}
public String setMessage() {
System.out.println("메시지를 입력하세요.");
String message = getString();
return message;
}
public void IsPremium(boolean premium) { // ~~premium을 봉인해제하면 프리미엄을 true로 바꿔저서 신호를 준다
// if(true){ //premium을 봉인해제 하는 조건 : premium매칭을 하시겠습니까?에서 확인을 누르면
// //this.premium = true;
// MatchingCondition mc = new MatchingCondition();
// mc.setCondition();
// mc.setMinAge();
// mc.setMaxAge();
// mc.setGender();
// mc.setUniv();
// mc.setMajor();
// }
// else
// this.premium = false;
}
public void match(){
}
public void matchAllClient() {
for (ClientSocket client : clients) {
client.match();
}
}
public void setNumOfClients() {
System.out.println("클라이언트 수를 입력하세요.");
numberOfClient = getInteger();
for (int i = 0; i < numberOfClient; i++) {
ClientSocket cs = new ClientSocket();
ClientSocketManager.getInstance().add(cs);
}
}
// ------------------------------------------------------------------------//
//
// ------------------------------------------------------------------------//
public static int getInteger() {
int input = 0;
while (true) {
try {
Scanner sc = new Scanner(System.in);
input = sc.nextInt();
break;
} catch (InputMismatchException exception) {
System.out.println("정수만 입력 가능합니다..");
}
}
return input;
}
// ------------------------------------------------------------------------//
//
// ------------------------------------------------------------------------//
private String getString() {
String input = "";
while (true) {
try {
Scanner sc = new Scanner(System.in);
input = sc.nextLine();
break;
} catch (Exception exception) {
exception.printStackTrace();
}
}
return input;
}
}
| 5,158 | 0.502891 | 0.499793 | 171 | 27.31579 | 21.587704 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.508772 | false | false | 2 |
6ce274b587bb6849bc4494f4573bfb7c4899ca64 | 1,563,368,104,328 | 4c3e131ada7e786a509cc67db2041f9eb242ea5b | /src/au/com/woolworths/mcr/thirdparty/datacash/hpssetup/MCRUnregisteredCardSetupRequestBean.java | 7599d3335433e3261d35d93d576e83ed6bba5707 | [] | no_license | skumarv/myrepo | https://github.com/skumarv/myrepo | 695430c116b8c811bcc3e2b5b44065b66352d792 | 63aae4851eef0fefd8793e8e46a8f788feba233e | refs/heads/master | 2016-05-31T05:42:07.098000 | 2014-08-23T14:35:16 | 2014-08-23T14:35:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (C) 2009 Woolworths Limited
*
* 1 Woolworths Way Bella Vista NSW 2153 Australia
* All rights reserved.
* This software is the confidential and proprietary information of Woolworths Limited. You shall not disclose
* such confidential information and shall use it only in accordance with the terms of the licence agreement
* you entered into with Woolworths Limited.
* No part of this document may be presented, reproduced or copied in any form or by any means (graphical,
* electronic or mechanical including photocopying, recording tape or by any information storage and
* retrieval system) without the express written permission of Woolworths Ltd.
* Unpublished work.
*/
package au.com.woolworths.mcr.thirdparty.datacash.hpssetup;
/**
* This is the Bean object class, contains the variables used for request and response
* object communicated between Application,Interface and Third party.
*
* @author 308635
* Version 1.0
*/
public class MCRUnregisteredCardSetupRequestBean {
//Privates variables of the bean
private String client;
private String password;
private String amount;
private String method;
private String pageSetId;
private String returnUrl;
private String hpsUrl;
private String sessionId;
private String datacashReference;
private String merchantReference;
private String mode;
private String reason;
private String status;
private String time;
private String currency;
private String id;
//Webpay : Tracking Order number
private String orderNbr;
//Getters and Setters for the variable
public String getClient() {
return client;
}
public void setClient(String client) {
this.client = client;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getPageSetId() {
return pageSetId;
}
public void setPageSetId(String pageSetId) {
this.pageSetId = pageSetId;
}
public String getReturnUrl() {
return returnUrl;
}
public void setReturnUrl(String returnUrl) {
this.returnUrl = returnUrl;
}
public String getHpsUrl() {
return hpsUrl;
}
public void setHpsUrl(String hpsUrl) {
this.hpsUrl = hpsUrl;
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public String getDatacashReference() {
return datacashReference;
}
public void setDatacashReference(String datacashReference) {
this.datacashReference = datacashReference;
}
public String getMerchantReference() {
return merchantReference;
}
public void setMerchantReference(String merchantReference) {
this.merchantReference = merchantReference;
}
public String getMode() {
return mode;
}
public void setMode(String mode) {
this.mode = mode;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
/**
* @return the orderNbr
*/
public String getOrderNbr() {
return orderNbr;
}
/**
* @param orderNbr the orderNbr to set
*/
public void setOrderNbr(String orderNbr) {
this.orderNbr = orderNbr;
}
}
| UTF-8 | Java | 3,973 | java | MCRUnregisteredCardSetupRequestBean.java | Java | [
{
"context": "cation,Interface and Third party.\r\n *\r\n * @author 308635\r\n * Version 1.0\r\n */ \r\npublic class",
"end": 960,
"score": 0.9995324015617371,
"start": 954,
"tag": "USERNAME",
"value": "308635"
}
] | null | [] | /*
* Copyright (C) 2009 Woolworths Limited
*
* 1 Woolworths Way Bella Vista NSW 2153 Australia
* All rights reserved.
* This software is the confidential and proprietary information of Woolworths Limited. You shall not disclose
* such confidential information and shall use it only in accordance with the terms of the licence agreement
* you entered into with Woolworths Limited.
* No part of this document may be presented, reproduced or copied in any form or by any means (graphical,
* electronic or mechanical including photocopying, recording tape or by any information storage and
* retrieval system) without the express written permission of Woolworths Ltd.
* Unpublished work.
*/
package au.com.woolworths.mcr.thirdparty.datacash.hpssetup;
/**
* This is the Bean object class, contains the variables used for request and response
* object communicated between Application,Interface and Third party.
*
* @author 308635
* Version 1.0
*/
public class MCRUnregisteredCardSetupRequestBean {
//Privates variables of the bean
private String client;
private String password;
private String amount;
private String method;
private String pageSetId;
private String returnUrl;
private String hpsUrl;
private String sessionId;
private String datacashReference;
private String merchantReference;
private String mode;
private String reason;
private String status;
private String time;
private String currency;
private String id;
//Webpay : Tracking Order number
private String orderNbr;
//Getters and Setters for the variable
public String getClient() {
return client;
}
public void setClient(String client) {
this.client = client;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getPageSetId() {
return pageSetId;
}
public void setPageSetId(String pageSetId) {
this.pageSetId = pageSetId;
}
public String getReturnUrl() {
return returnUrl;
}
public void setReturnUrl(String returnUrl) {
this.returnUrl = returnUrl;
}
public String getHpsUrl() {
return hpsUrl;
}
public void setHpsUrl(String hpsUrl) {
this.hpsUrl = hpsUrl;
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public String getDatacashReference() {
return datacashReference;
}
public void setDatacashReference(String datacashReference) {
this.datacashReference = datacashReference;
}
public String getMerchantReference() {
return merchantReference;
}
public void setMerchantReference(String merchantReference) {
this.merchantReference = merchantReference;
}
public String getMode() {
return mode;
}
public void setMode(String mode) {
this.mode = mode;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
/**
* @return the orderNbr
*/
public String getOrderNbr() {
return orderNbr;
}
/**
* @param orderNbr the orderNbr to set
*/
public void setOrderNbr(String orderNbr) {
this.orderNbr = orderNbr;
}
}
| 3,973 | 0.706771 | 0.702492 | 158 | 23.145569 | 21.691107 | 110 | true | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.411392 | false | false | 2 |
d12053743d9694d00dcd27fa45ea926dfa045d6a | 18,769,007,124,964 | d8755697c9a4e515729c87404fbc858e7007d374 | /src/test/java/adsim/core/RelationWeightManagerTest.java | f2d5ec898cb58d4e23d15b5ff29ae7467b0b6881 | [] | no_license | kanosaki/adhock-simulator | https://github.com/kanosaki/adhock-simulator | dc5ef5eb566e52ea27e1966ae8783dfa2bff182c | 87b9f49b98e60fd3b79595260e12d8fa2abe2cf7 | refs/heads/master | 2020-04-26T14:47:01.720000 | 2012-12-13T12:23:56 | 2012-12-13T12:23:56 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package adsim.core;
import java.util.LinkedList;
import lombok.*;
import static org.junit.Assert.*;
import org.junit.Test;
import adsim.core.Message.TellNeighbors;
import adsim.core.Message.TellNeighbors.Entry;
public class RelationWeightManagerTest {
public TellNeighbors createPacket(NodeID id, int weight, long timestamp) {
val entries = new LinkedList<TellNeighbors.Entry>();
entries.add(new Entry(id, weight, new LinkedList<Long>(), timestamp));
return new TellNeighbors(entries);
}
@Test
public void test_update() {
val rwm = new RelationWeightManager.Recent(10);
val id = new NodeID();
val pack1 = createPacket(id, 3, 1);
val pack2 = createPacket(id, 4, 2);
rwm.push(pack1);
rwm.push(pack2);
assertEquals(4, rwm.get(id));
}
@Test
public void test_ignore() {
val rwm = new RelationWeightManager.Recent(10);
val id = new NodeID();
val pack1 = createPacket(id, 3, 2);
val pack2 = createPacket(id, 4, 1);
rwm.push(pack1);
rwm.push(pack2);
assertEquals(3, rwm.get(id));
}
@Test
public void test_export() {
val rwm = new RelationWeightManager.Recent(10);
val id1 = new NodeID();
val id2 = new NodeID();
val pack1 = createPacket(id1, 3, 2);
val pack2 = createPacket(id2, 4, 1);
rwm.push(pack1);
rwm.push(pack2);
val result = (TellNeighbors) rwm.export(null);
for (val entry : result.getEntries()) {
if (entry.getSender().equals(id1)) {
assertEquals(2, entry.getWeight());
assertEquals(2, entry.getTimestamp());
} else if (entry.getSender().equals(id2)) {
assertEquals(3, entry.getWeight());
assertEquals(1, entry.getTimestamp());
}
}
}
@Test
public void test_collect() {
val rwm = new RelationWeightManager.Recent(2);
val id1 = new NodeID();
val id2 = new NodeID();
val id3 = new NodeID();
rwm.push(createPacket(id1, 1, 1));
rwm.push(createPacket(id3, 3, 3));
rwm.push(createPacket(id2, 2, 2));
assertEquals(3, rwm.get(id3));
assertEquals(2, rwm.get(id2));
assertEquals(RelationWeightManager.DEFAULT_WEIGHT, rwm.get(id1));
}
}
| UTF-8 | Java | 2,390 | java | RelationWeightManagerTest.java | Java | [] | null | [] | package adsim.core;
import java.util.LinkedList;
import lombok.*;
import static org.junit.Assert.*;
import org.junit.Test;
import adsim.core.Message.TellNeighbors;
import adsim.core.Message.TellNeighbors.Entry;
public class RelationWeightManagerTest {
public TellNeighbors createPacket(NodeID id, int weight, long timestamp) {
val entries = new LinkedList<TellNeighbors.Entry>();
entries.add(new Entry(id, weight, new LinkedList<Long>(), timestamp));
return new TellNeighbors(entries);
}
@Test
public void test_update() {
val rwm = new RelationWeightManager.Recent(10);
val id = new NodeID();
val pack1 = createPacket(id, 3, 1);
val pack2 = createPacket(id, 4, 2);
rwm.push(pack1);
rwm.push(pack2);
assertEquals(4, rwm.get(id));
}
@Test
public void test_ignore() {
val rwm = new RelationWeightManager.Recent(10);
val id = new NodeID();
val pack1 = createPacket(id, 3, 2);
val pack2 = createPacket(id, 4, 1);
rwm.push(pack1);
rwm.push(pack2);
assertEquals(3, rwm.get(id));
}
@Test
public void test_export() {
val rwm = new RelationWeightManager.Recent(10);
val id1 = new NodeID();
val id2 = new NodeID();
val pack1 = createPacket(id1, 3, 2);
val pack2 = createPacket(id2, 4, 1);
rwm.push(pack1);
rwm.push(pack2);
val result = (TellNeighbors) rwm.export(null);
for (val entry : result.getEntries()) {
if (entry.getSender().equals(id1)) {
assertEquals(2, entry.getWeight());
assertEquals(2, entry.getTimestamp());
} else if (entry.getSender().equals(id2)) {
assertEquals(3, entry.getWeight());
assertEquals(1, entry.getTimestamp());
}
}
}
@Test
public void test_collect() {
val rwm = new RelationWeightManager.Recent(2);
val id1 = new NodeID();
val id2 = new NodeID();
val id3 = new NodeID();
rwm.push(createPacket(id1, 1, 1));
rwm.push(createPacket(id3, 3, 3));
rwm.push(createPacket(id2, 2, 2));
assertEquals(3, rwm.get(id3));
assertEquals(2, rwm.get(id2));
assertEquals(RelationWeightManager.DEFAULT_WEIGHT, rwm.get(id1));
}
}
| 2,390 | 0.586611 | 0.561506 | 78 | 29.641026 | 20.554478 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 2 |
7e363fb7b095aac4db02f00ea05f24dc2148377d | 23,656,679,888,097 | a049737e6b11b9ac8ec1f96330de9ffe6337357b | /projetInfo_2018_KARIMOU_PRUDHOMME/workspace/GestionHotel/src/reservations/PannReservationChambre.java | 59dc2cd595b05a13482e809d4515291b3983585e | [
"Apache-2.0"
] | permissive | FionaPrudhomme/Projet_Info2018_Karimou_Prudhomme | https://github.com/FionaPrudhomme/Projet_Info2018_Karimou_Prudhomme | d5af1e21df7e7a6567fc478bb869f80844c23551 | 8d2a03636488f033ec4436c49dcc01e8e0c903cc | refs/heads/master | 2020-03-17T18:36:45.142000 | 2020-02-20T15:07:36 | 2020-02-20T15:07:36 | 133,828,156 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package reservations;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import connexionBDD.Connexion;
import panneau_principal.PanneauPrincipal;
/**
* Classe permettant d'effectuer une réservation d'une chambre
*
* @version 1.0
* @author Prud'homme Fiona, Karimou Samira
*/
public class PannReservationChambre extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
// lignes indiquant les details de chaque reservation
private JLabel labelResa = new JLabel("Numéro de réservation: ");
private JLabel labelClient = new JLabel("Identifiant du client: ");
private JLabel labelChambre = new JLabel("Numéro Chambre: ");
private JLabel labelPersonnel = new JLabel("Identifiant Personnel: ");
private JLabel labelDate1 = new JLabel("Début de la Réservation: ");
private JLabel labelDate2 = new JLabel("Fin de la réservation: ");
private JLabel labelOptions = new JLabel("Options: ");
private JLabel labelNuit = new JLabel("Nombre de nuit: ");
private JTextField textResa = new JTextField(20);
private JTextField textClient = new JTextField(20);
private JTextField textChambre = new JTextField(20);
private JTextField textPersonnel = new JTextField(20);
private JTextField textDate1 = new JTextField(20);
private JTextField textDate2 = new JTextField(20);
private JTextField textOptions = new JTextField(20);
private JTextField textNuit = new JTextField(20);
private JButton button1 = new JButton("Réserver chambre");
private JButton button2 = new JButton("Menu");
private JPanel pan = new JPanel(new GridBagLayout());//nouvelle fenetre
ResultSet resultat = null;
public PannReservationChambre() {
//initialisation
this.init();
}
public void init(){
//Affichage
GridBagConstraints constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.WEST;
constraints.insets = new Insets(10, 10, 10, 10);
constraints.gridx = 0;
constraints.gridy = 0;
pan.add(labelResa, constraints);
constraints.gridx = 1;
pan.add(textResa, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
pan.add(labelClient, constraints);
constraints.gridx = 1;
pan.add(textClient, constraints);
constraints.gridx = 0;
constraints.gridy = 2;
pan.add(labelChambre, constraints);
constraints.gridx = 1;
pan.add(textChambre, constraints);
constraints.gridx = 0;
constraints.gridy = 3;
pan.add(labelPersonnel, constraints);
constraints.gridx = 1;
pan.add(textPersonnel, constraints);
constraints.gridx = 0;
constraints.gridy = 4;
pan.add(labelDate1, constraints);
constraints.gridx = 1;
pan.add(textDate1, constraints);
constraints.gridx = 0;
constraints.gridy = 5;
pan.add(labelDate2, constraints);
constraints.gridx = 1;
pan.add(textDate2, constraints);
constraints.gridx = 0;
constraints.gridy = 6;
pan.add(labelOptions, constraints);
constraints.gridx = 1;
pan.add(textOptions, constraints);
constraints.gridx = 0;
constraints.gridy = 7;
pan.add(labelNuit, constraints);
constraints.gridx = 1;
pan.add(textNuit, constraints);
button1.addActionListener(this);
constraints.gridx = 1;
constraints.gridy = 8;
constraints.gridwidth = 2;
constraints.anchor = GridBagConstraints.EAST;
pan.add(button1, constraints);
button2.addActionListener(this);
constraints.gridx = 0;
constraints.gridy = 8;
constraints.gridwidth = 2;
constraints.anchor = GridBagConstraints.WEST;
pan.add(button2, constraints);
add(pan);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button1) {
try {
//reservation d'une chambre
String idC = textClient.getText();
String idPersonnel = textPersonnel.getText();
String numCh = textChambre.getText();
String numResa = textResa.getText();
String date1 = textDate1.getText();
String date2 = textDate2.getText();
String options = textOptions.getText();
String nbNuit = textNuit.getText();
int idClient = Integer.parseInt(idC);
int idPerso = Integer.parseInt(idPersonnel);
int numReservation = Integer.parseInt(numResa);
int numChambre = Integer.parseInt(numCh);
int nbN = Integer.parseInt(nbNuit);
PreparedStatement preparedState = Connexion.getInstance().prepareStatement("SELECT num_resa FROM resa_chambre WHERE num_resa ='"+numReservation+"'");
resultat = preparedState.executeQuery();
if(resultat.next()) {
JOptionPane.showMessageDialog(null,"Numéro de réservation déjà utilisé ","Error",1);
}
else {
PreparedStatement preparedState2 = Connexion.getInstance().prepareStatement("INSERT INTO resa_chambre(num_resa,num_chambre,id_client,id_personnel,date_debut,date_fin,options,nb_nuits) VALUES (?,?,?,?,?,?,?,?)");
preparedState2.setInt(1, numReservation);
preparedState2.setInt(2, numChambre);
preparedState2.setInt(3, idClient);
preparedState2.setInt(4, idPerso);
preparedState2.setString(5, date1);
preparedState2.setString(6, date2);
preparedState2.setString(7, options);
preparedState2.setInt(8, nbN);
preparedState2.executeUpdate();
JOptionPane.showMessageDialog(null,"Ajout réussi ","Success",JOptionPane.PLAIN_MESSAGE);
dispose();
PanneauPrincipal fenetre = new PanneauPrincipal();
fenetre.setVisible(true);
}
}
catch (Exception e3) {
e3.printStackTrace();
}
}
if(e.getSource() == button2) {
dispose();
PanneauPrincipal pann = new PanneauPrincipal();
pann.setVisible(true);
}
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
ex.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new PannReservationChambre().setVisible(true);
}
});
}
}
| UTF-8 | Java | 7,180 | java | PannReservationChambre.java | Java | [
{
"context": "servation d'une chambre\n*\n* @version 1.0\n* @author Prud'homme Fiona, Karimou Samira\n*/\npublic class PannReservationCh",
"end": 673,
"score": 0.9998797178268433,
"start": 657,
"tag": "NAME",
"value": "Prud'homme Fiona"
},
{
"context": "ambre\n*\n* @version 1.0\n* @a... | null | [] | package reservations;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import connexionBDD.Connexion;
import panneau_principal.PanneauPrincipal;
/**
* Classe permettant d'effectuer une réservation d'une chambre
*
* @version 1.0
* @author <NAME>, <NAME>
*/
public class PannReservationChambre extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
// lignes indiquant les details de chaque reservation
private JLabel labelResa = new JLabel("Numéro de réservation: ");
private JLabel labelClient = new JLabel("Identifiant du client: ");
private JLabel labelChambre = new JLabel("Numéro Chambre: ");
private JLabel labelPersonnel = new JLabel("Identifiant Personnel: ");
private JLabel labelDate1 = new JLabel("Début de la Réservation: ");
private JLabel labelDate2 = new JLabel("Fin de la réservation: ");
private JLabel labelOptions = new JLabel("Options: ");
private JLabel labelNuit = new JLabel("Nombre de nuit: ");
private JTextField textResa = new JTextField(20);
private JTextField textClient = new JTextField(20);
private JTextField textChambre = new JTextField(20);
private JTextField textPersonnel = new JTextField(20);
private JTextField textDate1 = new JTextField(20);
private JTextField textDate2 = new JTextField(20);
private JTextField textOptions = new JTextField(20);
private JTextField textNuit = new JTextField(20);
private JButton button1 = new JButton("Réserver chambre");
private JButton button2 = new JButton("Menu");
private JPanel pan = new JPanel(new GridBagLayout());//nouvelle fenetre
ResultSet resultat = null;
public PannReservationChambre() {
//initialisation
this.init();
}
public void init(){
//Affichage
GridBagConstraints constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.WEST;
constraints.insets = new Insets(10, 10, 10, 10);
constraints.gridx = 0;
constraints.gridy = 0;
pan.add(labelResa, constraints);
constraints.gridx = 1;
pan.add(textResa, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
pan.add(labelClient, constraints);
constraints.gridx = 1;
pan.add(textClient, constraints);
constraints.gridx = 0;
constraints.gridy = 2;
pan.add(labelChambre, constraints);
constraints.gridx = 1;
pan.add(textChambre, constraints);
constraints.gridx = 0;
constraints.gridy = 3;
pan.add(labelPersonnel, constraints);
constraints.gridx = 1;
pan.add(textPersonnel, constraints);
constraints.gridx = 0;
constraints.gridy = 4;
pan.add(labelDate1, constraints);
constraints.gridx = 1;
pan.add(textDate1, constraints);
constraints.gridx = 0;
constraints.gridy = 5;
pan.add(labelDate2, constraints);
constraints.gridx = 1;
pan.add(textDate2, constraints);
constraints.gridx = 0;
constraints.gridy = 6;
pan.add(labelOptions, constraints);
constraints.gridx = 1;
pan.add(textOptions, constraints);
constraints.gridx = 0;
constraints.gridy = 7;
pan.add(labelNuit, constraints);
constraints.gridx = 1;
pan.add(textNuit, constraints);
button1.addActionListener(this);
constraints.gridx = 1;
constraints.gridy = 8;
constraints.gridwidth = 2;
constraints.anchor = GridBagConstraints.EAST;
pan.add(button1, constraints);
button2.addActionListener(this);
constraints.gridx = 0;
constraints.gridy = 8;
constraints.gridwidth = 2;
constraints.anchor = GridBagConstraints.WEST;
pan.add(button2, constraints);
add(pan);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button1) {
try {
//reservation d'une chambre
String idC = textClient.getText();
String idPersonnel = textPersonnel.getText();
String numCh = textChambre.getText();
String numResa = textResa.getText();
String date1 = textDate1.getText();
String date2 = textDate2.getText();
String options = textOptions.getText();
String nbNuit = textNuit.getText();
int idClient = Integer.parseInt(idC);
int idPerso = Integer.parseInt(idPersonnel);
int numReservation = Integer.parseInt(numResa);
int numChambre = Integer.parseInt(numCh);
int nbN = Integer.parseInt(nbNuit);
PreparedStatement preparedState = Connexion.getInstance().prepareStatement("SELECT num_resa FROM resa_chambre WHERE num_resa ='"+numReservation+"'");
resultat = preparedState.executeQuery();
if(resultat.next()) {
JOptionPane.showMessageDialog(null,"Numéro de réservation déjà utilisé ","Error",1);
}
else {
PreparedStatement preparedState2 = Connexion.getInstance().prepareStatement("INSERT INTO resa_chambre(num_resa,num_chambre,id_client,id_personnel,date_debut,date_fin,options,nb_nuits) VALUES (?,?,?,?,?,?,?,?)");
preparedState2.setInt(1, numReservation);
preparedState2.setInt(2, numChambre);
preparedState2.setInt(3, idClient);
preparedState2.setInt(4, idPerso);
preparedState2.setString(5, date1);
preparedState2.setString(6, date2);
preparedState2.setString(7, options);
preparedState2.setInt(8, nbN);
preparedState2.executeUpdate();
JOptionPane.showMessageDialog(null,"Ajout réussi ","Success",JOptionPane.PLAIN_MESSAGE);
dispose();
PanneauPrincipal fenetre = new PanneauPrincipal();
fenetre.setVisible(true);
}
}
catch (Exception e3) {
e3.printStackTrace();
}
}
if(e.getSource() == button2) {
dispose();
PanneauPrincipal pann = new PanneauPrincipal();
pann.setVisible(true);
}
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
ex.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new PannReservationChambre().setVisible(true);
}
});
}
}
| 7,162 | 0.64806 | 0.634106 | 237 | 29.236286 | 25.372065 | 215 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.64135 | false | false | 2 |
9679671aab73b0ac2aa755f1f6cec5ecb8874daa | 23,656,679,888,536 | f4be9a1a6be0ec1eca7dcb99a960cf47de4d8807 | /src/Persistence/FileImageLoader.java | 57a646ca9c2e31941abaf007eb2a49aa5e6bc934 | [] | no_license | jimenazo97/Imageviewer | https://github.com/jimenazo97/Imageviewer | ea5e634a12cc6defc3b4a6a2352fa478bdc70260 | 0dfbbe25575e4cfe3a653efd1d424a32b44796b3 | refs/heads/master | 2022-01-08T16:09:47.684000 | 2019-05-17T08:28:44 | 2019-05-17T08:28:44 | 115,435,244 | 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 Persistence;
import imageviewer.model.Image;
import Persistence.ImageLoader;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
/**
*
* @author Ithiel
*/
public class FileImageLoader implements ImageLoader{
private File[] files;
public FileImageLoader(File folder) {
this.files = folder.listFiles();
}
private FileFilter imageType(){
return new FileFilter(){
@Override
public boolean accept(File pathname) {
return pathname.getName().endsWith(".jpg");
}
};
}
//@Override
public Image imageAt(int i){
return new Image(){
@Override
public String name(){
return files[i].getName();
}
@Override
public InputStream stream(){
try{
return new BufferedInputStream(new FileInputStream(files[i]));
}catch(FileNotFoundException ex){
return null;
}
}
@Override
public Image next(){
//return imageAt(i == files.length-1 ? 0 : i+1);
return i == files.length - 1 ? imageAt(0):imageAt(i+1);
}
@Override
public Image prev(){
if( i == 0){
return imageAt(files.length -1);
}else{
return imageAt(i-1);
}
}
};
}
@Override
public Image load() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
} | UTF-8 | Java | 2,178 | java | FileImageLoader.java | Java | [
{
"context": "rt java.io.InputStream;\r\n \r\n /**\r\n *\r\n * @author Ithiel\r\n */\r\n public class FileImageLoader implements I",
"end": 509,
"score": 0.9987099766731262,
"start": 503,
"tag": "NAME",
"value": "Ithiel"
}
] | 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 Persistence;
import imageviewer.model.Image;
import Persistence.ImageLoader;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
/**
*
* @author Ithiel
*/
public class FileImageLoader implements ImageLoader{
private File[] files;
public FileImageLoader(File folder) {
this.files = folder.listFiles();
}
private FileFilter imageType(){
return new FileFilter(){
@Override
public boolean accept(File pathname) {
return pathname.getName().endsWith(".jpg");
}
};
}
//@Override
public Image imageAt(int i){
return new Image(){
@Override
public String name(){
return files[i].getName();
}
@Override
public InputStream stream(){
try{
return new BufferedInputStream(new FileInputStream(files[i]));
}catch(FileNotFoundException ex){
return null;
}
}
@Override
public Image next(){
//return imageAt(i == files.length-1 ? 0 : i+1);
return i == files.length - 1 ? imageAt(0):imageAt(i+1);
}
@Override
public Image prev(){
if( i == 0){
return imageAt(files.length -1);
}else{
return imageAt(i-1);
}
}
};
}
@Override
public Image load() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
} | 2,178 | 0.506428 | 0.502296 | 76 | 26.68421 | 23.021849 | 136 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.355263 | false | false | 2 |
d08b8b5b2c4e61c82b9e35a71905f97ed6550206 | 17,884,243,866,364 | 73c0a8e3b21f08e78ac939ca6da31f59bb8599e8 | /src/main/java/company/Title.java | d703c94645c3885100728aab60357bcccdfbd578 | [] | no_license | PeterJames12/JavaCourser | https://github.com/PeterJames12/JavaCourser | 35ed079d1af73a019ebc7a98c79c3de8f6673373 | c3b61ac6613f9e78d53a8520a2dce4c337bc02ab | refs/heads/master | 2021-01-19T10:45:52.097000 | 2017-03-02T21:19:06 | 2017-03-02T21:19:06 | 82,216,252 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package company;
/**
* @author Igor Gnes on 3/2/17.
*/
@Deprecated
public class Title {
public static void main(String[] args) {
Test<String, String> values = new Test<>();
values.setKey("key");
values.setValue("Value");
Test<Integer, Integer> integerValue = new Test<>();
integerValue.setKey(34);
integerValue.setValue(656);
Test<String, Integer> mix = new Test<>();
mix.setKey("Key");
mix.setValue(25332657);
printValues(values);
printValues(integerValue);
printValues(mix);
}
private static void printValues(Test<?, ?> item) {
System.out.println(item.getKey());
System.out.println(item.getValue());
}
}
| UTF-8 | Java | 749 | java | Title.java | Java | [
{
"context": "package company;\n\n/**\n * @author Igor Gnes on 3/2/17.\n */\n\n@Deprecated\npublic class Title {\n",
"end": 42,
"score": 0.9998310804367065,
"start": 33,
"tag": "NAME",
"value": "Igor Gnes"
}
] | null | [] | package company;
/**
* @author <NAME> on 3/2/17.
*/
@Deprecated
public class Title {
public static void main(String[] args) {
Test<String, String> values = new Test<>();
values.setKey("key");
values.setValue("Value");
Test<Integer, Integer> integerValue = new Test<>();
integerValue.setKey(34);
integerValue.setValue(656);
Test<String, Integer> mix = new Test<>();
mix.setKey("Key");
mix.setValue(25332657);
printValues(values);
printValues(integerValue);
printValues(mix);
}
private static void printValues(Test<?, ?> item) {
System.out.println(item.getKey());
System.out.println(item.getValue());
}
}
| 746 | 0.580774 | 0.558077 | 38 | 18.710526 | 19.139252 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 2 |
490e3d109a458523628b850d8438b4c68eff4984 | 34,986,803,596,293 | 27e63cb2e1880561acfca5882d44a55be597a597 | /src/main/java/com/ubs/opsit/interviews/BerlinClock.java | 0631edbb2743c5187405ab69c34254edd0a14615 | [] | no_license | gmisra16/jbc | https://github.com/gmisra16/jbc | eda5d5a3c293d5a68f6c2e62e109797d80da8dcd | 7a52e4a532896a1515904e0fe8daa3cd4ae02680 | refs/heads/master | 2021-01-01T17:45:48.402000 | 2017-07-24T08:39:38 | 2017-07-24T08:39:38 | 98,151,039 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ubs.opsit.interviews;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
/**
* BerlinClock
*/
public class BerlinClock {
private static final Logger LOG = LoggerFactory.getLogger(BerlinClock.class);
private char sec = 'O';
private final char[] hr_5 = new char[4];
private final char[] hr_1 = new char[4];
private final char[] min_5 = new char[11];
private final char[] min_1 = new char[4];
/**
* @param time - The 24 hour time in the format of HH:MM:SS
*/
BerlinClock(String time) {
reset();
validateAndInit(time);
LOG.debug("Creation done");
}
/**
* @param hours - an int representing Hours
* @param minutes - an int representing Minutes
* @param seconds - an int representing Seconds
*/
private void init(int hours, int minutes, int seconds) {
this.sec = (seconds % 2 == 0) ? 'Y' : 'O';
switchOn(hr_5, hours / 5, 'R');
switchOn(hr_1, hours % 5, 'R');
switchOn(min_5, minutes / 5, 'Y');
yellowToRed(min_5);
switchOn(min_1, minutes % 5, 'Y');
}
private void reset() {
Arrays.fill(hr_5, 'O');
Arrays.fill(hr_1, 'O');
Arrays.fill(min_5, 'O');
Arrays.fill(min_1, 'O');
LOG.debug("reset done");
}
private void validateAndInit(String time) {
if (time == null) throw new NullPointerException("Cannot convert null time");
String[] times = time.split(":", 3);
if (times.length != 3) throw new IllegalArgumentException("The 24 hour time in the format of HH:MM:SS");
int hours;
int minutes;
int seconds;
try {
hours = Integer.parseInt(times[0]);
minutes = Integer.parseInt(times[1]);
seconds = Integer.parseInt(times[2]);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("The 24 hour time in the format of HH:MM:SS");
}
//24:00:00 is valid time
if (!"24:00:00".equals(time)){
if (hours < 0 || hours > 23) throw new IllegalArgumentException("Valid Hours 0-23. Actual " + hours);
if (minutes < 0 || minutes > 59) throw new IllegalArgumentException("Valid Minutes 0-59. Actual " + minutes);
if (seconds < 0 || seconds > 59) throw new IllegalArgumentException("Valid Seconds 0-59. Actual " + seconds);
}
LOG.debug("Validation done, calling init");
init(hours, minutes, seconds);
LOG.debug("init done");
}
/**
* Creates a string for each row of the berlin clock.
*
*/
private void switchOn(char[] arr, int litLights, char lampType) {
for (int i = 0; i < litLights; i++) {
arr[i] = lampType;
}
}
private void yellowToRed(char[] chars) {
for (int i = 0; i < chars.length; i++) {
if ((i == 2 || i == 5 || i == 8) && chars[i] == 'Y') chars[i] = 'R';
}
}
@Override
public String toString() {
return this.sec+System.lineSeparator()
+new String(hr_5)+System.lineSeparator()
+new String(hr_1)+System.lineSeparator()
+new String(min_5)+System.lineSeparator()
+new String(min_1);
}
/*public static void main(String ... args){
System.out.println(new BerlinClock("13:17:01").toString());
}*/
} | UTF-8 | Java | 3,451 | java | BerlinClock.java | Java | [] | null | [] | package com.ubs.opsit.interviews;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
/**
* BerlinClock
*/
public class BerlinClock {
private static final Logger LOG = LoggerFactory.getLogger(BerlinClock.class);
private char sec = 'O';
private final char[] hr_5 = new char[4];
private final char[] hr_1 = new char[4];
private final char[] min_5 = new char[11];
private final char[] min_1 = new char[4];
/**
* @param time - The 24 hour time in the format of HH:MM:SS
*/
BerlinClock(String time) {
reset();
validateAndInit(time);
LOG.debug("Creation done");
}
/**
* @param hours - an int representing Hours
* @param minutes - an int representing Minutes
* @param seconds - an int representing Seconds
*/
private void init(int hours, int minutes, int seconds) {
this.sec = (seconds % 2 == 0) ? 'Y' : 'O';
switchOn(hr_5, hours / 5, 'R');
switchOn(hr_1, hours % 5, 'R');
switchOn(min_5, minutes / 5, 'Y');
yellowToRed(min_5);
switchOn(min_1, minutes % 5, 'Y');
}
private void reset() {
Arrays.fill(hr_5, 'O');
Arrays.fill(hr_1, 'O');
Arrays.fill(min_5, 'O');
Arrays.fill(min_1, 'O');
LOG.debug("reset done");
}
private void validateAndInit(String time) {
if (time == null) throw new NullPointerException("Cannot convert null time");
String[] times = time.split(":", 3);
if (times.length != 3) throw new IllegalArgumentException("The 24 hour time in the format of HH:MM:SS");
int hours;
int minutes;
int seconds;
try {
hours = Integer.parseInt(times[0]);
minutes = Integer.parseInt(times[1]);
seconds = Integer.parseInt(times[2]);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("The 24 hour time in the format of HH:MM:SS");
}
//24:00:00 is valid time
if (!"24:00:00".equals(time)){
if (hours < 0 || hours > 23) throw new IllegalArgumentException("Valid Hours 0-23. Actual " + hours);
if (minutes < 0 || minutes > 59) throw new IllegalArgumentException("Valid Minutes 0-59. Actual " + minutes);
if (seconds < 0 || seconds > 59) throw new IllegalArgumentException("Valid Seconds 0-59. Actual " + seconds);
}
LOG.debug("Validation done, calling init");
init(hours, minutes, seconds);
LOG.debug("init done");
}
/**
* Creates a string for each row of the berlin clock.
*
*/
private void switchOn(char[] arr, int litLights, char lampType) {
for (int i = 0; i < litLights; i++) {
arr[i] = lampType;
}
}
private void yellowToRed(char[] chars) {
for (int i = 0; i < chars.length; i++) {
if ((i == 2 || i == 5 || i == 8) && chars[i] == 'Y') chars[i] = 'R';
}
}
@Override
public String toString() {
return this.sec+System.lineSeparator()
+new String(hr_5)+System.lineSeparator()
+new String(hr_1)+System.lineSeparator()
+new String(min_5)+System.lineSeparator()
+new String(min_1);
}
/*public static void main(String ... args){
System.out.println(new BerlinClock("13:17:01").toString());
}*/
} | 3,451 | 0.563315 | 0.539554 | 107 | 31.261683 | 28.03047 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.728972 | false | false | 2 |
247081bd5a4aca35e33856724982b239b8f87050 | 5,042,291,649,685 | 8918678b9b478a295e71336e976c67afe4480f2f | /Multiple.java | c48a27a3f05d14ff86cc5e6028b318ed1b146038 | [] | no_license | EzenwaOpara/CIE-1 | https://github.com/EzenwaOpara/CIE-1 | c8d89515c77223ecb2e1c182c80b73cac5deabed | b37ef6ecd7d6c9beed381e32efb665ecf9f97021 | refs/heads/master | 2023-05-12T13:39:52.562000 | 2020-09-21T11:30:13 | 2020-09-21T11:30:13 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
public class Multiple {
public static void main(String...args) {
Scanner enter = new Scanner(System.in);
System.out.println("input the two integers numbers");
System.out.print("input for a: ");
int a = enter.nextInt();
System.out.print("input for b: ");
int b = enter.nextInt();
if (a % b == 1 && b % a ==1)
System.out.println("Is not a multiple of this number");
if (a % b == 2 && b % a == 2)
System.out.println("is a multiple of this number");
}
}
| UTF-8 | Java | 593 | java | Multiple.java | Java | [] | null | [] | import java.util.Scanner;
public class Multiple {
public static void main(String...args) {
Scanner enter = new Scanner(System.in);
System.out.println("input the two integers numbers");
System.out.print("input for a: ");
int a = enter.nextInt();
System.out.print("input for b: ");
int b = enter.nextInt();
if (a % b == 1 && b % a ==1)
System.out.println("Is not a multiple of this number");
if (a % b == 2 && b % a == 2)
System.out.println("is a multiple of this number");
}
}
| 593 | 0.53457 | 0.527825 | 16 | 35.0625 | 19.523924 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5625 | false | false | 2 |
c6366c1b85b20e751f271fac5e577a6d102ef950 | 36,146,444,774,219 | e3dd92c2712f3daa8e6a37fbdb6978d954891f02 | /java/src/TheDoors.java | 255aaedd0d7536cf9a673ffe4e176d3e6b295c50 | [] | no_license | aahnn/comp-problems | https://github.com/aahnn/comp-problems | 7e12c84cce397cbc5f0ff94d3ca8a068e6aa3f6a | 77a49195a41645d7550af2c5e333a21462c37bb2 | refs/heads/master | 2020-03-27T16:11:18.534000 | 2019-09-10T19:29:41 | 2019-09-10T19:29:41 | 146,764,774 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.*;
public class TheDoors {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int numDoors = in.nextInt();
int bestLeft = -1;
int bestRight = -1;
for (int i = 0; i < numDoors; i++) {
if (in.nextInt() == 0) {
bestLeft = i;
}
else {
bestRight = i;
}
}
System.out.println(Math.min(bestLeft, bestRight) + 1);
}
}
| UTF-8 | Java | 500 | java | TheDoors.java | Java | [] | null | [] | import java.util.*;
public class TheDoors {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int numDoors = in.nextInt();
int bestLeft = -1;
int bestRight = -1;
for (int i = 0; i < numDoors; i++) {
if (in.nextInt() == 0) {
bestLeft = i;
}
else {
bestRight = i;
}
}
System.out.println(Math.min(bestLeft, bestRight) + 1);
}
}
| 500 | 0.458 | 0.448 | 21 | 22.809525 | 17.075794 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52381 | false | false | 2 |
a3983b3ac933dc1a7201c8e9d5c91b80e5361443 | 14,680,198,278,252 | 427d849eb7dde7e381836433fd200b8ae15eb5cf | /src/test/java/utilTest/M22.java | b681f84d8f7c18d43cf199657da04ab9fc79da5e | [] | no_license | turtlerrrrr/pmt | https://github.com/turtlerrrrr/pmt | 8ee7aecd6fb67120ad975f7abfa89979c9c7b3af | 250af5a1e0321821b8a5834b4a3467049712c338 | refs/heads/master | 2021-01-22T00:58:32.746000 | 2015-06-13T05:51:08 | 2015-06-13T05:51:08 | 37,358,523 | 2 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null | package utilTest;
import java.lang.reflect.Field;
import java.util.Date;
import com.sx.mmt.constants.ConfigConstants;
import com.sx.mmt.internal.util.DateTool;
import com.sx.mmt.internal.util.SimpleBytes;
public class M22 {
public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Date Dfrom=DateTool.getDateFromString("2014-10-9");
Date dTo=DateTool.getDateFromString("2014-10-10");
Date a=DateTool.getDateFromString("2014-10-10");
// System.out.println(a.after(Dfrom) && a.before(dTo));
String apn=null;
// System.out.println(apn==null?"":apn);
SimpleBytes rawValue=new SimpleBytes();
rawValue.add(new SimpleBytes((apn==null?"":apn).trim(),16,"utf-8"));
// System.out.println(rawValue);
Field field=A.class.getDeclaredField("c");
M22 m=new M22();
A testa=m.new A();
// for(int i=0;i<field.length;i++){
// System.out.print(field[i].getGenericType()+"\n");
// }
System.out.print("class java.lang.String".equals(field.getGenericType().toString())+"\n");
field.set(testa, "aa");
System.out.print(testa.getC());
}
class A{
private int a;
private boolean b;
private String c;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public boolean isB() {
return b;
}
public void setB(boolean b) {
this.b = b;
}
public String getC() {
return c;
}
public void setC(String c) {
this.c = c;
}
}
}
| UTF-8 | Java | 1,479 | java | M22.java | Java | [] | null | [] | package utilTest;
import java.lang.reflect.Field;
import java.util.Date;
import com.sx.mmt.constants.ConfigConstants;
import com.sx.mmt.internal.util.DateTool;
import com.sx.mmt.internal.util.SimpleBytes;
public class M22 {
public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Date Dfrom=DateTool.getDateFromString("2014-10-9");
Date dTo=DateTool.getDateFromString("2014-10-10");
Date a=DateTool.getDateFromString("2014-10-10");
// System.out.println(a.after(Dfrom) && a.before(dTo));
String apn=null;
// System.out.println(apn==null?"":apn);
SimpleBytes rawValue=new SimpleBytes();
rawValue.add(new SimpleBytes((apn==null?"":apn).trim(),16,"utf-8"));
// System.out.println(rawValue);
Field field=A.class.getDeclaredField("c");
M22 m=new M22();
A testa=m.new A();
// for(int i=0;i<field.length;i++){
// System.out.print(field[i].getGenericType()+"\n");
// }
System.out.print("class java.lang.String".equals(field.getGenericType().toString())+"\n");
field.set(testa, "aa");
System.out.print(testa.getC());
}
class A{
private int a;
private boolean b;
private String c;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public boolean isB() {
return b;
}
public void setB(boolean b) {
this.b = b;
}
public String getC() {
return c;
}
public void setC(String c) {
this.c = c;
}
}
}
| 1,479 | 0.678837 | 0.656525 | 57 | 24.947369 | 24.938114 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.315789 | false | false | 2 |
91692bb2d0eb6d8ea768378439b58c19f919dcb6 | 12,189,117,214,114 | 46167791cbfeebc8d3ddc97112764d7947fffa22 | /spring-boot/src/main/java/com/justexample/repository/Entity1337Repository.java | 44f5df1ce23317be756634fc04bfb365356de7c7 | [] | no_license | kahlai/unrealistictest | https://github.com/kahlai/unrealistictest | 4f668b4822a25b4c1f06c6b543a26506bb1f8870 | fe30034b05f5aacd0ef69523479ae721e234995c | refs/heads/master | 2023-08-25T09:32:16.059000 | 2021-11-09T08:17:22 | 2021-11-09T08:17:22 | 425,726,016 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.justexample.repository;
import java.util.List;
import com.justexample.entity.Entity1337;
import org.springframework.data.jpa.repository.JpaRepository;
public interface Entity1337Repository extends JpaRepository<Entity1337,Long>{
}
| UTF-8 | Java | 252 | java | Entity1337Repository.java | Java | [] | null | [] | package com.justexample.repository;
import java.util.List;
import com.justexample.entity.Entity1337;
import org.springframework.data.jpa.repository.JpaRepository;
public interface Entity1337Repository extends JpaRepository<Entity1337,Long>{
}
| 252 | 0.825397 | 0.777778 | 11 | 21.90909 | 26.589315 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 2 |
16c67defcc7f645078aec2ee73dfa29e995813e7 | 1,211,180,826,564 | a35af9d6da1c9869251f12641d2e3f361cb5dc41 | /src/book/JrBookLegende.java | 9d009aab93b93f77826396f5769938ab1f78f9b0 | [] | no_license | ArtigueOlivier/JvRoad | https://github.com/ArtigueOlivier/JvRoad | c07f240ff8eadf5b472c052143df6813d363efe1 | 9d2420c131bed74b10b68e85c11cd08007723705 | refs/heads/master | 2023-03-23T12:10:14.124000 | 2021-03-14T09:08:09 | 2021-03-14T09:08:09 | 347,436,021 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Created on Feb 8, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package book;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import book.symbol.JrSymbol;
import tools.JrDrawTools;
import names.JrPenName;
import names.JrSymbolName;
/**
* @author artigue
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class JrBookLegende extends JrBookAbstractPrintable {
private Rectangle [] regions = null;
private Font fontText = null;
public JrBookLegende(JrBook bk) {
super(bk);
}
public int print(Graphics g, PageFormat pf, int page) throws PrinterException {
if (page >= getPageCount())
return Printable.NO_SUCH_PAGE;
int pw = (int)(pf.getImageableWidth());
int ph = (int)(pf.getImageableHeight());
int x,y,w,h;
Graphics2D g2 = (Graphics2D)g;
dt.setDeviceGraphic(g2);
g2.translate(pf.getImageableX(),pf.getImageableY());
if ((pw != refWidth) || (ph != refHeight)) {
refWidth = pw;
refHeight = ph;
computeRegions(regions1,5,5,refWidth-10,refHeight-10);
computeRegions(5,5,refWidth-10,refHeight-10);
}
dt.selectColor(Color.WHITE);
dt.drawRectangle(0,0,refWidth,refHeight,true);
printPage(dt,regions);
return Printable.PAGE_EXISTS;
}
public void computeRegions(int x,int y,int w,int h) {
int he = h / 15;
int hc = (h - he) / JrSymbolName.SYMBOL_COUNT;
int ht = he + (hc * JrSymbolName.SYMBOL_COUNT);
int wc = hc;
regions = new Rectangle [3 + (2 * JrSymbolName.SYMBOL_COUNT)];
regions[0] = new Rectangle(x,y,w,ht);
regions[1] = new Rectangle(x,y,w,he);
regions[2] = new Rectangle(x,y+he,wc,ht-he);
for(int i = 0; i < JrSymbolName.SYMBOL_COUNT; i++) {
regions[3+(2*i)] = new Rectangle(x,y+he+(i*hc),wc,hc);
regions[4+(2*i)] = new Rectangle(x+wc,y+he+(i*hc),w-wc,hc);
}
fontText = dt.createFont(Math.min(he,(w-wc)/40),true);
}
public void printPage(JrDrawTools dt,Rectangle[] regs) {
JrSymbol symb;
dt.selectDefinedPen(JrPenName.PEN_CADRE_EPAIS,true);
drawRectangle(dt,regs[0]);
drawRectangle(dt,regs[1]);
dt.selectDefinedPen(JrPenName.PEN_CADRE_NORMAL,true);
drawRectangle(dt,regs[2]);
dt.selectFont(fontText);
dt.drawText(GetWord("TxtLegende"),regs[1],1);
for(int i = 0; i < JrSymbolName.SYMBOL_COUNT; i++) {
dt.selectDefinedPen(JrPenName.PEN_CADRE_NORMAL,true);
drawRectangle(dt,regs[3+(2*i)]);
drawRectangle(dt,regs[4+(2*i)]);
dt.selectFont(fontText);
dt.drawText(GetWord(JrSymbolName.GetSymbolText(i)),regs[4+(2*i)],0);
symb = JrSymbol.Create(i);
symb.draw(dt,regs[3+(2*i)]);
}
}
public void drawRectangle(JrDrawTools dt,Rectangle r) {
dt.drawRectangle((float)r.x,(float)r.y,(float)r.width,(float)r.height,false);
}
}
| UTF-8 | Java | 3,034 | java | JrBookLegende.java | Java | [
{
"context": "nName;\nimport names.JrSymbolName;\n\n\n/**\n * @author artigue\n *\n * TODO To change the template for this genera",
"end": 539,
"score": 0.9890372157096863,
"start": 532,
"tag": "USERNAME",
"value": "artigue"
}
] | null | [] | /*
* Created on Feb 8, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package book;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import book.symbol.JrSymbol;
import tools.JrDrawTools;
import names.JrPenName;
import names.JrSymbolName;
/**
* @author artigue
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class JrBookLegende extends JrBookAbstractPrintable {
private Rectangle [] regions = null;
private Font fontText = null;
public JrBookLegende(JrBook bk) {
super(bk);
}
public int print(Graphics g, PageFormat pf, int page) throws PrinterException {
if (page >= getPageCount())
return Printable.NO_SUCH_PAGE;
int pw = (int)(pf.getImageableWidth());
int ph = (int)(pf.getImageableHeight());
int x,y,w,h;
Graphics2D g2 = (Graphics2D)g;
dt.setDeviceGraphic(g2);
g2.translate(pf.getImageableX(),pf.getImageableY());
if ((pw != refWidth) || (ph != refHeight)) {
refWidth = pw;
refHeight = ph;
computeRegions(regions1,5,5,refWidth-10,refHeight-10);
computeRegions(5,5,refWidth-10,refHeight-10);
}
dt.selectColor(Color.WHITE);
dt.drawRectangle(0,0,refWidth,refHeight,true);
printPage(dt,regions);
return Printable.PAGE_EXISTS;
}
public void computeRegions(int x,int y,int w,int h) {
int he = h / 15;
int hc = (h - he) / JrSymbolName.SYMBOL_COUNT;
int ht = he + (hc * JrSymbolName.SYMBOL_COUNT);
int wc = hc;
regions = new Rectangle [3 + (2 * JrSymbolName.SYMBOL_COUNT)];
regions[0] = new Rectangle(x,y,w,ht);
regions[1] = new Rectangle(x,y,w,he);
regions[2] = new Rectangle(x,y+he,wc,ht-he);
for(int i = 0; i < JrSymbolName.SYMBOL_COUNT; i++) {
regions[3+(2*i)] = new Rectangle(x,y+he+(i*hc),wc,hc);
regions[4+(2*i)] = new Rectangle(x+wc,y+he+(i*hc),w-wc,hc);
}
fontText = dt.createFont(Math.min(he,(w-wc)/40),true);
}
public void printPage(JrDrawTools dt,Rectangle[] regs) {
JrSymbol symb;
dt.selectDefinedPen(JrPenName.PEN_CADRE_EPAIS,true);
drawRectangle(dt,regs[0]);
drawRectangle(dt,regs[1]);
dt.selectDefinedPen(JrPenName.PEN_CADRE_NORMAL,true);
drawRectangle(dt,regs[2]);
dt.selectFont(fontText);
dt.drawText(GetWord("TxtLegende"),regs[1],1);
for(int i = 0; i < JrSymbolName.SYMBOL_COUNT; i++) {
dt.selectDefinedPen(JrPenName.PEN_CADRE_NORMAL,true);
drawRectangle(dt,regs[3+(2*i)]);
drawRectangle(dt,regs[4+(2*i)]);
dt.selectFont(fontText);
dt.drawText(GetWord(JrSymbolName.GetSymbolText(i)),regs[4+(2*i)],0);
symb = JrSymbol.Create(i);
symb.draw(dt,regs[3+(2*i)]);
}
}
public void drawRectangle(JrDrawTools dt,Rectangle r) {
dt.drawRectangle((float)r.x,(float)r.y,(float)r.width,(float)r.height,false);
}
}
| 3,034 | 0.692485 | 0.674357 | 101 | 29.039604 | 21.888521 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.554456 | false | false | 2 |
5d888b6e4da84f8f9bc1f928cacca81a1f5ad0ea | 37,890,201,485,515 | 9e9a79c652aa55179bfd977b544b000d48bfcc9b | /src/Basics/IfElse.java | 5d45fdf73dc02e0cdd9431535a5a9fa7ddd4a4f0 | [] | no_license | Pranjalnegi/java-learning | https://github.com/Pranjalnegi/java-learning | 4189d7736d9a49f78a98ddc7935445ebc9a9ec26 | 06bde6c75dcd8aeb900a69c2b5d2276b3eb106ac | refs/heads/master | 2022-06-21T21:42:09.760000 | 2020-05-09T13:03:46 | 2020-05-09T13:03:46 | 262,571,415 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Basics;
public class IfElse {
public static void main(String[] args) {
int salary=50000;
if (salary>50000){
System.out.println("My salary is goood"+salary);
}
else if (salary<50000) {
System.out.println("My salary is very low "+salary);
}
else {
System.out.println("My salary is Ok as it is "+salary);
}
}
}
| UTF-8 | Java | 345 | java | IfElse.java | Java | [] | null | [] | package Basics;
public class IfElse {
public static void main(String[] args) {
int salary=50000;
if (salary>50000){
System.out.println("My salary is goood"+salary);
}
else if (salary<50000) {
System.out.println("My salary is very low "+salary);
}
else {
System.out.println("My salary is Ok as it is "+salary);
}
}
}
| 345 | 0.649275 | 0.605797 | 18 | 18.166666 | 19.785658 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.666667 | false | false | 2 |
0a3fdf83c5bfb8b1f7ca4293af7dc5fee71c9854 | 4,234,837,810,951 | 8c2a8456b55fd8a58474be5acb902a63b16f170d | /app/src/main/java/com/walmart/walmartlabstest/shared/WalmartLabsTestApplicationComponent.java | 5e78676e9540ca795811e0449589b721ae443104 | [] | no_license | gowrishankar901/WalmartLabs | https://github.com/gowrishankar901/WalmartLabs | aae120259dbc314fae99d4b5c83eef45e2d6424f | 4fb5f5b3649d1dd2997eca135afc57ec3a805bbf | refs/heads/master | 2020-07-04T10:43:04.228000 | 2019-08-14T02:45:43 | 2019-08-14T03:01:45 | 202,259,937 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.walmart.walmartlabstest.shared;
import android.app.Application;
import android.content.Context;
import javax.inject.Singleton;
import dagger.BindsInstance;
import dagger.Component;
import dagger.android.support.AndroidSupportInjectionModule;
@Component(modules = {
ActivityModule.class,
WalmartLabsModule.class,
AndroidSupportInjectionModule.class
})
@Singleton
public interface WalmartLabsTestApplicationComponent {
@Component.Builder
interface Builder {
@BindsInstance
Builder application(Application application);
@BindsInstance
Builder context(Context context);
WalmartLabsTestApplicationComponent build();
}
void inject(WalmartLabsTestApplication walmartLabsTestApplication);
}
| UTF-8 | Java | 782 | java | WalmartLabsTestApplicationComponent.java | Java | [] | null | [] | package com.walmart.walmartlabstest.shared;
import android.app.Application;
import android.content.Context;
import javax.inject.Singleton;
import dagger.BindsInstance;
import dagger.Component;
import dagger.android.support.AndroidSupportInjectionModule;
@Component(modules = {
ActivityModule.class,
WalmartLabsModule.class,
AndroidSupportInjectionModule.class
})
@Singleton
public interface WalmartLabsTestApplicationComponent {
@Component.Builder
interface Builder {
@BindsInstance
Builder application(Application application);
@BindsInstance
Builder context(Context context);
WalmartLabsTestApplicationComponent build();
}
void inject(WalmartLabsTestApplication walmartLabsTestApplication);
}
| 782 | 0.763427 | 0.763427 | 31 | 24.225807 | 20.3972 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.419355 | false | false | 2 |
6340b1b4ef26e90362b45602959a84eaca5630cb | 4,234,837,812,581 | a13a30fdf6cd4f11d63fc3a5e8665d063a420c13 | /src/main/java/edu/osu/cse/HammingDistance.java | 8755a691cd4e9cbe40beaa543b6531e11a676451 | [] | no_license | prasanthj/algorithms | https://github.com/prasanthj/algorithms | 4905b15d419f8b6007755cb76b1a71b6bb23387f | 7f1c4eb19e587a3be2f495f0907ff5b41133c3b5 | refs/heads/master | 2021-01-17T17:01:50.666000 | 2013-07-24T05:16:31 | 2013-07-24T05:16:31 | 10,540,203 | 2 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.osu.cse;
public class HammingDistance {
public static int hammingDistance(String s, String t) {
if(s == null || t == null || s.isEmpty() || t.isEmpty()) {
return -1;
}
if(s.length() != t.length()) {
return -1;
}
int dist = 0;
for(int i=0; i<s.length(); i++) {
if(s.charAt(i) != t.charAt(i)) {
dist++;
}
}
return dist;
}
public static int hammingDistance(int x, int y) {
int dist = 0;
int xor = x ^ y;
while(xor > 0) {
if((xor & 1) == 1) {
dist++;
}
xor = xor >>> 1;
}
return dist;
}
}
| UTF-8 | Java | 579 | java | HammingDistance.java | Java | [] | null | [] | package edu.osu.cse;
public class HammingDistance {
public static int hammingDistance(String s, String t) {
if(s == null || t == null || s.isEmpty() || t.isEmpty()) {
return -1;
}
if(s.length() != t.length()) {
return -1;
}
int dist = 0;
for(int i=0; i<s.length(); i++) {
if(s.charAt(i) != t.charAt(i)) {
dist++;
}
}
return dist;
}
public static int hammingDistance(int x, int y) {
int dist = 0;
int xor = x ^ y;
while(xor > 0) {
if((xor & 1) == 1) {
dist++;
}
xor = xor >>> 1;
}
return dist;
}
}
| 579 | 0.504318 | 0.488774 | 38 | 14.236842 | 15.706911 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.473684 | false | false | 2 |
a9690aff3e9f34eb007ea2c1c7a91a3d66f7dc1e | 4,234,837,813,927 | 5c4dcf33cd3102ed8faf110c7d613d57e28db708 | /java/orientacao-objetos/AulaPOO/src/TrabalhoA2/Repository.java | c0363a185c6d3e87a7aa3e41f8575c18cbb88c7a | [] | no_license | Rafael-Pessoni/sistemas-de-informacao | https://github.com/Rafael-Pessoni/sistemas-de-informacao | cf12290de161e48cdce4e90ff9b54ce5b42cccec | bbc217c91429930068e38f5d27d6016a6892d38a | refs/heads/master | 2020-03-24T01:00:11.167000 | 2017-12-14T01:05:57 | 2017-12-14T01:05:57 | 52,675,042 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package TrabalhoA2;
import java.util.ArrayList;
public class Repository {
public static ArrayList<Cliente> clientes = new ArrayList<Cliente>();
public static ArrayList<Produto> produtos = new ArrayList<Produto>();
public static ArrayList<Pedido> pedidos = new ArrayList<Pedido>();
public static ArrayList<Movimentacao> movimentacoes = new ArrayList<Movimentacao>();
public static void RelatorioGeral(){
System.out.println("\n\nPedidos:");
for(Pedido item : pedidos)
item.mostraPedido();
}
} | UTF-8 | Java | 580 | java | Repository.java | Java | [] | null | [] | package TrabalhoA2;
import java.util.ArrayList;
public class Repository {
public static ArrayList<Cliente> clientes = new ArrayList<Cliente>();
public static ArrayList<Produto> produtos = new ArrayList<Produto>();
public static ArrayList<Pedido> pedidos = new ArrayList<Pedido>();
public static ArrayList<Movimentacao> movimentacoes = new ArrayList<Movimentacao>();
public static void RelatorioGeral(){
System.out.println("\n\nPedidos:");
for(Pedido item : pedidos)
item.mostraPedido();
}
} | 580 | 0.662069 | 0.660345 | 18 | 30.333334 | 28.64534 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 2 |
583d110a4c81141938565f0dd19c0b7cdfab9060 | 37,357,625,558,492 | 3fd09a06e3280039fd4afdd3691a57a3c4b51845 | /fudannlp-0.9-src/src/edu/fudan/ml/struct/classifier/Linear.java | 5a7c09284840631cd3a16423089f3fab5c35bcec | [] | no_license | DrStephenWang/ResearchProject | https://github.com/DrStephenWang/ResearchProject | 888b997e3b4ea907cd4bdf6c013acc6267ddacc4 | 73ef0c1cae06dc61281278391176cb4bd39b86cb | refs/heads/master | 2021-01-20T10:46:21.784000 | 2013-06-07T14:40:03 | 2013-06-07T14:40:03 | 9,594,127 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.fudan.ml.struct.classifier;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.List;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import edu.fudan.ml.classifier.Classifier;
import edu.fudan.ml.pipe.Pipe;
import edu.fudan.ml.struct.solver.IMaxSolver;
import edu.fudan.ml.types.Alphabet;
import edu.fudan.ml.types.Instance;
import edu.fudan.ml.types.InstanceSet;
public class Linear implements Classifier, Serializable {
private static final long serialVersionUID = 7811611261579845079L;
private double[] weights;
private IMaxSolver msolver;
private Alphabet labelAlphabet;
private Pipe pipe;
public Alphabet getLabelAlphabet() {
return labelAlphabet;
}
public void setLabelAlphabet(Alphabet labelAlphabet) {
this.labelAlphabet = labelAlphabet;
}
public Linear() {
}
public Linear(double[] sv, IMaxSolver msolver, Alphabet labelAlphabet,Pipe pipe) {
this.msolver = msolver;
this.setWeights(sv);
this.labelAlphabet = labelAlphabet;
this.setPipe(pipe);
}
public Object classify(Instance instance) {
List pred = (List) msolver.getBest(instance, 2);
return pred.get(0);
}
public String[] predict(Instance instance) {
List pred = (List) msolver.getBest(instance, 2);
int[] label = (int[]) pred.get(0);
return labelAlphabet.lookupString(label);
}
public String[][] predict(InstanceSet instSet) {
String[][] res = new String[instSet.size()][];
for(int i=0; i<instSet.size(); i++) {
Instance inst = instSet.getInstance(i);
res[i]=predict(inst);
}
return res;
}
public double[] getWeight() {
return getWeights();
}
public void setPipe(Pipe pipe) {
this.pipe = pipe;
}
public Pipe getPipe() {
return pipe;
}
public void saveModel(String file) throws IOException {
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream (
new GZIPOutputStream (new FileOutputStream(file))));
out.writeObject(this);
out.close();
}
public static Linear readModel(InputStream is) throws IOException{
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream
(new GZIPInputStream (is)));
return readModel(in);
}
public static Linear readModel(String file) throws IOException {
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream
(new GZIPInputStream (new FileInputStream(file))));
return readModel(in);
}
public static Linear readModel(ObjectInputStream in){
try {
Linear cl = (Linear) in.readObject();
return cl;
}catch(Exception e) {
e.printStackTrace();
System.err.print("Read model error!");
return null;
}
}
public void setWeights(double[] weights) {
this.weights = weights;
if(msolver==null){
System.err.println("Solver is null!");
return;
}
msolver.setWeight(weights);
}
public double[] getWeights() {
return weights;
}
}
| UTF-8 | Java | 3,128 | java | Linear.java | Java | [] | null | [] | package edu.fudan.ml.struct.classifier;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.List;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import edu.fudan.ml.classifier.Classifier;
import edu.fudan.ml.pipe.Pipe;
import edu.fudan.ml.struct.solver.IMaxSolver;
import edu.fudan.ml.types.Alphabet;
import edu.fudan.ml.types.Instance;
import edu.fudan.ml.types.InstanceSet;
public class Linear implements Classifier, Serializable {
private static final long serialVersionUID = 7811611261579845079L;
private double[] weights;
private IMaxSolver msolver;
private Alphabet labelAlphabet;
private Pipe pipe;
public Alphabet getLabelAlphabet() {
return labelAlphabet;
}
public void setLabelAlphabet(Alphabet labelAlphabet) {
this.labelAlphabet = labelAlphabet;
}
public Linear() {
}
public Linear(double[] sv, IMaxSolver msolver, Alphabet labelAlphabet,Pipe pipe) {
this.msolver = msolver;
this.setWeights(sv);
this.labelAlphabet = labelAlphabet;
this.setPipe(pipe);
}
public Object classify(Instance instance) {
List pred = (List) msolver.getBest(instance, 2);
return pred.get(0);
}
public String[] predict(Instance instance) {
List pred = (List) msolver.getBest(instance, 2);
int[] label = (int[]) pred.get(0);
return labelAlphabet.lookupString(label);
}
public String[][] predict(InstanceSet instSet) {
String[][] res = new String[instSet.size()][];
for(int i=0; i<instSet.size(); i++) {
Instance inst = instSet.getInstance(i);
res[i]=predict(inst);
}
return res;
}
public double[] getWeight() {
return getWeights();
}
public void setPipe(Pipe pipe) {
this.pipe = pipe;
}
public Pipe getPipe() {
return pipe;
}
public void saveModel(String file) throws IOException {
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream (
new GZIPOutputStream (new FileOutputStream(file))));
out.writeObject(this);
out.close();
}
public static Linear readModel(InputStream is) throws IOException{
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream
(new GZIPInputStream (is)));
return readModel(in);
}
public static Linear readModel(String file) throws IOException {
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream
(new GZIPInputStream (new FileInputStream(file))));
return readModel(in);
}
public static Linear readModel(ObjectInputStream in){
try {
Linear cl = (Linear) in.readObject();
return cl;
}catch(Exception e) {
e.printStackTrace();
System.err.print("Read model error!");
return null;
}
}
public void setWeights(double[] weights) {
this.weights = weights;
if(msolver==null){
System.err.println("Solver is null!");
return;
}
msolver.setWeight(weights);
}
public double[] getWeights() {
return weights;
}
}
| 3,128 | 0.744246 | 0.736573 | 104 | 29.076923 | 19.40296 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.038461 | false | false | 2 |
dea053d72ffd1a9d601a22001dd20aaff425840f | 37,357,625,560,949 | 813aeaaebcdf2a11a5d67440226d92a4e6312919 | /deodio-main/src/main/java/com/deodio/elearning/constants/DConstants.java | 9bfda68478f838994b75cea73dce7078e0d35e25 | [] | no_license | isaac-bo/deodio-education | https://github.com/isaac-bo/deodio-education | 25c0c003a7ec6ccd447f6540f08f4d6e86737982 | 198b02b8680bcbcfd648d00e680b5b29cee13947 | refs/heads/master | 2022-07-22T03:39:34.133000 | 2020-03-11T01:38:31 | 2020-03-11T01:38:31 | 246,486,424 | 0 | 1 | null | false | 2022-06-29T19:49:18 | 2020-03-11T05:51:36 | 2020-03-11T05:53:37 | 2022-06-29T19:49:18 | 41,411 | 0 | 1 | 2 | Java | false | false |
/**
* @Title: DConstants.java
* @Package com.deodio.elearning.constants
* @author isaac
* @date 2015-1-28
* @version V1.0
*/
package com.deodio.elearning.constants;
import com.deodio.core.constants.Constants;
/**
* @ClassName: DConstants
* @author isaac
* @date 2015-1-28
*/
public interface DConstants extends Constants{
//accout审核状态
public static final String ACCOUNT_STATUS = "ACCSTA";//account审核未通过
public static final String ACCOUNT_STATUS_APPROVING_STRING = "0";//account审核中
public static final String ACCOUNT_STATUS_APPROVED_STRING = "1";//account审核通过
public static final Short ACCOUNT_STATUS_APPROVING_SHORT = 0;//account审核中
public static final Short ACCOUNT_STATUS_APPROVED_SHORT = 1;//account审核通过
public static final String CELL_DATA_DELIMITER = "_#_";
public static final String ERROR_DATA_DELIMITER = "_:::_";
public static final Integer USER_STATUS_ACTIVATE = 1;
public static final Integer USER_STATUS_UNACTIVATE = 0;
public static final Integer USER_TYPE_IS_ACCOUNT = 1;
public static final Integer USER_TYPE_IS_NORMAL = 0;
public static final Integer ACCOUNT_IS_PERSONAL = 1;
public static final Integer ACCOUNT_IS_COMPANY = 0;
public static final Integer BILL_STATUS_ACTVATE = 1;
public static final Integer BILL_STATUS_UNACTIVATE = 0;
public static final Integer BUSINESS_LICENSE_INIT = 0;
public static final Integer BUSINESS_LICENSE_APPROVING = 1;
public static final Integer BUSINESS_LICENSE_APPROVED = 2;
public static final Integer BUSINESS_LICENSE_REJECT = 3;
public static final String USER_ACCOUNT_LIST_SIZE = "ACCOUNT_SIZE";
public static final String USER_CURRENT_GROUP_ID = "CURRENT_GROUP";
public static final String USER_SELF_ACCOUNT_ID="SELF_ACCOUNT_ID";
public static final String COOKIE_USER_ID="CUID";
public static final String COOKIE_ACCOUNT_ID="CAID";
public static final String COOKIE_USER_NAME="CUNAME";
public static final String COOKIE_NICK_NAME="N_NAME";
public static final String COOKIE_USER_PASS="CUKEY";
public static final String COOKIE_USER_HEADER_PIC="CUHP";
public static final String COOKIE_USER_REGISTER_TYPE="CURT";
public static final String COOKIE_USER_TYPE="CUT";
public static final String COOKIE_JSESSION_ID = "JSESSIONID";
public static final String COOKIE_GROUP_ROLE_ID = "CGRID";
public static final String COOKIE_GROUP_ID = "CGID";
public static final String COOKIE_COURSE_ID = "CCID";
public static final String COOKIE_HEADER_IMG = "CHI";
public static final String COOKIE_LOGO_IMG ="CLI";
public static final String COOKIE_FOOTER_IMG = "CFI";
public static final String COOKIE_BANNER_IMG = "CBI";
public static final String COOKIE_HEADER_IMG_LINK_URL = "CHILU";
public static final String COOKIE_LOGO_IMG_LINK_URL ="CLILU";
public static final String COOKIE_FOOTER_IMG_LINK_URL = "CFILU";
public static final String COOKIE_BANNER_IMG_LINK_URL = "CBILU";
public static final String COOKIE_MOBILE_VALIDATION_CODE="MV_CODE";
public static final String COOKIE_PICTURE_VALIDATION_CODE="P_CODE";
public static final short CLASSIFICATION_ITEMS_TYPE_PRESENTATION = 1;
public static final short CLASSIFICATION_ITEMS_TYPE_COURSE_ONLINE = 21;
public static final short CLASSIFICATION_ITEMS_TYPE_COURSE_OFFLINE = 22;
public static final short CLASSIFICATION_ITEMS_TYPE_COURSE_ONLIVE = 23;
public static final short CLASSIFICATION_ITEMS_TYPE_KNOWLEDGEPOINT = 3;
public static final short CLASSIFICATION_ITEMS_TYPE_COURSEPACKAGE = 4;
public static final short TAGS_ITEMS_TYPE_PRESENTATION = 1;
public static final short TAGS_ITEMS_TYPE_COURSE_ONLINE = 21;
public static final short TAGS_ITEMS_TYPE_COURSE_OFFLINE = 22;
public static final short TAGS_ITEMS_TYPE_COURSE_ONLIVE = 23;
public static final short TAGS_ITEMS_TYPE_KNOWLEDGEPOINT = 3;
public static final short TAGS_ITEMS_TYPE_COURSEPACKAGE = 4;
public static final short TAGS_ITEMS_TYPE_EXAMINATION = 5;
public static final String DEFAULT_PASS_WORD="123456";
public static final Integer PRESENTATION_FILES_TYPE_SCORM = 0;
public static final Integer PRESENTATION_FILES_TYPE_PACKAGE = 1;
public static final Integer TYPE_NO_PUBLISH = 0;
public static final Integer TYPE_IS_PUBLISH = 1;
public static final Integer NUMBER_TEN=10;
public static final Integer NUMBER_FIVE=5;
public static final String MAIL_HEADER_DATA = ";";
/**
* The suffix of Excel 2003.
*/
public static final String XLS = "xls";
/**
* The suffix of Excel 2007.
*/
public static final String XLSX = "xlsx";
public static final String DELIMITER_CELL_DATA = "_&_";
/**
* Separator by different characters for |
*/
public static final String SEPARATOR = "|";
/**
* Separator by different characters for _@_
*/
public static final String DELIMITER_ROW = "_@_";
/**
* Separator by different characters for _#_
*/
public static final String DELIMITER_DATA = "_#_";
/**
* Separator by different characters for ]=[
*/
public static final String DELIMITER_ATTR = "]=[";
/**
* Separator by different characters for _$_
*/
public static final String DELIMITER_DOLLER = "_$_";
/**
* Separator by different characters for ]@[
*/
public static final String DELIMITER_CELL_STYLE = "]@[";
/**
* Separator by different characters for comma
*/
public static final String DELIMITER_COMMA = ",";
public static final String DELIMITER_HR = "_";
public static final String DELIMITER_SEMICOLON = ";";
public static final String DELIMITER_SEPARATOR = "_|_";
public static final String FOLDER_MEDIA = "vod";
public static final String FOLDER_SCROM = "scrom";
public static final String FOLDER_IMAGE = "img";
public static final String FOLDER_PACKAGE = "package";
public static final String[] IMAGE_TYPE = {"jpg","JPG","gif","GIF","jpeg","JPEG","png","PNG","swf","SWF"};
public static final String[] PPT_FORMAT = {"ppt","PPT","pptx","PPTX"};
public static final String[] MEDIA_MP3 = {"mp3","MP3"};
public static final String[] OFFICE_FILE_TYPES = {"ppt","PPT","pptx","PPTX","xls","XLS","xlsx","XLSX","doc","DOC","docx","DOCX","txt","TXT","pdf","PDF"};
public static final Integer COURSE_TYPE_ONLINE = 1;
public static final Integer COURSE_TYPE_OFFLINE = 2;
public static final Integer COURSE_TYPE_ONLIVE = 3;
public static final int QUEUE_WAIT_SECONDS = 30;
public static final String DELIMITER_SLASH = "/";
public static final String DELIMITER_FULL = ".";
public static final String MEDIA_COVERT_STATUS_MRSTART_SUCCESS = "SUCCEEDED";
public static final String MEDIA_COVERT_STATUS_MRSTART_PROCESSING = "RUNNING";
public static final Integer SERVICE_PLAN_TRIAL = 1;
public static final Integer SERVICE_PLAN_TWO = 2;
public static final Integer SERVICE_PLAN_THREE = 3;
public static final Integer SERVICE_PLAN_FOUR = 4;
public static final String SERVICE_PLAN_CMOBO_TYPE_MAX_CLASSIFICATION_COUNT = "maxClassificationCount";
public static final Integer ACCOUNT_ITEMS_REL_ITEMS_TYPE_PLAN = 1;
public static final Integer ACCOUNT_ITEMS_REL_ITEMS_TYPE_CLASSIFICATION = 2;
public static final Integer ACCOUNT_ITEMS_REL_ACCOUNT_TYPE_STANDARD = 1;
public static final Integer ACCOUNT_ITEMS_REL_ACCOUNT_TYPE_PREFERENTIAL = 2;
public static final short USE_REGISTER_TYPE_PHONE = 1;
public static final short USE_REGISTER_TYPE_MAIL = 2;
public static final short USE_REGISTER_TYPE_COMPANY = 3;
public static final short USE_REGISTER_TYPE_THREE_PART = 4;
public static final short USE_REGISTER_TYPE_OTHERS= 5;
public static final String USE_REGISTER_TYPE_PHONE_String = "1";
public static final String USE_REGISTER_TYPE_MAIL_String = "2";
public static final String USE_REGISTER_TYPE_COMPANY_String = "3";
public static final String USE_REGISTER_TYPE_THREE_PART_String = "4";
// public static final String DOMAIN_POSTIFX = ".deodio.com.cn";
public static final String DOMAIN_WWW = "www";
public static final String DOMIAN_CONTENT_ROOT = "/deodio-main";
public static final String DOMAIN_SESSION_ACCOUNT_ID="DSAID";
public static final String GROUP_ROLE_GROUP_LEADER_ID = "10000";
public static final String GROUP_ROLE_CONTENT_CREATOR_ID = "10001";
public static final String GROUP_ROLE_VIEWER_ID = "10002";
public static final String ROLE_CONTENT_ACCOUNT_ID = "ACCOUNT";
public static final short USER_TYPE_PERSONAL = 1;
public static final short USER_TYPE_COMPANY = 2;
public static final short HAS_LEADER_PRIVILEDGE_YES = 1;
public static final short HAS_LEADER_PRIVILEDGE_NO = 0;
public static final String REFRESH_IMG_LOGO = "refresh";
/*1:presentation, 2:quiz,3:survey, 4:course*/
public static final short GROUP_ITEMS_TYPE_PRESENTATION = 1;
public static final short GROUP_ITEMS_TYPE_QUIZ = 2;
public static final short GROUP_ITEMS_TYPE_SURVEY = 3;
public static final short GROUP_ITEMS_TYPE_COURSE = 4;
public static final short GROUP_ITEMS_TYPE_PACKAGE = 5;
public static final boolean INSERT_SYS_CLASSIFICATION_FLAG_PRE_DEL_DO = true;
public static final boolean INSERT_SYS_CLASSIFICATION_FLAG_PRE_DEL_UNDO = false;
public static final short GROUP_TYPE_PERMISSION = 1;
public static final short GROUP_TYPE_MODEL_FUNCTION = 2;
public static final int SYSTEM_TEMPLATE_INVITE_MAIL_SUBJECT = 10005;
public static final int SYSTEM_TEMPLATE_INVITE_MAIL_CONTENT = 10006;
public static final int SYSTEM_TEMPLATE_INVITE_MAIL_TEMPLATE = 10002;
public static final int SYSTEM_TEMPLATE_INVITE_MAIL_REINVITE = 10003;
public static final int SYSTEM_TEMPLATE_INVITE_MAIL_TEXT_TEMPLATE = 10007;
public static final int SYSTEM_TEMPLATE_INVITE_MAIL_TEXT_TEMPLATE_COMMON_MAIL = 10008;
public static final int SYSTEM_TEMPLATE_INVITE_MAIL_TEXT_TEMPLATE_BATCH_IMPORT_MAIL = 10010;
public static final Integer PRESENTATION_IS_COUNT_DOWN_FLAG_YES = 1;
public static final Integer PRESENTATION_IS_COUNT_DOWN_FLAG_NO = 0;
public static final Short PRESENTATION_PUBLISH_IS_COURSE_YES = 1;
public static final Short PRESENTATION_PUBLISH_IS_COURSE_NO = 0;
public static final Integer ATTACHMENT_TYPE_PRESENTATION = 5;
public static final Integer ATTACHMENT_TYPE_SCROM = 50;
public static final Integer ATTACHMENT_TYPE_PACKAGE = 51;
public static final Integer ATTACHMENT_TYPE_SLIDES = 53;
public static final Integer ATTACHMENT_TYPE_MEDIA = 54;
public static final String SCROM_MANIFEST_FILE_NAME = "imsmanifest.xml";
public static final Integer PACKAGE_IS_CONVERT_YES = 1;
public static final Integer PACKAGE_IS_CONVERT_NO = 0;
public static final Integer ATTACHMENT_IS_CONVERT_YES = 1;
public static final Integer ATTACHMENT_IS_CONVERT_NO = 0;
//站内信状态 0:保存 1:已发布
public static final String MESSAGE_TEXT_STATUS_SAVE="0";
public static final String MESSAGE_TEXT_STATUS_PUBLISH="1";
//站内信消息类型
public static final String MESSAGE_TEXT_TYPE_JOIN="1";
//站内信发送对象类型
public static final Integer MESSAGE_TEXT_REC_TYPE_TEACHER=1;
//站内信内容查看状态 0:未查看 1:查看
public static final String MESSAGE_VIEW_STATUS_ZERO="0";
public static final String MESSAGE_VIEW_STATUS_ONE="1";
public static final String SLIDE_EXT_PNG = "png";
public static final String MEDIA_EXT_MP4 = "mp4";
public static final int PRESENTATION_MODEL_SCORM = 0;
public static final int PRESENTATION_MODEL_PACKAGE = 1;
public static final int PRESENTATION_MODEL_SYNC = 2;
public static final int PRESENTATION_MODEL_EXTERNAL = 3;
public static final Integer COURSE_RECORD_IS_PASS = 1;
public static final Integer COURSE_RECORD_IS_CONTINUE = 0;
public static final Integer TRAINEE_COURSE_REL_COURSE = 1;
public static final Integer TRAINEE_COURSE_REL_PACKAGE = 2;
/*课后作业60;考试61;调查问卷62 附件63*/
public static final String TRAINEE_COURSE_HOMEWORK = "60";
public static final String TRAINEE_COURSE_QUIZ = "61";
public static final String TRAINEE_COURSE_SURVEY = "62";
public static final String TRAINEE_COURSE_ATTACH = "63";
public static final String TRAINEE_COURSE_APPRAISE = "64";
//内容类型 1:考试 2:调查问卷
public static final Integer TRAINEE_EXAM_TYPE_QUIZ = 1;
public static final Integer TRAINEE_EXAM_TYPE_SURVEY = 2;
//状态 1:新提交 2:已阅
public static final Integer TRAINEE_EXAM_STATUS_NEWSUBMIT = 1;
public static final Integer TRAINEE_EXAM_STATUS_READ = 2;
//登录有效性
public static final Short LOGIN_IS_NEED_CHECK_YES = 1;
public static final Short LOGIN_IS_NEED_CHECK_NO = 0;
public static final Short LOGIN_IS_VALID_NO = 0;
//编辑状态 0: 未编辑 1: 正在编辑
public static final Integer ISNOT_EDIT = 0;
public static final Integer IS_EDIT = 1;
//手机号码是否已验证: 0 未验证 1 已验证
public static final Short PHONE_NUMBER_NOT_CHECKED = 0;
public static final Short PHONE_NUMBER_IS_CHECKED = 1;
//邮箱是否已验证: 0 未验证 1 已验证
public static final Short EMAIL_NOT_CHECKED = 0;
public static final Short EMAIL_IS_CHECKED = 1;
//默认题库ID
public static final String DEFAULT_BANK_ID = "999999";
//试题来源 0:题库 1:手动试卷
public static final Integer QUIZ_SUBJECT_FROM_MANUAL = 1;
public static final Integer QUIZ_SUBJECT_FROM_BANK = 0;
//0: 随机题 1:必考题
public static final Integer QUIZ_SUBJECT_ISNOT_REQUIRED = 0;
public static final Integer QUIZ_SUBJECT_IS_REQUIRED = 1;
//用户注册方式
public static final String REGISTER_TYPE_PHONE = "1";
public static final String REGISTER_TYPE_MAIL = "2";
public static final String REGISTER_TYPE_COMPANY = "3";
//用户详细注册校验内容
public static final String REGISTER_CHECK_OGCODE="organizationCode";
public static final String REGISTER_CHECK_LSCODE="licenseCode";
public static final String REGISTER_CHECK_IDCODE="IDCode";
//小组内课程管理和快速学习
public static final String GROUP_COURSE_MANAGER_SHOW="GCMS";
public static final String GROUP_COURSE_STUDY_SHOW="GCSS";
public static final String GROUP_COURSE_MANAGER_AND_STUDY_SHOW="GCMASS";
public static final String GROUP_COURSE_MANAGER_AND_STUDY_HIDDEN="GCMASH";
//切换账户
public static final String CHANGE_ACCOUNT_SHOW="CACCS";
public static final String CHANGE_ACCOUNT_HIDDEN="CACCH";
//标题栏显示
public static final String GROUP_USER_ROLE_ID="userRoleId";
//用户切换账户后跳转个人中心
public static final String USER_CHANGE_ACCOUNT_TO="CHANGE_TO";
public static final String USER_CHANGE_ACCOUNT_TO_SELF="SELF";
public static final String USER_CHANGE_ACCOUNT_TO_OTHER="OTHER";
//未登录不调转登录页面的链接
public static final String USER_JOIN_GROUP="/deodio-main/group/active_join_group.html";
public static final String USER_GROUP_REGISTER="/deodio-main/group/toGroupFormRegister.html";
public static final String USER_GROUP_SETPWD="/deodio-main/group/setPwd.html";
/* //小組课程列表排序方式
public static final String GROUP_COURSE_ORDER_BY_STUDY_TIME="studyTime";
public static final String GROUP_COURSE_ORDER_BY_ADD_TIME="addTime";*/
}
| UTF-8 | Java | 15,149 | java | DConstants.java | Java | [
{
"context": "@Package com.deodio.elearning.constants\n * @author isaac\n * @date 2015-1-28\n * @version V1.0\n*/\n\t\npackage ",
"end": 91,
"score": 0.8719276189804077,
"start": 86,
"tag": "NAME",
"value": "isaac"
},
{
"context": "stants;\n\n\n/**\n * @ClassName: DConstants\n * @aut... | null | [] |
/**
* @Title: DConstants.java
* @Package com.deodio.elearning.constants
* @author isaac
* @date 2015-1-28
* @version V1.0
*/
package com.deodio.elearning.constants;
import com.deodio.core.constants.Constants;
/**
* @ClassName: DConstants
* @author isaac
* @date 2015-1-28
*/
public interface DConstants extends Constants{
//accout审核状态
public static final String ACCOUNT_STATUS = "ACCSTA";//account审核未通过
public static final String ACCOUNT_STATUS_APPROVING_STRING = "0";//account审核中
public static final String ACCOUNT_STATUS_APPROVED_STRING = "1";//account审核通过
public static final Short ACCOUNT_STATUS_APPROVING_SHORT = 0;//account审核中
public static final Short ACCOUNT_STATUS_APPROVED_SHORT = 1;//account审核通过
public static final String CELL_DATA_DELIMITER = "_#_";
public static final String ERROR_DATA_DELIMITER = "_:::_";
public static final Integer USER_STATUS_ACTIVATE = 1;
public static final Integer USER_STATUS_UNACTIVATE = 0;
public static final Integer USER_TYPE_IS_ACCOUNT = 1;
public static final Integer USER_TYPE_IS_NORMAL = 0;
public static final Integer ACCOUNT_IS_PERSONAL = 1;
public static final Integer ACCOUNT_IS_COMPANY = 0;
public static final Integer BILL_STATUS_ACTVATE = 1;
public static final Integer BILL_STATUS_UNACTIVATE = 0;
public static final Integer BUSINESS_LICENSE_INIT = 0;
public static final Integer BUSINESS_LICENSE_APPROVING = 1;
public static final Integer BUSINESS_LICENSE_APPROVED = 2;
public static final Integer BUSINESS_LICENSE_REJECT = 3;
public static final String USER_ACCOUNT_LIST_SIZE = "ACCOUNT_SIZE";
public static final String USER_CURRENT_GROUP_ID = "CURRENT_GROUP";
public static final String USER_SELF_ACCOUNT_ID="SELF_ACCOUNT_ID";
public static final String COOKIE_USER_ID="CUID";
public static final String COOKIE_ACCOUNT_ID="CAID";
public static final String COOKIE_USER_NAME="CUNAME";
public static final String COOKIE_NICK_NAME="N_NAME";
public static final String COOKIE_USER_PASS="<PASSWORD>";
public static final String COOKIE_USER_HEADER_PIC="CUHP";
public static final String COOKIE_USER_REGISTER_TYPE="CURT";
public static final String COOKIE_USER_TYPE="CUT";
public static final String COOKIE_JSESSION_ID = "JSESSIONID";
public static final String COOKIE_GROUP_ROLE_ID = "CGRID";
public static final String COOKIE_GROUP_ID = "CGID";
public static final String COOKIE_COURSE_ID = "CCID";
public static final String COOKIE_HEADER_IMG = "CHI";
public static final String COOKIE_LOGO_IMG ="CLI";
public static final String COOKIE_FOOTER_IMG = "CFI";
public static final String COOKIE_BANNER_IMG = "CBI";
public static final String COOKIE_HEADER_IMG_LINK_URL = "CHILU";
public static final String COOKIE_LOGO_IMG_LINK_URL ="CLILU";
public static final String COOKIE_FOOTER_IMG_LINK_URL = "CFILU";
public static final String COOKIE_BANNER_IMG_LINK_URL = "CBILU";
public static final String COOKIE_MOBILE_VALIDATION_CODE="MV_CODE";
public static final String COOKIE_PICTURE_VALIDATION_CODE="P_CODE";
public static final short CLASSIFICATION_ITEMS_TYPE_PRESENTATION = 1;
public static final short CLASSIFICATION_ITEMS_TYPE_COURSE_ONLINE = 21;
public static final short CLASSIFICATION_ITEMS_TYPE_COURSE_OFFLINE = 22;
public static final short CLASSIFICATION_ITEMS_TYPE_COURSE_ONLIVE = 23;
public static final short CLASSIFICATION_ITEMS_TYPE_KNOWLEDGEPOINT = 3;
public static final short CLASSIFICATION_ITEMS_TYPE_COURSEPACKAGE = 4;
public static final short TAGS_ITEMS_TYPE_PRESENTATION = 1;
public static final short TAGS_ITEMS_TYPE_COURSE_ONLINE = 21;
public static final short TAGS_ITEMS_TYPE_COURSE_OFFLINE = 22;
public static final short TAGS_ITEMS_TYPE_COURSE_ONLIVE = 23;
public static final short TAGS_ITEMS_TYPE_KNOWLEDGEPOINT = 3;
public static final short TAGS_ITEMS_TYPE_COURSEPACKAGE = 4;
public static final short TAGS_ITEMS_TYPE_EXAMINATION = 5;
public static final String DEFAULT_PASS_WORD="<PASSWORD>";
public static final Integer PRESENTATION_FILES_TYPE_SCORM = 0;
public static final Integer PRESENTATION_FILES_TYPE_PACKAGE = 1;
public static final Integer TYPE_NO_PUBLISH = 0;
public static final Integer TYPE_IS_PUBLISH = 1;
public static final Integer NUMBER_TEN=10;
public static final Integer NUMBER_FIVE=5;
public static final String MAIL_HEADER_DATA = ";";
/**
* The suffix of Excel 2003.
*/
public static final String XLS = "xls";
/**
* The suffix of Excel 2007.
*/
public static final String XLSX = "xlsx";
public static final String DELIMITER_CELL_DATA = "_&_";
/**
* Separator by different characters for |
*/
public static final String SEPARATOR = "|";
/**
* Separator by different characters for _@_
*/
public static final String DELIMITER_ROW = "_@_";
/**
* Separator by different characters for _#_
*/
public static final String DELIMITER_DATA = "_#_";
/**
* Separator by different characters for ]=[
*/
public static final String DELIMITER_ATTR = "]=[";
/**
* Separator by different characters for _$_
*/
public static final String DELIMITER_DOLLER = "_$_";
/**
* Separator by different characters for ]@[
*/
public static final String DELIMITER_CELL_STYLE = "]@[";
/**
* Separator by different characters for comma
*/
public static final String DELIMITER_COMMA = ",";
public static final String DELIMITER_HR = "_";
public static final String DELIMITER_SEMICOLON = ";";
public static final String DELIMITER_SEPARATOR = "_|_";
public static final String FOLDER_MEDIA = "vod";
public static final String FOLDER_SCROM = "scrom";
public static final String FOLDER_IMAGE = "img";
public static final String FOLDER_PACKAGE = "package";
public static final String[] IMAGE_TYPE = {"jpg","JPG","gif","GIF","jpeg","JPEG","png","PNG","swf","SWF"};
public static final String[] PPT_FORMAT = {"ppt","PPT","pptx","PPTX"};
public static final String[] MEDIA_MP3 = {"mp3","MP3"};
public static final String[] OFFICE_FILE_TYPES = {"ppt","PPT","pptx","PPTX","xls","XLS","xlsx","XLSX","doc","DOC","docx","DOCX","txt","TXT","pdf","PDF"};
public static final Integer COURSE_TYPE_ONLINE = 1;
public static final Integer COURSE_TYPE_OFFLINE = 2;
public static final Integer COURSE_TYPE_ONLIVE = 3;
public static final int QUEUE_WAIT_SECONDS = 30;
public static final String DELIMITER_SLASH = "/";
public static final String DELIMITER_FULL = ".";
public static final String MEDIA_COVERT_STATUS_MRSTART_SUCCESS = "SUCCEEDED";
public static final String MEDIA_COVERT_STATUS_MRSTART_PROCESSING = "RUNNING";
public static final Integer SERVICE_PLAN_TRIAL = 1;
public static final Integer SERVICE_PLAN_TWO = 2;
public static final Integer SERVICE_PLAN_THREE = 3;
public static final Integer SERVICE_PLAN_FOUR = 4;
public static final String SERVICE_PLAN_CMOBO_TYPE_MAX_CLASSIFICATION_COUNT = "maxClassificationCount";
public static final Integer ACCOUNT_ITEMS_REL_ITEMS_TYPE_PLAN = 1;
public static final Integer ACCOUNT_ITEMS_REL_ITEMS_TYPE_CLASSIFICATION = 2;
public static final Integer ACCOUNT_ITEMS_REL_ACCOUNT_TYPE_STANDARD = 1;
public static final Integer ACCOUNT_ITEMS_REL_ACCOUNT_TYPE_PREFERENTIAL = 2;
public static final short USE_REGISTER_TYPE_PHONE = 1;
public static final short USE_REGISTER_TYPE_MAIL = 2;
public static final short USE_REGISTER_TYPE_COMPANY = 3;
public static final short USE_REGISTER_TYPE_THREE_PART = 4;
public static final short USE_REGISTER_TYPE_OTHERS= 5;
public static final String USE_REGISTER_TYPE_PHONE_String = "1";
public static final String USE_REGISTER_TYPE_MAIL_String = "2";
public static final String USE_REGISTER_TYPE_COMPANY_String = "3";
public static final String USE_REGISTER_TYPE_THREE_PART_String = "4";
// public static final String DOMAIN_POSTIFX = ".deodio.com.cn";
public static final String DOMAIN_WWW = "www";
public static final String DOMIAN_CONTENT_ROOT = "/deodio-main";
public static final String DOMAIN_SESSION_ACCOUNT_ID="DSAID";
public static final String GROUP_ROLE_GROUP_LEADER_ID = "10000";
public static final String GROUP_ROLE_CONTENT_CREATOR_ID = "10001";
public static final String GROUP_ROLE_VIEWER_ID = "10002";
public static final String ROLE_CONTENT_ACCOUNT_ID = "ACCOUNT";
public static final short USER_TYPE_PERSONAL = 1;
public static final short USER_TYPE_COMPANY = 2;
public static final short HAS_LEADER_PRIVILEDGE_YES = 1;
public static final short HAS_LEADER_PRIVILEDGE_NO = 0;
public static final String REFRESH_IMG_LOGO = "refresh";
/*1:presentation, 2:quiz,3:survey, 4:course*/
public static final short GROUP_ITEMS_TYPE_PRESENTATION = 1;
public static final short GROUP_ITEMS_TYPE_QUIZ = 2;
public static final short GROUP_ITEMS_TYPE_SURVEY = 3;
public static final short GROUP_ITEMS_TYPE_COURSE = 4;
public static final short GROUP_ITEMS_TYPE_PACKAGE = 5;
public static final boolean INSERT_SYS_CLASSIFICATION_FLAG_PRE_DEL_DO = true;
public static final boolean INSERT_SYS_CLASSIFICATION_FLAG_PRE_DEL_UNDO = false;
public static final short GROUP_TYPE_PERMISSION = 1;
public static final short GROUP_TYPE_MODEL_FUNCTION = 2;
public static final int SYSTEM_TEMPLATE_INVITE_MAIL_SUBJECT = 10005;
public static final int SYSTEM_TEMPLATE_INVITE_MAIL_CONTENT = 10006;
public static final int SYSTEM_TEMPLATE_INVITE_MAIL_TEMPLATE = 10002;
public static final int SYSTEM_TEMPLATE_INVITE_MAIL_REINVITE = 10003;
public static final int SYSTEM_TEMPLATE_INVITE_MAIL_TEXT_TEMPLATE = 10007;
public static final int SYSTEM_TEMPLATE_INVITE_MAIL_TEXT_TEMPLATE_COMMON_MAIL = 10008;
public static final int SYSTEM_TEMPLATE_INVITE_MAIL_TEXT_TEMPLATE_BATCH_IMPORT_MAIL = 10010;
public static final Integer PRESENTATION_IS_COUNT_DOWN_FLAG_YES = 1;
public static final Integer PRESENTATION_IS_COUNT_DOWN_FLAG_NO = 0;
public static final Short PRESENTATION_PUBLISH_IS_COURSE_YES = 1;
public static final Short PRESENTATION_PUBLISH_IS_COURSE_NO = 0;
public static final Integer ATTACHMENT_TYPE_PRESENTATION = 5;
public static final Integer ATTACHMENT_TYPE_SCROM = 50;
public static final Integer ATTACHMENT_TYPE_PACKAGE = 51;
public static final Integer ATTACHMENT_TYPE_SLIDES = 53;
public static final Integer ATTACHMENT_TYPE_MEDIA = 54;
public static final String SCROM_MANIFEST_FILE_NAME = "imsmanifest.xml";
public static final Integer PACKAGE_IS_CONVERT_YES = 1;
public static final Integer PACKAGE_IS_CONVERT_NO = 0;
public static final Integer ATTACHMENT_IS_CONVERT_YES = 1;
public static final Integer ATTACHMENT_IS_CONVERT_NO = 0;
//站内信状态 0:保存 1:已发布
public static final String MESSAGE_TEXT_STATUS_SAVE="0";
public static final String MESSAGE_TEXT_STATUS_PUBLISH="1";
//站内信消息类型
public static final String MESSAGE_TEXT_TYPE_JOIN="1";
//站内信发送对象类型
public static final Integer MESSAGE_TEXT_REC_TYPE_TEACHER=1;
//站内信内容查看状态 0:未查看 1:查看
public static final String MESSAGE_VIEW_STATUS_ZERO="0";
public static final String MESSAGE_VIEW_STATUS_ONE="1";
public static final String SLIDE_EXT_PNG = "png";
public static final String MEDIA_EXT_MP4 = "mp4";
public static final int PRESENTATION_MODEL_SCORM = 0;
public static final int PRESENTATION_MODEL_PACKAGE = 1;
public static final int PRESENTATION_MODEL_SYNC = 2;
public static final int PRESENTATION_MODEL_EXTERNAL = 3;
public static final Integer COURSE_RECORD_IS_PASS = 1;
public static final Integer COURSE_RECORD_IS_CONTINUE = 0;
public static final Integer TRAINEE_COURSE_REL_COURSE = 1;
public static final Integer TRAINEE_COURSE_REL_PACKAGE = 2;
/*课后作业60;考试61;调查问卷62 附件63*/
public static final String TRAINEE_COURSE_HOMEWORK = "60";
public static final String TRAINEE_COURSE_QUIZ = "61";
public static final String TRAINEE_COURSE_SURVEY = "62";
public static final String TRAINEE_COURSE_ATTACH = "63";
public static final String TRAINEE_COURSE_APPRAISE = "64";
//内容类型 1:考试 2:调查问卷
public static final Integer TRAINEE_EXAM_TYPE_QUIZ = 1;
public static final Integer TRAINEE_EXAM_TYPE_SURVEY = 2;
//状态 1:新提交 2:已阅
public static final Integer TRAINEE_EXAM_STATUS_NEWSUBMIT = 1;
public static final Integer TRAINEE_EXAM_STATUS_READ = 2;
//登录有效性
public static final Short LOGIN_IS_NEED_CHECK_YES = 1;
public static final Short LOGIN_IS_NEED_CHECK_NO = 0;
public static final Short LOGIN_IS_VALID_NO = 0;
//编辑状态 0: 未编辑 1: 正在编辑
public static final Integer ISNOT_EDIT = 0;
public static final Integer IS_EDIT = 1;
//手机号码是否已验证: 0 未验证 1 已验证
public static final Short PHONE_NUMBER_NOT_CHECKED = 0;
public static final Short PHONE_NUMBER_IS_CHECKED = 1;
//邮箱是否已验证: 0 未验证 1 已验证
public static final Short EMAIL_NOT_CHECKED = 0;
public static final Short EMAIL_IS_CHECKED = 1;
//默认题库ID
public static final String DEFAULT_BANK_ID = "999999";
//试题来源 0:题库 1:手动试卷
public static final Integer QUIZ_SUBJECT_FROM_MANUAL = 1;
public static final Integer QUIZ_SUBJECT_FROM_BANK = 0;
//0: 随机题 1:必考题
public static final Integer QUIZ_SUBJECT_ISNOT_REQUIRED = 0;
public static final Integer QUIZ_SUBJECT_IS_REQUIRED = 1;
//用户注册方式
public static final String REGISTER_TYPE_PHONE = "1";
public static final String REGISTER_TYPE_MAIL = "2";
public static final String REGISTER_TYPE_COMPANY = "3";
//用户详细注册校验内容
public static final String REGISTER_CHECK_OGCODE="organizationCode";
public static final String REGISTER_CHECK_LSCODE="licenseCode";
public static final String REGISTER_CHECK_IDCODE="IDCode";
//小组内课程管理和快速学习
public static final String GROUP_COURSE_MANAGER_SHOW="GCMS";
public static final String GROUP_COURSE_STUDY_SHOW="GCSS";
public static final String GROUP_COURSE_MANAGER_AND_STUDY_SHOW="GCMASS";
public static final String GROUP_COURSE_MANAGER_AND_STUDY_HIDDEN="GCMASH";
//切换账户
public static final String CHANGE_ACCOUNT_SHOW="CACCS";
public static final String CHANGE_ACCOUNT_HIDDEN="CACCH";
//标题栏显示
public static final String GROUP_USER_ROLE_ID="userRoleId";
//用户切换账户后跳转个人中心
public static final String USER_CHANGE_ACCOUNT_TO="CHANGE_TO";
public static final String USER_CHANGE_ACCOUNT_TO_SELF="SELF";
public static final String USER_CHANGE_ACCOUNT_TO_OTHER="OTHER";
//未登录不调转登录页面的链接
public static final String USER_JOIN_GROUP="/deodio-main/group/active_join_group.html";
public static final String USER_GROUP_REGISTER="/deodio-main/group/toGroupFormRegister.html";
public static final String USER_GROUP_SETPWD="/deodio-main/group/setPwd.html";
/* //小組课程列表排序方式
public static final String GROUP_COURSE_ORDER_BY_STUDY_TIME="studyTime";
public static final String GROUP_COURSE_ORDER_BY_ADD_TIME="addTime";*/
}
| 15,158 | 0.747529 | 0.730012 | 361 | 39.637119 | 28.461933 | 154 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.612188 | false | false | 2 |
fc8774ba5a6b339e206f7bcfd3b83c0440ede4c2 | 37,709,812,874,592 | 8823215d6ad817e6b0f59d2a177cee1ecce6858c | /src/test/java/com/azure/app/BookTest.java | 97ab0ca0c5cb73d64f310b7216672d25d3e95d50 | [
"MIT"
] | permissive | conniey/intern-project | https://github.com/conniey/intern-project | 4ffd121efbd8cc878de1a6bec65c9db629fc972e | 0fc302764823be1b3dfb29894569597a9c430a5b | refs/heads/master | 2022-12-13T16:27:22.981000 | 2019-12-11T21:25:48 | 2019-12-11T21:25:48 | 193,846,048 | 0 | 1 | MIT | false | 2022-10-19T01:05:35 | 2019-06-26T06:49:26 | 2019-12-11T21:25:52 | 2022-10-19T01:05:32 | 5,119 | 0 | 1 | 5 | Java | false | false | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.app;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.File;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@RunWith(Parameterized.class)
public class BookTest {
/**
* Verifies that the correct information was passed to the Book object
*/
@Test
public void testGoodBookChecker() {
//Arrange
final URL folder = BookTest.class.getClassLoader().getResource(".");
assertNotNull(folder);
Book book = new Book("Title", new Author("Good", "Book"), new File(folder.getPath() + "KK8.jpg").toURI());
//Act and Assert
assertTrue(book.isValid());
}
//TEST INVALID BOOKS
/**
* Gathers the data for the Book object that'll be tested
*
* @return Collection of Book objects
*/
@Parameterized.Parameters
public static Collection<Book[]> data() {
//Arrange
final URL folder = BookTest.class.getClassLoader().getResource(".");
assertNotNull(folder);
return Arrays.asList(new Book[][]{
{new Book("", new Author("Good", "Book"), new File(folder.getPath() + "KK8.jpg").toURI())},
{new Book("Title", new Author("Good", ""), new File(folder.getPath() + "KK8.jpg").toURI())},
{new Book("Title", new Author("", "Bad"), new File(folder.getPath() + "KK8.jpg").toURI())},
{new Book("Title", new Author("", ""), new File(folder.getPath() + "KK8.jpg").toURI())},
{new Book("Title", new Author("Good", "Author"), null)}
});
}
private Book bInput;
private boolean expected;
/**
* Constructor for the BookTest to pass the parameters and set the
* expected result
*
* @param b - one of the faulty Book objects
*/
public BookTest(Book b) {
this.bInput = b;
this.expected = false;
}
/**
* Verifies that none of the parameters pass the checkBook test
*/
@Test
public void testInvalidBooks() {
assertEquals(expected, bInput.isValid());
}
}
| UTF-8 | Java | 2,356 | java | BookTest.java | Java | [] | null | [] | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.app;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.File;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@RunWith(Parameterized.class)
public class BookTest {
/**
* Verifies that the correct information was passed to the Book object
*/
@Test
public void testGoodBookChecker() {
//Arrange
final URL folder = BookTest.class.getClassLoader().getResource(".");
assertNotNull(folder);
Book book = new Book("Title", new Author("Good", "Book"), new File(folder.getPath() + "KK8.jpg").toURI());
//Act and Assert
assertTrue(book.isValid());
}
//TEST INVALID BOOKS
/**
* Gathers the data for the Book object that'll be tested
*
* @return Collection of Book objects
*/
@Parameterized.Parameters
public static Collection<Book[]> data() {
//Arrange
final URL folder = BookTest.class.getClassLoader().getResource(".");
assertNotNull(folder);
return Arrays.asList(new Book[][]{
{new Book("", new Author("Good", "Book"), new File(folder.getPath() + "KK8.jpg").toURI())},
{new Book("Title", new Author("Good", ""), new File(folder.getPath() + "KK8.jpg").toURI())},
{new Book("Title", new Author("", "Bad"), new File(folder.getPath() + "KK8.jpg").toURI())},
{new Book("Title", new Author("", ""), new File(folder.getPath() + "KK8.jpg").toURI())},
{new Book("Title", new Author("Good", "Author"), null)}
});
}
private Book bInput;
private boolean expected;
/**
* Constructor for the BookTest to pass the parameters and set the
* expected result
*
* @param b - one of the faulty Book objects
*/
public BookTest(Book b) {
this.bInput = b;
this.expected = false;
}
/**
* Verifies that none of the parameters pass the checkBook test
*/
@Test
public void testInvalidBooks() {
assertEquals(expected, bInput.isValid());
}
}
| 2,356 | 0.62309 | 0.620968 | 75 | 30.413334 | 28.626837 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.613333 | false | false | 2 |
4e7a15f9a0fc981b278ca1acbd5140291bc2f6fe | 33,397,665,699,786 | 699efa1564f7385085c43fcfb4cf9aea1d9186dc | /src/com/exam/EmailServlet.java | def5563113c776af817a2c0cd7d97b0f864f38b0 | [] | no_license | hussienalbared/cloud | https://github.com/hussienalbared/cloud | e92834637c33a1e36aba4a0332446e835bc1fbc6 | 706fdeb8d4a949cd897e7f3f905b768c6aa56400 | refs/heads/master | 2021-01-13T13:22:57.843000 | 2016-11-11T23:40:48 | 2016-11-11T23:40:48 | 72,448,959 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.exam;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class EmailServlet extends HttpServlet{
/**
*
*/
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException ,IOException {
String rec=req.getParameter("t");
String tex=req.getParameter("tex");
String subb=req.getParameter("subjec");
Tr.sendSimpleMessage(rec, tex, subb);
}
}
| UTF-8 | Java | 648 | java | EmailServlet.java | Java | [] | null | [] | package com.exam;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class EmailServlet extends HttpServlet{
/**
*
*/
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException ,IOException {
String rec=req.getParameter("t");
String tex=req.getParameter("tex");
String subb=req.getParameter("subjec");
Tr.sendSimpleMessage(rec, tex, subb);
}
}
| 648 | 0.736111 | 0.736111 | 41 | 14.804878 | 22.186811 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.04878 | false | false | 2 |
b0ce0402e84e2e3b2699ad8f528a84106bf61265 | 32,186,484,975,993 | bdfcf4705440a9b950c347cbc494dacd8208689a | /src/main/java/org/neustupov/videonotes/service/StickerService.java | 7ca4a622cce7e38887fc727773407d18eebf5b5c | [] | no_license | neustupov/videonotes | https://github.com/neustupov/videonotes | 21122666f3cad2be3bd1ba3b5da2721afbe75e5d | cda0a8edcc735a77e0b808f0d36c1622ebd490a3 | refs/heads/master | 2022-12-31T15:53:30.624000 | 2020-10-05T15:40:52 | 2020-10-05T15:40:52 | 299,332,646 | 0 | 0 | null | false | 2020-10-05T15:40:53 | 2020-09-28T14:21:06 | 2020-10-04T16:48:14 | 2020-10-05T15:40:52 | 328 | 0 | 0 | 0 | Vue | false | false | package org.neustupov.videonotes.service;
import java.util.ArrayList;
import java.util.Optional;
import org.neustupov.videonotes.model.Board;
import org.neustupov.videonotes.model.Sticker;
import org.neustupov.videonotes.repo.BoardRepository;
import org.neustupov.videonotes.repo.StickerRepository;
import org.neustupov.videonotes.to.StickerTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StickerService {
private BoardRepository boardRepository;
private StickerRepository stickerRepository;
@Autowired
public StickerService(BoardRepository boardRepository, StickerRepository stickerRepository) {
this.boardRepository = boardRepository;
this.stickerRepository = stickerRepository;
}
public Sticker save(StickerTo stickerTo){
Board board = boardRepository.findById(stickerTo.getBoardId()).orElseThrow(IllegalArgumentException::new);
Sticker sticker = stickerRepository.save(new Sticker(stickerTo.getTitle(), new ArrayList<>(),
new ArrayList<>(), board));
board.getStickers().add(sticker);
return sticker;
}
}
| UTF-8 | Java | 1,148 | java | StickerService.java | Java | [] | null | [] | package org.neustupov.videonotes.service;
import java.util.ArrayList;
import java.util.Optional;
import org.neustupov.videonotes.model.Board;
import org.neustupov.videonotes.model.Sticker;
import org.neustupov.videonotes.repo.BoardRepository;
import org.neustupov.videonotes.repo.StickerRepository;
import org.neustupov.videonotes.to.StickerTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StickerService {
private BoardRepository boardRepository;
private StickerRepository stickerRepository;
@Autowired
public StickerService(BoardRepository boardRepository, StickerRepository stickerRepository) {
this.boardRepository = boardRepository;
this.stickerRepository = stickerRepository;
}
public Sticker save(StickerTo stickerTo){
Board board = boardRepository.findById(stickerTo.getBoardId()).orElseThrow(IllegalArgumentException::new);
Sticker sticker = stickerRepository.save(new Sticker(stickerTo.getTitle(), new ArrayList<>(),
new ArrayList<>(), board));
board.getStickers().add(sticker);
return sticker;
}
}
| 1,148 | 0.801394 | 0.801394 | 33 | 33.78788 | 28.934364 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 2 |
2a5ec187a4d29e60bd629f24e8de62bdc9fee925 | 21,483,426,443,721 | 133a51cc595fb8d149c10a440da59ede9dc0b007 | /medical_record/src/medicalfile/AddUser.java | 89622c17f751444da99a6a6eac526a3e7221ac87 | [] | no_license | chenhaozai/SoftEng | https://github.com/chenhaozai/SoftEng | 237e2fe93c279bf57ce18243200961f03f528402 | e9141bc49a1940b36f5262638d5eb3b964342269 | refs/heads/master | 2016-08-04T15:21:06.734000 | 2014-01-24T18:26:39 | 2014-01-24T18:26:39 | null | 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 medicalfile;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
/**
*
* @author gloria
*/
public class AddUser extends javax.swing.JFrame {
/**
* Creates new form AddUser
*/
String role;
static Statement stmt = null;
static Connection conn = null;
String pass, user, roleType;
int row;
public AddUser(String role, Statement stmt) {
initComponents();
setSize(580, 450);
this.role = role;
this.stmt = stmt;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jButtonAdd = new javax.swing.JButton();
jButtonLogOut = new javax.swing.JButton();
jButtonDelete = new javax.swing.JButton();
jUserNameTextField = new javax.swing.JTextField();
jPasswordTextField = new javax.swing.JTextField();
jRoleComboBox = new javax.swing.JComboBox();
jLabel5 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
jButtonAdd.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButtonAdd.setText("Προσθήκη");
jButtonAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonAddActionPerformed(evt);
}
});
getContentPane().add(jButtonAdd);
jButtonAdd.setBounds(110, 330, 110, 50);
jButtonLogOut.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButtonLogOut.setText("Αποσύνδεση");
jButtonLogOut.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonLogOutActionPerformed(evt);
}
});
getContentPane().add(jButtonLogOut);
jButtonLogOut.setBounds(390, 330, 110, 50);
jButtonDelete.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButtonDelete.setText("Διαγραφή");
jButtonDelete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonDeleteActionPerformed(evt);
}
});
getContentPane().add(jButtonDelete);
jButtonDelete.setBounds(250, 330, 110, 50);
getContentPane().add(jUserNameTextField);
jUserNameTextField.setBounds(240, 110, 120, 20);
getContentPane().add(jPasswordTextField);
jPasswordTextField.setBounds(240, 160, 120, 20);
jRoleComboBox.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jRoleComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Secretary", "Nurse", "Doctor", "Administrator" }));
getContentPane().add(jRoleComboBox);
jRoleComboBox.setBounds(240, 200, 120, 30);
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel5.setText("~ Εγγραφή Νέου Χρήστη ~");
getContentPane().add(jLabel5);
jLabel5.setBounds(100, 10, 390, 40);
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel4.setText("Ρόλος :");
getContentPane().add(jLabel4);
jLabel4.setBounds(150, 210, 70, 17);
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel3.setText("Κωδικός :");
getContentPane().add(jLabel3);
jLabel3.setBounds(150, 160, 80, 17);
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel2.setText("Αναγνωριστικό χρήστη :");
getContentPane().add(jLabel2);
jLabel2.setBounds(60, 110, 160, 20);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/medicalfile/newpackage/Medical_2.jpg"))); // NOI18N
getContentPane().add(jLabel1);
jLabel1.setBounds(-10, 0, 570, 410);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButtonLogOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLogOutActionPerformed
// TODO add your handling code here:
this.setVisible(false);
new Authentication(stmt, conn).setVisible(true);
}//GEN-LAST:event_jButtonLogOutActionPerformed
private void jButtonAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAddActionPerformed
// TODO add your handling code here:
this.user = jUserNameTextField.getText();
this.pass = jPasswordTextField.getText();
this.roleType = (String) jRoleComboBox.getSelectedItem();
addition(stmt, user, pass, roleType);
}//GEN-LAST:event_jButtonAddActionPerformed
private void jButtonDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDeleteActionPerformed
// TODO add your handling code here:
this.user = jUserNameTextField.getText();
this.pass = jPasswordTextField.getText();
this.roleType = (String) jRoleComboBox.getSelectedItem();
System.out.println(delete(stmt, user, pass, roleType));
}//GEN-LAST:event_jButtonDeleteActionPerformed
public String addition(Statement stmt, String user, String pass, String roleType) {
if (stmt != null) {
try {
String sql;
sql = "INSERT INTO user (username, password, role) VALUES ('" + user + "','" + pass + "','" + roleType + "');";
System.out.println(sql);
stmt.executeUpdate(sql);
} catch (SQLException es) {
System.out.println("Unable to insert int the databese");
JOptionPane.showMessageDialog(null, "Μη ολοκληρωμένα πεδία.", "Ανεπιτυχής Δημιουργία", JOptionPane.ERROR_MESSAGE);
return "ERROR";
}
if (stmt == null) {
JOptionPane.showMessageDialog(null, "Μη ολοκληρωμένα πεδία.", "Ανεπιτυχής Δημιουργία", JOptionPane.ERROR_MESSAGE);
return "ERROR";
} else {
JOptionPane.showMessageDialog(null, "Ο νέος χρήστης προστέθηκε.", "Επιτυχής Προσθήκη", JOptionPane.INFORMATION_MESSAGE);
}
}
return "Added";
}
public String delete(Statement stmt, String user, String pass, String roleType) {
if (stmt != null) {
try {
String sql;
sql = "DELETE FROM user WHERE username= '" + user + "' AND password = '" + pass + "' AND role='" + roleType + "';";
this.row = stmt.executeUpdate(sql);
} catch (SQLException es) {
System.out.println("Unable to insert into the databese");
JOptionPane.showMessageDialog(null, "Μη ολοκληρωμένα πεδία.", "Ανεπιτυχής Δημιουργία", JOptionPane.ERROR_MESSAGE);
}
if (stmt == null) {
JOptionPane.showMessageDialog(null, "Μη ολοκληρωμένα πεδία.", "Ανεπιτυχής Δημιουργία", JOptionPane.ERROR_MESSAGE);
return "ERROR";
} else if (row == 0) {
JOptionPane.showMessageDialog(null, "Δεν υπάρχει ο χρήστης.", "Ανεπιτυχής Διαγραφή", JOptionPane.INFORMATION_MESSAGE);
return "This user does not exist";
} else {
JOptionPane.showMessageDialog(null, "Ο χρήστης διαγράφηκε επιτυχώς.", "Επιτυχής Διαγραφή", JOptionPane.INFORMATION_MESSAGE);
return "Deleted";
}
}
return "ERROR";
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButtonAdd;
private javax.swing.JButton jButtonDelete;
private javax.swing.JButton jButtonLogOut;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JTextField jPasswordTextField;
private javax.swing.JComboBox jRoleComboBox;
private javax.swing.JTextField jUserNameTextField;
// End of variables declaration//GEN-END:variables
}
| UTF-8 | Java | 9,226 | java | AddUser.java | Java | [
{
"context": "import javax.swing.JOptionPane;\n\n/**\n *\n * @author gloria\n */\npublic class AddUser extends javax.swing.JFra",
"end": 349,
"score": 0.9900834560394287,
"start": 343,
"tag": "USERNAME",
"value": "gloria"
},
{
"context": " jUserNameTextField.getText();\n this.... | 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 medicalfile;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
/**
*
* @author gloria
*/
public class AddUser extends javax.swing.JFrame {
/**
* Creates new form AddUser
*/
String role;
static Statement stmt = null;
static Connection conn = null;
String pass, user, roleType;
int row;
public AddUser(String role, Statement stmt) {
initComponents();
setSize(580, 450);
this.role = role;
this.stmt = stmt;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jButtonAdd = new javax.swing.JButton();
jButtonLogOut = new javax.swing.JButton();
jButtonDelete = new javax.swing.JButton();
jUserNameTextField = new javax.swing.JTextField();
jPasswordTextField = new javax.swing.JTextField();
jRoleComboBox = new javax.swing.JComboBox();
jLabel5 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
jButtonAdd.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButtonAdd.setText("Προσθήκη");
jButtonAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonAddActionPerformed(evt);
}
});
getContentPane().add(jButtonAdd);
jButtonAdd.setBounds(110, 330, 110, 50);
jButtonLogOut.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButtonLogOut.setText("Αποσύνδεση");
jButtonLogOut.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonLogOutActionPerformed(evt);
}
});
getContentPane().add(jButtonLogOut);
jButtonLogOut.setBounds(390, 330, 110, 50);
jButtonDelete.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jButtonDelete.setText("Διαγραφή");
jButtonDelete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonDeleteActionPerformed(evt);
}
});
getContentPane().add(jButtonDelete);
jButtonDelete.setBounds(250, 330, 110, 50);
getContentPane().add(jUserNameTextField);
jUserNameTextField.setBounds(240, 110, 120, 20);
getContentPane().add(jPasswordTextField);
jPasswordTextField.setBounds(240, 160, 120, 20);
jRoleComboBox.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jRoleComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Secretary", "Nurse", "Doctor", "Administrator" }));
getContentPane().add(jRoleComboBox);
jRoleComboBox.setBounds(240, 200, 120, 30);
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel5.setText("~ Εγγραφή Νέου Χρήστη ~");
getContentPane().add(jLabel5);
jLabel5.setBounds(100, 10, 390, 40);
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel4.setText("Ρόλος :");
getContentPane().add(jLabel4);
jLabel4.setBounds(150, 210, 70, 17);
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel3.setText("Κωδικός :");
getContentPane().add(jLabel3);
jLabel3.setBounds(150, 160, 80, 17);
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel2.setText("Αναγνωριστικό χρήστη :");
getContentPane().add(jLabel2);
jLabel2.setBounds(60, 110, 160, 20);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/medicalfile/newpackage/Medical_2.jpg"))); // NOI18N
getContentPane().add(jLabel1);
jLabel1.setBounds(-10, 0, 570, 410);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButtonLogOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLogOutActionPerformed
// TODO add your handling code here:
this.setVisible(false);
new Authentication(stmt, conn).setVisible(true);
}//GEN-LAST:event_jButtonLogOutActionPerformed
private void jButtonAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAddActionPerformed
// TODO add your handling code here:
this.user = jUserNameTextField.getText();
this.pass = <PASSWORD>.getText();
this.roleType = (String) jRoleComboBox.getSelectedItem();
addition(stmt, user, pass, roleType);
}//GEN-LAST:event_jButtonAddActionPerformed
private void jButtonDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDeleteActionPerformed
// TODO add your handling code here:
this.user = jUserNameTextField.getText();
this.pass = jPasswordTextField.getText();
this.roleType = (String) jRoleComboBox.getSelectedItem();
System.out.println(delete(stmt, user, pass, roleType));
}//GEN-LAST:event_jButtonDeleteActionPerformed
public String addition(Statement stmt, String user, String pass, String roleType) {
if (stmt != null) {
try {
String sql;
sql = "INSERT INTO user (username, password, role) VALUES ('" + user + "','" + pass + "','" + roleType + "');";
System.out.println(sql);
stmt.executeUpdate(sql);
} catch (SQLException es) {
System.out.println("Unable to insert int the databese");
JOptionPane.showMessageDialog(null, "Μη ολοκληρωμένα πεδία.", "Ανεπιτυχής Δημιουργία", JOptionPane.ERROR_MESSAGE);
return "ERROR";
}
if (stmt == null) {
JOptionPane.showMessageDialog(null, "Μη ολοκληρωμένα πεδία.", "Ανεπιτυχής Δημιουργία", JOptionPane.ERROR_MESSAGE);
return "ERROR";
} else {
JOptionPane.showMessageDialog(null, "Ο νέος χρήστης προστέθηκε.", "Επιτυχής Προσθήκη", JOptionPane.INFORMATION_MESSAGE);
}
}
return "Added";
}
public String delete(Statement stmt, String user, String pass, String roleType) {
if (stmt != null) {
try {
String sql;
sql = "DELETE FROM user WHERE username= '" + user + "' AND password = '" + <PASSWORD> + "' AND role='" + roleType + "';";
this.row = stmt.executeUpdate(sql);
} catch (SQLException es) {
System.out.println("Unable to insert into the databese");
JOptionPane.showMessageDialog(null, "Μη ολοκληρωμένα πεδία.", "Ανεπιτυχής Δημιουργία", JOptionPane.ERROR_MESSAGE);
}
if (stmt == null) {
JOptionPane.showMessageDialog(null, "Μη ολοκληρωμένα πεδία.", "Ανεπιτυχής Δημιουργία", JOptionPane.ERROR_MESSAGE);
return "ERROR";
} else if (row == 0) {
JOptionPane.showMessageDialog(null, "Δεν υπάρχει ο χρήστης.", "Ανεπιτυχής Διαγραφή", JOptionPane.INFORMATION_MESSAGE);
return "This user does not exist";
} else {
JOptionPane.showMessageDialog(null, "Ο χρήστης διαγράφηκε επιτυχώς.", "Επιτυχής Διαγραφή", JOptionPane.INFORMATION_MESSAGE);
return "Deleted";
}
}
return "ERROR";
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButtonAdd;
private javax.swing.JButton jButtonDelete;
private javax.swing.JButton jButtonLogOut;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JTextField jPasswordTextField;
private javax.swing.JComboBox jRoleComboBox;
private javax.swing.JTextField jUserNameTextField;
// End of variables declaration//GEN-END:variables
}
| 9,224 | 0.637387 | 0.615541 | 211 | 41.085308 | 33.072697 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.023697 | false | false | 2 |
dc2bdd70b971b28dfd32cf6da5b32679b39d46ad | 25,486,335,995,317 | e59e83d64bacbda580037a71990cbc3ef22510da | /src/main/java/com/dounets/blp/pi/process/dm/model/DmmDmnDicVO.java | 418aa923cedab47aee354726b4bd9b5ada93236a | [] | no_license | dounets/BLP | https://github.com/dounets/BLP | 93851681a3d7d371fc6eb2f65f6b4ab27d856acc | 6ffeb0360c4a2b73020f4c1cb0ac19f5110f42cf | refs/heads/alpha_v2.0.0 | 2016-08-16T17:58:33.582000 | 2016-08-02T02:48:21 | 2016-08-02T02:48:21 | 46,174,430 | 2 | 0 | null | false | 2016-08-03T02:48:08 | 2015-11-14T12:50:48 | 2016-07-18T06:58:16 | 2016-08-03T02:48:08 | 24,025 | 1 | 0 | 9 | Java | null | null | /*
*****************************************************************
*
* COPYRIGHT (C) 2011 DOU HOLDINGS NETWORKS CO., LTD. ALL RIGHTS RESERVED
*
* Create Date : 2011. 10. 24
* Change History
* ===============================================================
* DATE DEVELOPER REVISION DESCRIPTION
* ===============================================================
* 2011. 10. 24 Thinh.Pham 1.0 First Created.
* ===============================================================
*
*
*****************************************************************/
package com.dounets.blp.pi.process.dm.model;
import com.dounets.framework.ibsheet.model.IBStatus;
import com.dounets.framework.model.Model;
/**
* Table Value Object<br>
*
* @author Thinh.Pham
* @see Model
* @since J2EE 1.6
*/
public class DmmDmnDicVO extends Model implements DmmDmnDicVOKey {
private static final long serialVersionUID = -8233648461858549368L;
public DmmDmnDicVO() {
}
public DmmDmnDicVO(
String stndDmnId,
int mode
) {
this.stndDmnId = stndDmnId;
this.setIbflag(mode == 1 ? IBStatus.INSERT : mode == 2 ? IBStatus.UPDATE : mode == 3 ? IBStatus.DELETE : IBStatus.RETRIEVE);
}
/* Column Info */
String stndDmnId;
/* Column Info */
String dmnNm;
/* Column Info */
String datTpCd;
/* Column Info */
Integer datLen;
/* Column Info */
Integer datPnt;
/* Column Info */
String dmnDesc;
/* Column Info */
String rqstRsn;
/* Column Info */
String aproRjctRsn;
/* Column Info */
java.sql.Date rqstDt;
/* Column Info */
java.sql.Date aproDt;
/* Column Info */
String rqstrId;
/* Column Info */
String apstsCd;
/* Column Info */
String apverId;
/* Column Info */
String abbrNm;
/* Column Info */
String mgrCmt;
/* Column Info */
String dicTpCd;
/* Column Info */
String pjtId;
/* Column Info */
String mstDmnFlg;
/* Column Info */
String reqFlg;
/**
* Column Info Getter
*
* @return stndDmnId
*/
@Override
public String getStndDmnId() {
return stndDmnId;
}
/**
* Column Info Setter
*
* @param stndDmnId
*/
@Override
public void setStndDmnId(String stndDmnId) {
this.stndDmnId = stndDmnId;
}
/**
* Column Info Getter
*
* @return dmnNm
*/
public String getDmnNm() {
return dmnNm;
}
/**
* Column Info Setter
*
* @param dmnNm
*/
public void setDmnNm(String dmnNm) {
this.dmnNm = dmnNm;
}
/**
* Column Info Getter
*
* @return datTpCd
*/
public String getDatTpCd() {
return datTpCd;
}
/**
* Column Info Setter
*
* @param datTpCd
*/
public void setDatTpCd(String datTpCd) {
this.datTpCd = datTpCd;
}
/**
* Column Info Getter
*
* @return datLen
*/
public Integer getDatLen() {
return datLen;
}
/**
* Column Info Setter
*
* @param datLen
*/
public void setDatLen(Integer datLen) {
this.datLen = datLen;
}
/**
* Column Info Getter
*
* @return datPnt
*/
public Integer getDatPnt() {
return datPnt;
}
/**
* Column Info Setter
*
* @param datPnt
*/
public void setDatPnt(Integer datPnt) {
this.datPnt = datPnt;
}
/**
* Column Info Getter
*
* @return dmnDesc
*/
public String getDmnDesc() {
return dmnDesc;
}
/**
* Column Info Setter
*
* @param dmnDesc
*/
public void setDmnDesc(String dmnDesc) {
this.dmnDesc = dmnDesc;
}
/**
* Column Info Getter
*
* @return rqstRsn
*/
public String getRqstRsn() {
return rqstRsn;
}
/**
* Column Info Setter
*
* @param rqstRsn
*/
public void setRqstRsn(String rqstRsn) {
this.rqstRsn = rqstRsn;
}
/**
* Column Info Getter
*
* @return aproRjctRsn
*/
public String getAproRjctRsn() {
return aproRjctRsn;
}
/**
* Column Info Setter
*
* @param aproRjctRsn
*/
public void setAproRjctRsn(String aproRjctRsn) {
this.aproRjctRsn = aproRjctRsn;
}
/**
* Column Info Getter
*
* @return rqstDt
*/
public java.sql.Date getRqstDt() {
return rqstDt;
}
/**
* Column Info Setter
*
* @param rqstDt
*/
public void setRqstDt(java.sql.Date rqstDt) {
this.rqstDt = rqstDt;
}
/**
* Column Info Getter
*
* @return aproDt
*/
public java.sql.Date getAproDt() {
return aproDt;
}
/**
* Column Info Setter
*
* @param aproDt
*/
public void setAproDt(java.sql.Date aproDt) {
this.aproDt = aproDt;
}
/**
* Column Info Getter
*
* @return rqstrId
*/
public String getRqstrId() {
return rqstrId;
}
/**
* Column Info Setter
*
* @param rqstrId
*/
public void setRqstrId(String rqstrId) {
this.rqstrId = rqstrId;
}
/**
* Column Info Getter
*
* @return apstsCd
*/
public String getApstsCd() {
return apstsCd;
}
/**
* Column Info Setter
*
* @param apstsCd
*/
public void setApstsCd(String apstsCd) {
this.apstsCd = apstsCd;
}
/**
* Column Info Getter
*
* @return apverId
*/
public String getApverId() {
return apverId;
}
/**
* Column Info Setter
*
* @param apverId
*/
public void setApverId(String apverId) {
this.apverId = apverId;
}
/**
* Column Info Getter
*
* @return abbrNm
*/
public String getAbbrNm() {
return abbrNm;
}
/**
* Column Info Setter
*
* @param abbrNm
*/
public void setAbbrNm(String abbrNm) {
this.abbrNm = abbrNm;
}
/**
* Column Info Getter
*
* @return mgrCmt
*/
public String getMgrCmt() {
return mgrCmt;
}
/**
* Column Info Setter
*
* @param mgrCmt
*/
public void setMgrCmt(String mgrCmt) {
this.mgrCmt = mgrCmt;
}
/**
* Column Info Getter
*
* @return dicTpCd
*/
public String getDicTpCd() {
return dicTpCd;
}
/**
* Column Info Setter
*
* @param dicTpCd
*/
public void setDicTpCd(String dicTpCd) {
this.dicTpCd = dicTpCd;
}
public String getPjtId() {
return pjtId;
}
public void setPjtId(String pjtId) {
this.pjtId = pjtId;
}
/**
* Column Info
*
* @return mstDmnFlg
*/
public String getMstDmnFlg() {
return mstDmnFlg;
}
/**
* Column Info
*
* @param mstDmnFlg
*/
public void setMstDmnFlg(String mstDmnFlg) {
this.mstDmnFlg = mstDmnFlg;
}
public String getReqFlg() {
return reqFlg;
}
public void setReqFlg(String reqFlg) {
this.reqFlg = reqFlg;
}
}
| UTF-8 | Java | 7,346 | java | DmmDmnDicVO.java | Java | [
{
"context": "============================ \n* 2011. 10. 24 Thinh.Pham 1.0 First Created.\n* =============",
"end": 417,
"score": 0.9998735189437866,
"start": 407,
"tag": "NAME",
"value": "Thinh.Pham"
},
{
"context": "odel;\n\n/**\n * Table Value Object<br>\n *\n... | null | [] | /*
*****************************************************************
*
* COPYRIGHT (C) 2011 DOU HOLDINGS NETWORKS CO., LTD. ALL RIGHTS RESERVED
*
* Create Date : 2011. 10. 24
* Change History
* ===============================================================
* DATE DEVELOPER REVISION DESCRIPTION
* ===============================================================
* 2011. 10. 24 Thinh.Pham 1.0 First Created.
* ===============================================================
*
*
*****************************************************************/
package com.dounets.blp.pi.process.dm.model;
import com.dounets.framework.ibsheet.model.IBStatus;
import com.dounets.framework.model.Model;
/**
* Table Value Object<br>
*
* @author Thinh.Pham
* @see Model
* @since J2EE 1.6
*/
public class DmmDmnDicVO extends Model implements DmmDmnDicVOKey {
private static final long serialVersionUID = -8233648461858549368L;
public DmmDmnDicVO() {
}
public DmmDmnDicVO(
String stndDmnId,
int mode
) {
this.stndDmnId = stndDmnId;
this.setIbflag(mode == 1 ? IBStatus.INSERT : mode == 2 ? IBStatus.UPDATE : mode == 3 ? IBStatus.DELETE : IBStatus.RETRIEVE);
}
/* Column Info */
String stndDmnId;
/* Column Info */
String dmnNm;
/* Column Info */
String datTpCd;
/* Column Info */
Integer datLen;
/* Column Info */
Integer datPnt;
/* Column Info */
String dmnDesc;
/* Column Info */
String rqstRsn;
/* Column Info */
String aproRjctRsn;
/* Column Info */
java.sql.Date rqstDt;
/* Column Info */
java.sql.Date aproDt;
/* Column Info */
String rqstrId;
/* Column Info */
String apstsCd;
/* Column Info */
String apverId;
/* Column Info */
String abbrNm;
/* Column Info */
String mgrCmt;
/* Column Info */
String dicTpCd;
/* Column Info */
String pjtId;
/* Column Info */
String mstDmnFlg;
/* Column Info */
String reqFlg;
/**
* Column Info Getter
*
* @return stndDmnId
*/
@Override
public String getStndDmnId() {
return stndDmnId;
}
/**
* Column Info Setter
*
* @param stndDmnId
*/
@Override
public void setStndDmnId(String stndDmnId) {
this.stndDmnId = stndDmnId;
}
/**
* Column Info Getter
*
* @return dmnNm
*/
public String getDmnNm() {
return dmnNm;
}
/**
* Column Info Setter
*
* @param dmnNm
*/
public void setDmnNm(String dmnNm) {
this.dmnNm = dmnNm;
}
/**
* Column Info Getter
*
* @return datTpCd
*/
public String getDatTpCd() {
return datTpCd;
}
/**
* Column Info Setter
*
* @param datTpCd
*/
public void setDatTpCd(String datTpCd) {
this.datTpCd = datTpCd;
}
/**
* Column Info Getter
*
* @return datLen
*/
public Integer getDatLen() {
return datLen;
}
/**
* Column Info Setter
*
* @param datLen
*/
public void setDatLen(Integer datLen) {
this.datLen = datLen;
}
/**
* Column Info Getter
*
* @return datPnt
*/
public Integer getDatPnt() {
return datPnt;
}
/**
* Column Info Setter
*
* @param datPnt
*/
public void setDatPnt(Integer datPnt) {
this.datPnt = datPnt;
}
/**
* Column Info Getter
*
* @return dmnDesc
*/
public String getDmnDesc() {
return dmnDesc;
}
/**
* Column Info Setter
*
* @param dmnDesc
*/
public void setDmnDesc(String dmnDesc) {
this.dmnDesc = dmnDesc;
}
/**
* Column Info Getter
*
* @return rqstRsn
*/
public String getRqstRsn() {
return rqstRsn;
}
/**
* Column Info Setter
*
* @param rqstRsn
*/
public void setRqstRsn(String rqstRsn) {
this.rqstRsn = rqstRsn;
}
/**
* Column Info Getter
*
* @return aproRjctRsn
*/
public String getAproRjctRsn() {
return aproRjctRsn;
}
/**
* Column Info Setter
*
* @param aproRjctRsn
*/
public void setAproRjctRsn(String aproRjctRsn) {
this.aproRjctRsn = aproRjctRsn;
}
/**
* Column Info Getter
*
* @return rqstDt
*/
public java.sql.Date getRqstDt() {
return rqstDt;
}
/**
* Column Info Setter
*
* @param rqstDt
*/
public void setRqstDt(java.sql.Date rqstDt) {
this.rqstDt = rqstDt;
}
/**
* Column Info Getter
*
* @return aproDt
*/
public java.sql.Date getAproDt() {
return aproDt;
}
/**
* Column Info Setter
*
* @param aproDt
*/
public void setAproDt(java.sql.Date aproDt) {
this.aproDt = aproDt;
}
/**
* Column Info Getter
*
* @return rqstrId
*/
public String getRqstrId() {
return rqstrId;
}
/**
* Column Info Setter
*
* @param rqstrId
*/
public void setRqstrId(String rqstrId) {
this.rqstrId = rqstrId;
}
/**
* Column Info Getter
*
* @return apstsCd
*/
public String getApstsCd() {
return apstsCd;
}
/**
* Column Info Setter
*
* @param apstsCd
*/
public void setApstsCd(String apstsCd) {
this.apstsCd = apstsCd;
}
/**
* Column Info Getter
*
* @return apverId
*/
public String getApverId() {
return apverId;
}
/**
* Column Info Setter
*
* @param apverId
*/
public void setApverId(String apverId) {
this.apverId = apverId;
}
/**
* Column Info Getter
*
* @return abbrNm
*/
public String getAbbrNm() {
return abbrNm;
}
/**
* Column Info Setter
*
* @param abbrNm
*/
public void setAbbrNm(String abbrNm) {
this.abbrNm = abbrNm;
}
/**
* Column Info Getter
*
* @return mgrCmt
*/
public String getMgrCmt() {
return mgrCmt;
}
/**
* Column Info Setter
*
* @param mgrCmt
*/
public void setMgrCmt(String mgrCmt) {
this.mgrCmt = mgrCmt;
}
/**
* Column Info Getter
*
* @return dicTpCd
*/
public String getDicTpCd() {
return dicTpCd;
}
/**
* Column Info Setter
*
* @param dicTpCd
*/
public void setDicTpCd(String dicTpCd) {
this.dicTpCd = dicTpCd;
}
public String getPjtId() {
return pjtId;
}
public void setPjtId(String pjtId) {
this.pjtId = pjtId;
}
/**
* Column Info
*
* @return mstDmnFlg
*/
public String getMstDmnFlg() {
return mstDmnFlg;
}
/**
* Column Info
*
* @param mstDmnFlg
*/
public void setMstDmnFlg(String mstDmnFlg) {
this.mstDmnFlg = mstDmnFlg;
}
public String getReqFlg() {
return reqFlg;
}
public void setReqFlg(String reqFlg) {
this.reqFlg = reqFlg;
}
}
| 7,346 | 0.497686 | 0.491288 | 408 | 17.004902 | 15.669847 | 132 | false | false | 0 | 0 | 0 | 0 | 64 | 0.017424 | 0.159314 | false | false | 2 |
5370ea15b3ccce5bb0782a229b658ea7b5e44dbd | 31,069,793,465,525 | d3591b905206223947e1f662e55f1b36b24c6004 | /Assignment-5/Q5/Dog.java | 4b9742be62a93045a3598fcb31e9b4e43c33bfe6 | [] | no_license | GroovyEverywhere/5100-Assignment | https://github.com/GroovyEverywhere/5100-Assignment | fb0220e9ec35e78fa0505673608ff7405e8e6ac6 | c151c7aeb5669b26c47bf2fb24292cde36f7022d | refs/heads/master | 2020-07-25T16:14:21.981000 | 2019-12-13T08:00:32 | 2019-12-13T08:00:32 | 208,351,394 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Dog;
import Boardable.Boardable;
import Pet.Pet;
public class Dog extends Pet implements Boardable{
private String size;
int startDay;
int startMonth;
int startYear;
int endDay;
int endMonth;
int endYear;
public Dog(String petName, String ownerName, String color,String size) {
super(petName, ownerName, color);
this.size = size;
// TODO Auto-generated constructor stub
}
String getSize() {
return size;
}
public String toString() {
return "DOG:" + '\n' + super.toString() + '\n' + "Size: " + this.getSize();
}
void setBoardStart(int month, int day, int year) {
this.startDay = day;
this.startMonth = month;
this.startYear = year;
}
void setBoardEnd(int month, int day, int year) {
this.endDay = day;
this.endMonth = month;
this.endYear = year;
}
boolean boarding(int month, int day, int year) {
if(startYear == endYear && year == startYear) {
if(startMonth == endMonth && month == startMonth) {
if(day >= startDay && day <= endDay) {
return true;
}
}
else if(startMonth < endMonth && month == startMonth) {
if(day >= startDay) {
return true;
}
}
else if(startMonth < endMonth && month == endMonth) {
if(day <= endDay) {
return true;
}
}
else if(startMonth < month && month< endMonth ) {
return true;
}
}
else if(startYear < endYear && year > startYear && year < endYear) {
return true;
}
else if(startYear < endYear && year == startYear) {
if(month == startMonth) {
if(day >= startDay) {
return true;
}
}
else if(month > startMonth) {
return true;
}
}
else if(startYear < endYear && year == endYear) {
if(month == endMonth) {
if(day <= endDay) {
return true;
}
}
else if(month < endMonth) {
return true;
}
}
return false;
}
public static void main(String args[]) {
Dog d = new Dog("Ted","Bruno","Black", "Medium");
d.sex = FEMALE;
d.setBoardStart(10, 1, 2020);
d.setBoardEnd(10, 8, 2020);
System.out.println(d);
System.out.println(d.boarding(10, 7, 2020));
}
}
| UTF-8 | Java | 2,224 | java | Dog.java | Java | [
{
"context": "tic void main(String args[]) {\n\t\tDog d = new Dog(\"Ted\",\"Bruno\",\"Black\", \"Medium\");\n\t\td.sex = FEMALE;\n\t\t",
"end": 2037,
"score": 0.9997042417526245,
"start": 2034,
"tag": "NAME",
"value": "Ted"
},
{
"context": "id main(String args[]) {\n\t\tDog d = new D... | null | [] | package Dog;
import Boardable.Boardable;
import Pet.Pet;
public class Dog extends Pet implements Boardable{
private String size;
int startDay;
int startMonth;
int startYear;
int endDay;
int endMonth;
int endYear;
public Dog(String petName, String ownerName, String color,String size) {
super(petName, ownerName, color);
this.size = size;
// TODO Auto-generated constructor stub
}
String getSize() {
return size;
}
public String toString() {
return "DOG:" + '\n' + super.toString() + '\n' + "Size: " + this.getSize();
}
void setBoardStart(int month, int day, int year) {
this.startDay = day;
this.startMonth = month;
this.startYear = year;
}
void setBoardEnd(int month, int day, int year) {
this.endDay = day;
this.endMonth = month;
this.endYear = year;
}
boolean boarding(int month, int day, int year) {
if(startYear == endYear && year == startYear) {
if(startMonth == endMonth && month == startMonth) {
if(day >= startDay && day <= endDay) {
return true;
}
}
else if(startMonth < endMonth && month == startMonth) {
if(day >= startDay) {
return true;
}
}
else if(startMonth < endMonth && month == endMonth) {
if(day <= endDay) {
return true;
}
}
else if(startMonth < month && month< endMonth ) {
return true;
}
}
else if(startYear < endYear && year > startYear && year < endYear) {
return true;
}
else if(startYear < endYear && year == startYear) {
if(month == startMonth) {
if(day >= startDay) {
return true;
}
}
else if(month > startMonth) {
return true;
}
}
else if(startYear < endYear && year == endYear) {
if(month == endMonth) {
if(day <= endDay) {
return true;
}
}
else if(month < endMonth) {
return true;
}
}
return false;
}
public static void main(String args[]) {
Dog d = new Dog("Ted","Bruno","Black", "Medium");
d.sex = FEMALE;
d.setBoardStart(10, 1, 2020);
d.setBoardEnd(10, 8, 2020);
System.out.println(d);
System.out.println(d.boarding(10, 7, 2020));
}
}
| 2,224 | 0.57509 | 0.565647 | 101 | 21.019802 | 19.115067 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.168317 | false | false | 2 |
c19ec2aac09686b7cc814e6f64e2eaecc8e70635 | 35,192,962,063,321 | cb1378a10554bc53da038c3a3668197bb6c59e4f | /code/Table.java | 0ab6cf50f7cd2352d607a79f2736fb2ce59997ee | [] | no_license | Atichat43/Fahsai | https://github.com/Atichat43/Fahsai | 9245eb7cd40e38f5ba3236e5044e2287f2227a5d | 2fd6b574ba61a0be60e8a419a84a5832a9e6bd90 | refs/heads/master | 2021-07-10T12:47:47.871000 | 2017-10-14T07:41:27 | 2017-10-14T07:41:27 | 106,905,049 | 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 finalproject;
import java.util.*;
/**
*
* @author Dhitiwat
*/
public class Table implements java.io.Serializable {
public int id;
public int numberOfPeople;
public boolean avaliable;
public boolean checkingBill;
//public ArrayList<Food> foodOrdered;
//public ArrayList<Food> drinksOrdered;
public Map<Food, Integer> foodOrdered;
public Map<Food, Integer> drinksOrdered;
public String enteredTime;
public String order;
public Table(int id) {
this.id = id;
//this.foodOrdered = new ArrayList();
//this.drinksOrdered = new ArrayList();
this.foodOrdered = new HashMap<Food, Integer>();
this.drinksOrdered = new HashMap<Food, Integer>();
this.reset();
}
public Table(Table otherTable, int order) {
this.id = otherTable.id;
this.foodOrdered = otherTable.foodOrdered;
this.drinksOrdered = otherTable.drinksOrdered;
this.numberOfPeople = otherTable.numberOfPeople;
this.enteredTime = otherTable.enteredTime;
this.avaliable = false;
this.order = ""+order;
for (int i = this.order.length();i<4;++i){
this.order = "0"+this.order;
}
}
public void setUp(int numberOfPeople, String enteredTime) {
this.numberOfPeople = numberOfPeople;
this.enteredTime = enteredTime;
this.avaliable = false;
}
public void reset() {
this.numberOfPeople = 0;
this.avaliable = true;
this.checkingBill = false;
this.foodOrdered.clear();
this.drinksOrdered.clear();
}
public int getNumberOfPeople() {
return this.numberOfPeople;
}
private double getPrices() {
double totalPrice = 0;
for (Food i : foodOrdered.keySet()) {
totalPrice += i.getPrice() * foodOrdered.get(i);
}
for (Food i : drinksOrdered.keySet()) {
totalPrice += i.getPrice() * drinksOrdered.get(i);
}
return totalPrice;
}
public double getVAT() {
return getPrices() * 0.07;
}
public double getServiceCharge() {
return getPrices() * 0.15;
}
public double getTotalPrice() {
return getPrices() + getVAT() + getServiceCharge();
}
@Override
public String toString() {
return "Table: " + id + "\nNumber of People: " + numberOfPeople + "\nEntered Time: " + enteredTime + "\n";
}
public String getEnteredTime() {
return this.enteredTime;
}
public void addOrderd(Map<Food, Integer> selectedFood, Map<Food, Integer> selectedDrinks) {
for (Food i : selectedFood.keySet()) {
System.out.println(i + "\t" + selectedFood.get(i));
}
for (Food i : selectedFood.keySet()) {
for (Food j : this.foodOrdered.keySet()) {
if (i.getName(0).equals(j.getName(0))) {
System.out.println("adding Order");
System.out.println("\t\t" + this.foodOrdered.get(j) + "\t" + selectedFood.get(i));
selectedFood.replace(i, this.foodOrdered.get(j) + selectedFood.get(i));
this.foodOrdered.remove(j);
System.out.println("\t\t" + selectedFood.get(i));
break;
}
}
}
this.foodOrdered.putAll(selectedFood);
for (Food i : selectedDrinks.keySet()) {
for (Food j : this.drinksOrdered.keySet()) {
if (i.getName(0).equals(j.getName(0))) {
selectedDrinks.replace(i, this.drinksOrdered.get(j) + selectedDrinks.get(i));
this.drinksOrdered.remove(j);
break;
}
}
}
this.drinksOrdered.putAll(selectedDrinks);
/*
for (Food i : selectedFood.keySet()) {
if (this.foodOrdered.containsKey(i)) {
this.foodOrdered.replace(i, this.foodOrdered.get(i) + selectedFood.get(i));
selectedFood.remove(i);
}
}
this.drinksOrdered.putAll(selectedDrinks);
for (Food i : selectedDrinks.keySet()) {
if (this.drinksOrdered.containsKey(i)) {
this.drinksOrdered.replace(i, this.drinksOrdered.get(i) + selectedDrinks.get(i));
selectedDrinks.remove(i);
}
}
this.drinksOrdered.putAll(selectedDrinks);
*/
}
public String getOrder(){
return this.order;
}
}
| UTF-8 | Java | 4,751 | java | Table.java | Java | [
{
"context": "alproject;\n\nimport java.util.*;\n\n/**\n *\n * @author Dhitiwat\n */\npublic class Table implements java.io.Seriali",
"end": 255,
"score": 0.9997522830963135,
"start": 247,
"tag": "NAME",
"value": "Dhitiwat"
}
] | 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 finalproject;
import java.util.*;
/**
*
* @author Dhitiwat
*/
public class Table implements java.io.Serializable {
public int id;
public int numberOfPeople;
public boolean avaliable;
public boolean checkingBill;
//public ArrayList<Food> foodOrdered;
//public ArrayList<Food> drinksOrdered;
public Map<Food, Integer> foodOrdered;
public Map<Food, Integer> drinksOrdered;
public String enteredTime;
public String order;
public Table(int id) {
this.id = id;
//this.foodOrdered = new ArrayList();
//this.drinksOrdered = new ArrayList();
this.foodOrdered = new HashMap<Food, Integer>();
this.drinksOrdered = new HashMap<Food, Integer>();
this.reset();
}
public Table(Table otherTable, int order) {
this.id = otherTable.id;
this.foodOrdered = otherTable.foodOrdered;
this.drinksOrdered = otherTable.drinksOrdered;
this.numberOfPeople = otherTable.numberOfPeople;
this.enteredTime = otherTable.enteredTime;
this.avaliable = false;
this.order = ""+order;
for (int i = this.order.length();i<4;++i){
this.order = "0"+this.order;
}
}
public void setUp(int numberOfPeople, String enteredTime) {
this.numberOfPeople = numberOfPeople;
this.enteredTime = enteredTime;
this.avaliable = false;
}
public void reset() {
this.numberOfPeople = 0;
this.avaliable = true;
this.checkingBill = false;
this.foodOrdered.clear();
this.drinksOrdered.clear();
}
public int getNumberOfPeople() {
return this.numberOfPeople;
}
private double getPrices() {
double totalPrice = 0;
for (Food i : foodOrdered.keySet()) {
totalPrice += i.getPrice() * foodOrdered.get(i);
}
for (Food i : drinksOrdered.keySet()) {
totalPrice += i.getPrice() * drinksOrdered.get(i);
}
return totalPrice;
}
public double getVAT() {
return getPrices() * 0.07;
}
public double getServiceCharge() {
return getPrices() * 0.15;
}
public double getTotalPrice() {
return getPrices() + getVAT() + getServiceCharge();
}
@Override
public String toString() {
return "Table: " + id + "\nNumber of People: " + numberOfPeople + "\nEntered Time: " + enteredTime + "\n";
}
public String getEnteredTime() {
return this.enteredTime;
}
public void addOrderd(Map<Food, Integer> selectedFood, Map<Food, Integer> selectedDrinks) {
for (Food i : selectedFood.keySet()) {
System.out.println(i + "\t" + selectedFood.get(i));
}
for (Food i : selectedFood.keySet()) {
for (Food j : this.foodOrdered.keySet()) {
if (i.getName(0).equals(j.getName(0))) {
System.out.println("adding Order");
System.out.println("\t\t" + this.foodOrdered.get(j) + "\t" + selectedFood.get(i));
selectedFood.replace(i, this.foodOrdered.get(j) + selectedFood.get(i));
this.foodOrdered.remove(j);
System.out.println("\t\t" + selectedFood.get(i));
break;
}
}
}
this.foodOrdered.putAll(selectedFood);
for (Food i : selectedDrinks.keySet()) {
for (Food j : this.drinksOrdered.keySet()) {
if (i.getName(0).equals(j.getName(0))) {
selectedDrinks.replace(i, this.drinksOrdered.get(j) + selectedDrinks.get(i));
this.drinksOrdered.remove(j);
break;
}
}
}
this.drinksOrdered.putAll(selectedDrinks);
/*
for (Food i : selectedFood.keySet()) {
if (this.foodOrdered.containsKey(i)) {
this.foodOrdered.replace(i, this.foodOrdered.get(i) + selectedFood.get(i));
selectedFood.remove(i);
}
}
this.drinksOrdered.putAll(selectedDrinks);
for (Food i : selectedDrinks.keySet()) {
if (this.drinksOrdered.containsKey(i)) {
this.drinksOrdered.replace(i, this.drinksOrdered.get(i) + selectedDrinks.get(i));
selectedDrinks.remove(i);
}
}
this.drinksOrdered.putAll(selectedDrinks);
*/
}
public String getOrder(){
return this.order;
}
}
| 4,751 | 0.570827 | 0.56788 | 156 | 29.455128 | 25.177406 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.519231 | false | false | 2 |
34feb594eb40a0338e3f53441c40609358cdbd2c | 36,507,222,045,145 | 167415029ad4edb8585027e14b30628b85cf0f2c | /src/main/java/com/noctest/auth/AuthTokenRepo.java | 85d25d259cda96d73294d44d35eb87f2b1a80d2e | [
"Apache-2.0",
"CC-BY-4.0"
] | permissive | noelo/ferrytracker | https://github.com/noelo/ferrytracker | 862054ebb6a872c613fe250b81316e97811319d0 | 8dde7d435902380b871fc0f2d100dcf05c7728cc | refs/heads/master | 2021-01-01T04:00:28.824000 | 2016-05-16T02:53:04 | 2016-05-16T02:53:04 | 58,798,285 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.noctest.auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.util.Optional;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Created by admin on 2/05/2016.
*/
@Component
@Service
public class AuthTokenRepo implements TokenRepoIF {
private static final Logger log = LoggerFactory.getLogger(AuthTokenRepo.class);
private Optional<String> authToken = Optional.empty();
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private final Lock readLock = readWriteLock.readLock();
private final Lock writeLock = readWriteLock.writeLock();
public void setToken(String token) {
writeLock.lock();
try {
if (!token.isEmpty())
authToken = Optional.of(token);
} finally {
writeLock.unlock();
}
}
public Optional<String> getToken() {
Optional<String> result = Optional.empty();
readLock.lock();
try {
result = authToken;
} finally {
readLock.unlock();
}
return result;
}
}
| UTF-8 | Java | 1,302 | java | AuthTokenRepo.java | Java | [
{
"context": "t.locks.ReentrantReadWriteLock;\n\n/**\n * Created by admin on 2/05/2016.\n */\n@Component\n@Service\npublic clas",
"end": 379,
"score": 0.993144154548645,
"start": 374,
"tag": "USERNAME",
"value": "admin"
}
] | null | [] | package com.noctest.auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.util.Optional;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Created by admin on 2/05/2016.
*/
@Component
@Service
public class AuthTokenRepo implements TokenRepoIF {
private static final Logger log = LoggerFactory.getLogger(AuthTokenRepo.class);
private Optional<String> authToken = Optional.empty();
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private final Lock readLock = readWriteLock.readLock();
private final Lock writeLock = readWriteLock.writeLock();
public void setToken(String token) {
writeLock.lock();
try {
if (!token.isEmpty())
authToken = Optional.of(token);
} finally {
writeLock.unlock();
}
}
public Optional<String> getToken() {
Optional<String> result = Optional.empty();
readLock.lock();
try {
result = authToken;
} finally {
readLock.unlock();
}
return result;
}
}
| 1,302 | 0.674347 | 0.667435 | 45 | 27.933332 | 21.784195 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.488889 | false | false | 2 |
457444f99b69552ac9503c70649cb7345c9f8a94 | 26,027,501,883,343 | 166b25497763faac9f822ce30247c24e79e3ccc6 | /src/main/java/com/example/attendance_sheet/Config/UserDetails/UserDetailsServiceImpl.java | 84a663ac617d51c67f494e085063818ae6cad236 | [] | no_license | JY8752/appendance_sheet | https://github.com/JY8752/appendance_sheet | b8a045acb296d17f424e5bb839e7d716ca3fb330 | 7e0b757dcea93b7ceb31fc32e9bfb275f764d1c9 | refs/heads/master | 2022-11-19T11:30:02.835000 | 2020-07-11T15:35:29 | 2020-07-11T15:35:29 | 275,531,650 | 0 | 0 | null | false | 2020-07-11T15:35:30 | 2020-06-28T07:30:41 | 2020-06-28T07:31:30 | 2020-07-11T15:35:30 | 103 | 0 | 0 | 0 | Java | false | false | package com.example.attendance_sheet.Config.UserDetails;
import com.example.attendance_sheet.Common.UserRole;
import com.example.attendance_sheet.Common.Exception.UserRoleNotFoundException;
import com.example.attendance_sheet.Entity.UserEntity;
import com.example.attendance_sheet.Repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserEntity userEntity = userRepository.findByEmail(username)
.orElseThrow(() -> new UsernameNotFoundException("ユーザーが見つかりません"));
UserRole role = UserRole.getUserRoleById(userEntity.getRole())
.orElseThrow(() -> new UserRoleNotFoundException("ロールが見つかりません"));
return new UserDetails(userEntity.getId(), userEntity.getEmail(), userEntity.getPassword(), userEntity.getName(), role);
}
@Override
public UserDetails loadUserById(Integer id) throws UsernameNotFoundException {
UserEntity userEntity = userRepository.findById(id)
.orElseThrow(() -> new UsernameNotFoundException("ユーザーが見つかりません"));
UserRole role = UserRole.getUserRoleById(userEntity.getRole())
.orElseThrow(() -> new UserRoleNotFoundException("ロールが見つかりません"));
return new UserDetails(userEntity.getId(), userEntity.getEmail(), userEntity.getPassword(), userEntity.getName(), role);
}
@Override
public void login(int id) {
UserDetails userDetails = this.loadUserById(id);
if(userDetails == null) {
return;
}
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userDetails, null);
token.setDetails(userDetails);
SecurityContextHolder.getContext().setAuthentication(token);
}
@Override
public void logout() {
SecurityContextHolder.getContext().setAuthentication(null);
}
} | UTF-8 | Java | 2,428 | java | UserDetailsServiceImpl.java | Java | [] | null | [] | package com.example.attendance_sheet.Config.UserDetails;
import com.example.attendance_sheet.Common.UserRole;
import com.example.attendance_sheet.Common.Exception.UserRoleNotFoundException;
import com.example.attendance_sheet.Entity.UserEntity;
import com.example.attendance_sheet.Repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserEntity userEntity = userRepository.findByEmail(username)
.orElseThrow(() -> new UsernameNotFoundException("ユーザーが見つかりません"));
UserRole role = UserRole.getUserRoleById(userEntity.getRole())
.orElseThrow(() -> new UserRoleNotFoundException("ロールが見つかりません"));
return new UserDetails(userEntity.getId(), userEntity.getEmail(), userEntity.getPassword(), userEntity.getName(), role);
}
@Override
public UserDetails loadUserById(Integer id) throws UsernameNotFoundException {
UserEntity userEntity = userRepository.findById(id)
.orElseThrow(() -> new UsernameNotFoundException("ユーザーが見つかりません"));
UserRole role = UserRole.getUserRoleById(userEntity.getRole())
.orElseThrow(() -> new UserRoleNotFoundException("ロールが見つかりません"));
return new UserDetails(userEntity.getId(), userEntity.getEmail(), userEntity.getPassword(), userEntity.getName(), role);
}
@Override
public void login(int id) {
UserDetails userDetails = this.loadUserById(id);
if(userDetails == null) {
return;
}
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userDetails, null);
token.setDetails(userDetails);
SecurityContextHolder.getContext().setAuthentication(token);
}
@Override
public void logout() {
SecurityContextHolder.getContext().setAuthentication(null);
}
} | 2,428 | 0.745291 | 0.745291 | 57 | 40 | 36.740913 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.54386 | false | false | 2 |
0dd1ba56fa9b23db7d01ab48eece02f44b2159b6 | 36,979,668,448,464 | 146ccd1d7adc66cecbdc80fbdbea429c0a7aa7af | /LinkedList/src/com/company/LinkedList.java | a29b92fb6539751565284661b803d7fdfdb61f68 | [] | no_license | Gankova/LinkedList | https://github.com/Gankova/LinkedList | eccd1fa2709d588d7c9793f3136149d16ab31871 | ef25979b43bc7d40b200afe7df5c16ef57ba7290 | refs/heads/main | 2023-04-28T13:54:42.727000 | 2021-05-17T19:11:46 | 2021-05-17T19:11:46 | 368,295,628 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.company;
public class LinkedList {
private Node head;// ссылка на первый элемент списка(объект типа Node)
// метод add добавляет элемент в конец списка
public void add (int v){
if (head == null){
// создаем первый элемент списка
Node n = new Node();
n.value = v;
head = n;
return;// досрочный выход из метода void
}
Node last =head;
// доходим до последнего элемента в списке( у которого next !=null {}
while (last.next != null) {
last =last.next;
}
// создаем последний элемент в списке
Node n = new Node();
n.value = v;
last.next = n;
}
public void print(){
Node elem = head;
while (elem != null) {
System.out.println(elem.value);// выводим занчение текущего узла
elem = elem.next;
}
}
//метод удаляет элемент списка
public void remove (int index) throws NumberException{
Node r = head;
Node prev =null;
if (index == 0 && r != null) {
head = r.next;
return;
}
int i = 0;
while (r != null){
if (i == index) {
prev.next = r.next;
break;
} else {
prev = r;
r = r.next;
i++;
if (index > i) {
throw new NumberException();
}
}
}
}
// НАДО НАПИСАТЬ ЭКСЕПШН, при вводе индекса больше длинны списка
public int get(int index) throws NumberException{
Node el = head;
int k = 0;
while (el != null) {
if (k == index) {
return el.value;
}
el = el.next;
k++;
if (index > k){
throw new NumberException();
}
}return el.value;
}
}
| UTF-8 | Java | 2,359 | java | LinkedList.java | Java | [] | null | [] | package com.company;
public class LinkedList {
private Node head;// ссылка на первый элемент списка(объект типа Node)
// метод add добавляет элемент в конец списка
public void add (int v){
if (head == null){
// создаем первый элемент списка
Node n = new Node();
n.value = v;
head = n;
return;// досрочный выход из метода void
}
Node last =head;
// доходим до последнего элемента в списке( у которого next !=null {}
while (last.next != null) {
last =last.next;
}
// создаем последний элемент в списке
Node n = new Node();
n.value = v;
last.next = n;
}
public void print(){
Node elem = head;
while (elem != null) {
System.out.println(elem.value);// выводим занчение текущего узла
elem = elem.next;
}
}
//метод удаляет элемент списка
public void remove (int index) throws NumberException{
Node r = head;
Node prev =null;
if (index == 0 && r != null) {
head = r.next;
return;
}
int i = 0;
while (r != null){
if (i == index) {
prev.next = r.next;
break;
} else {
prev = r;
r = r.next;
i++;
if (index > i) {
throw new NumberException();
}
}
}
}
// НАДО НАПИСАТЬ ЭКСЕПШН, при вводе индекса больше длинны списка
public int get(int index) throws NumberException{
Node el = head;
int k = 0;
while (el != null) {
if (k == index) {
return el.value;
}
el = el.next;
k++;
if (index > k){
throw new NumberException();
}
}return el.value;
}
}
| 2,359 | 0.432655 | 0.431202 | 82 | 23.170732 | 18.375359 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.402439 | false | false | 2 |
275e9de00d95e5c39e7dab0df02790657db1fb21 | 36,996,848,309,998 | ec5ec39c637c0bfd68aacb74e3f82445af7ede5c | /Bookkeeping/src/main/java/com/lee/domain/Bills.java | 5294bcdad49b5d80716ce6777d090d0a85045553 | [] | no_license | nwpu2010/2020 | https://github.com/nwpu2010/2020 | b3fab7dbaf49ac1496fe8e840a8d7223f1d4f5f7 | ef154ab28348315be5fa2c69375cc78ab032f1b6 | refs/heads/master | 2022-12-25T02:23:35.968000 | 2020-02-24T11:25:00 | 2020-02-24T11:25:00 | 242,704,548 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lee.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
public class Bills {
private Integer id;
private String titile;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date billtime;
private Integer typeid;
private Double price;
private String remark;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitile() {
return titile;
}
public void setTitile(String titile) {
this.titile = titile;
}
public Date getBilltime() {
return billtime;
}
public void setBilltime(Date billtime) {
this.billtime = billtime;
}
public Integer getTypeid() {
return typeid;
}
public void setTypeid(Integer typeid) {
this.typeid = typeid;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
} | UTF-8 | Java | 1,299 | java | Bills.java | Java | [] | null | [] | package com.lee.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
public class Bills {
private Integer id;
private String titile;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date billtime;
private Integer typeid;
private Double price;
private String remark;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitile() {
return titile;
}
public void setTitile(String titile) {
this.titile = titile;
}
public Date getBilltime() {
return billtime;
}
public void setBilltime(Date billtime) {
this.billtime = billtime;
}
public Integer getTypeid() {
return typeid;
}
public void setTypeid(Integer typeid) {
this.typeid = typeid;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
} | 1,299 | 0.618168 | 0.617398 | 70 | 17.571428 | 16.950829 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.328571 | false | false | 2 |
52a76a223db0f142144d49490192f87146525b1b | 38,963,943,320,183 | 1e92fddfe4fc2f104e215200cabc2b10ff376e8c | /guo-shop/src/main/java/com/jc/cloud/shop/mapper/GoodsCommentMapper.java | cd74a6c51ad68af915fa19681d698b229639d8a6 | [] | no_license | marko36/guo_cloud | https://github.com/marko36/guo_cloud | 41acc5cf54ca7b6d032c63936acb972037b2fb6d | f45d2c1be5ee416f6b940846c3091ac12e14486e | refs/heads/master | 2022-04-13T04:54:16.406000 | 2020-04-10T11:27:32 | 2020-04-10T11:27:32 | 254,617,976 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jc.cloud.shop.mapper;
import com.jc.cloud.shop.entity.GoodsComment;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author lgh
* @since 2019-05-24
*/
public interface GoodsCommentMapper extends BaseMapper<GoodsComment> {
}
| UTF-8 | Java | 292 | java | GoodsCommentMapper.java | Java | [
{
"context": "r;\n\n/**\n * <p>\n * Mapper 接口\n * </p>\n *\n * @author lgh\n * @since 2019-05-24\n */\npublic interface GoodsCo",
"end": 188,
"score": 0.9996557831764221,
"start": 185,
"tag": "USERNAME",
"value": "lgh"
}
] | null | [] | package com.jc.cloud.shop.mapper;
import com.jc.cloud.shop.entity.GoodsComment;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author lgh
* @since 2019-05-24
*/
public interface GoodsCommentMapper extends BaseMapper<GoodsComment> {
}
| 292 | 0.71875 | 0.690972 | 16 | 17 | 21.342445 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.1875 | false | false | 2 |
9441cbc88c1bda8f40b44f94aff2783c5853aaf1 | 36,120,674,999,915 | a17403a3e14beccbb5088322b1d8d9483675dcd4 | /src/main/java/com/stock/future/v1/OrderStatus.java | 320b3f8b66dd552e5fe0c0b4fdf33a426cd0ee89 | [] | no_license | pairliu/IndexFuture | https://github.com/pairliu/IndexFuture | e2915d73dee2bf9a3c1cbc7939aa24aa413fbd47 | 666905d690f3a1936072a472c18efa1dffb8bdc9 | refs/heads/master | 2021-01-10T00:53:17.427000 | 2012-12-08T13:46:33 | 2012-12-08T13:46:33 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.stock.future.v1;
public enum OrderStatus {
NONE,
BULL_OPEN,
BEAR_OPEN,
BULL_OPENED_BUT_CLOSE,
BEAR_OPENED_BUT_CLOSE
}
| UTF-8 | Java | 151 | java | OrderStatus.java | Java | [] | null | [] | package com.stock.future.v1;
public enum OrderStatus {
NONE,
BULL_OPEN,
BEAR_OPEN,
BULL_OPENED_BUT_CLOSE,
BEAR_OPENED_BUT_CLOSE
}
| 151 | 0.662252 | 0.655629 | 9 | 15.777778 | 10.239117 | 28 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 2 |
28a4d819b606e655cc88e6126c08819b128f4872 | 23,210,003,268,187 | 609ff68bc83cfb205cb32b546d7694328984090e | /src/main/java/com/mancondome/local/cloud/controller/package-info.java | 65480163e42ee858d2320d532d32fee6c47ed683 | [] | no_license | mancondome/local-cloud | https://github.com/mancondome/local-cloud | d42135d27d0c67c2816a966726a3261d6caea2fb | b77fb8c3f08cf4343872b3ca6a2a550d15b5ef96 | refs/heads/master | 2020-05-18T17:44:49.378000 | 2013-08-25T18:22:05 | 2013-08-25T18:22:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* コントローラを配置する。
*/
package com.mancondome.local.cloud.controller; | UTF-8 | Java | 94 | java | package-info.java | Java | [] | null | [] | /**
* コントローラを配置する。
*/
package com.mancondome.local.cloud.controller; | 94 | 0.728571 | 0.728571 | 4 | 16.75 | 17.583729 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 2 |
171cb805fb1bdb6e42b571218844d4726bc8a34a | 30,030,411,357,441 | 47b85978de822d2701910e4672f2f1763b0045ec | /src/main/java/com/sinochem/fintech/service/TOrderItemService.java | 5cac372f444e441874fda3adc6d23368de97c2f5 | [] | no_license | heshouyou/sharding-boot-example | https://github.com/heshouyou/sharding-boot-example | 8576022d42beb7918180477ead93f4a5ef79eb4a | c3bc2562cbffdd5ec6ccd76305879058577d5a5b | refs/heads/master | 2020-04-09T22:58:31.846000 | 2018-12-06T08:35:39 | 2018-12-06T08:35:39 | 160,643,794 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sinochem.fintech.service;
import com.sinochem.fintech.common.BaseService;
import com.sinochem.fintech.entity.TOrderItem;
import com.sinochem.fintech.mapper.TOrderItemMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @Author: heshouyou
* @Description 订单子项服务
* @Date Created in 2018/12/6 10:23
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class TOrderItemService extends BaseService<TOrderItemMapper,TOrderItem> {
}
| UTF-8 | Java | 541 | java | TOrderItemService.java | Java | [
{
"context": "saction.annotation.Transactional;\n\n/**\n * @Author: heshouyou\n * @Description 订单子项服务\n * @Date Created in 2018/",
"end": 325,
"score": 0.9996751546859741,
"start": 316,
"tag": "USERNAME",
"value": "heshouyou"
}
] | null | [] | package com.sinochem.fintech.service;
import com.sinochem.fintech.common.BaseService;
import com.sinochem.fintech.entity.TOrderItem;
import com.sinochem.fintech.mapper.TOrderItemMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @Author: heshouyou
* @Description 订单子项服务
* @Date Created in 2018/12/6 10:23
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class TOrderItemService extends BaseService<TOrderItemMapper,TOrderItem> {
}
| 541 | 0.814745 | 0.793951 | 17 | 30.117647 | 24.318674 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.411765 | false | false | 2 |
834ccf8c26048b8034a938f5869f8eaa9b723ddb | 21,483,426,449,962 | 70a485ed1753225a699ecb424f93e3fa77262afb | /mdm-api/src/main/java/com/avatech/edi/mdm/contorller/BOMController.java | 50e78004dc38dcc7023c2e8621db7ca509adc32e | [
"Apache-2.0"
] | permissive | okzhangyu/mdm.application | https://github.com/okzhangyu/mdm.application | 4eb84efe6a7128c57dd52a3091bb176e40f016f2 | b5ab8168c2d2e5d927dce9c1be7bbdb986bc05ce | refs/heads/master | 2020-03-28T20:26:27.328000 | 2019-10-11T07:28:42 | 2019-10-11T07:28:42 | 149,070,741 | 0 | 2 | null | true | 2018-09-17T04:55:45 | 2018-09-17T04:55:45 | 2018-09-17T02:36:11 | 2018-09-17T02:36:09 | 2,035 | 0 | 0 | 0 | null | false | null | package com.avatech.edi.mdm.contorller;
import com.avatech.edi.mdm.bo.BillOfMaterial;
import com.avatech.edi.mdm.bo.CompontOfMaterialListItem;
import com.avatech.edi.mdm.bo.IBillOfMaterial;
import com.avatech.edi.mdm.bo.ICompontOfMaterialListItem;
import com.avatech.edi.mdm.config.ServiceException;
import com.avatech.edi.mdm.dto.Result;
import com.avatech.edi.mdm.dto.SyncResult;
import com.avatech.edi.mdm.service.BillOfMaterialService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.concurrent.Semaphore;
import java.util.stream.Collectors;
@RestController
@RequestMapping("bom/v1/*")
public class BOMController {
/**
* 定义资源总数
*/
Semaphore semaphore=new Semaphore(1);
private final Logger logger = LoggerFactory.getLogger(BOMController.class);
@Autowired
private BillOfMaterialService billOfMaterialService;
@GetMapping("bom")
public IBillOfMaterial getBillOfMaterial(){
IBillOfMaterial bom = new BillOfMaterial();
CompontOfMaterialListItem compontOfMaterialListItem = new CompontOfMaterialListItem();
compontOfMaterialListItem.setBOMVer("1");
compontOfMaterialListItem.setItemCode("10001");
bom.setCompanyDB("TEST1");
bom.setActived("Y");
bom.getCompontOfMaterialListItems().add(compontOfMaterialListItem);
return bom;
}
@RequestMapping(value = "bomversiontest",method ={RequestMethod.POST})
public @ResponseBody Result postTest(@RequestBody BillOfMaterial bom){
int availablePermits=semaphore.availablePermits();//可用资源数
if(availablePermits>0){
logger.info("抢到资源");
}else{
logger.info("资源已被占用,稍后再试");
return Result.error("1100","BOM审批资源正在被使用,请稍后再试");
}
try {
semaphore.acquire(1); //请求占用一个资源
logger.info("资源正在被使用");
Thread.sleep(30000);//放大资源占用时间,便于观察
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
semaphore.release(1);//释放一个资源
}
return Result.ok();
}
@RequestMapping(value = "bomversion",method ={RequestMethod.POST})
public @ResponseBody Result postBOMVersion( //@RequestParam(ServiceParam.TOKEN) String token,
@RequestBody BillOfMaterial bom){
Result rt;
int availablePermits=semaphore.availablePermits();//可用资源数
if(availablePermits<=0){
logger.info("BOM审批资源已被占用");
return Result.error("1100","BOM审批资源正在被使用,请稍后再试");
}
try
{
semaphore.acquire(1); //请求占用一个资源
logger.info("接收BOM信息》》》》》"+ bom.toString());
if(bom.getProject() == null || bom.getProject().isEmpty())
rt = Result.error("1001","项目信息为空");
else if(bom.getWorkOrderNo() == null || bom.getWorkOrderNo().isEmpty())
rt = Result.error("1002","工单号信息为空");
else if(bom.getCompontOfMaterialListItems().stream().filter(c->c.getIsLocked().equals("Y")).count() <= 0){
rt = Result.error("1003","冻结明细未空");
}else if (bom.getCompontOfMaterialListItems().stream().filter(c->c.getIsLocked().equals("Y") && c.getQuantity() == 0).collect(Collectors.toList()).size() > 0){
rt = Result.error("1004","冻结明细行数量不能为0");
}else{
SyncResult results = billOfMaterialService.syncBOM(bom);
rt = Result.ok(results);
}
}catch (ServiceException e){
logger.error(bom.toString(),e);
rt = Result.error("-1",e);
}
catch (Exception e){
logger.error(bom.toString(),e);
rt = Result.error("-1",e);
}finally {
semaphore.release(1);//释放一个资源
}
logger.info("BOM推送返回信息》》》》》"+ rt.toString());
return rt;
}
}
| UTF-8 | Java | 4,334 | java | BOMController.java | Java | [] | null | [] | package com.avatech.edi.mdm.contorller;
import com.avatech.edi.mdm.bo.BillOfMaterial;
import com.avatech.edi.mdm.bo.CompontOfMaterialListItem;
import com.avatech.edi.mdm.bo.IBillOfMaterial;
import com.avatech.edi.mdm.bo.ICompontOfMaterialListItem;
import com.avatech.edi.mdm.config.ServiceException;
import com.avatech.edi.mdm.dto.Result;
import com.avatech.edi.mdm.dto.SyncResult;
import com.avatech.edi.mdm.service.BillOfMaterialService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.concurrent.Semaphore;
import java.util.stream.Collectors;
@RestController
@RequestMapping("bom/v1/*")
public class BOMController {
/**
* 定义资源总数
*/
Semaphore semaphore=new Semaphore(1);
private final Logger logger = LoggerFactory.getLogger(BOMController.class);
@Autowired
private BillOfMaterialService billOfMaterialService;
@GetMapping("bom")
public IBillOfMaterial getBillOfMaterial(){
IBillOfMaterial bom = new BillOfMaterial();
CompontOfMaterialListItem compontOfMaterialListItem = new CompontOfMaterialListItem();
compontOfMaterialListItem.setBOMVer("1");
compontOfMaterialListItem.setItemCode("10001");
bom.setCompanyDB("TEST1");
bom.setActived("Y");
bom.getCompontOfMaterialListItems().add(compontOfMaterialListItem);
return bom;
}
@RequestMapping(value = "bomversiontest",method ={RequestMethod.POST})
public @ResponseBody Result postTest(@RequestBody BillOfMaterial bom){
int availablePermits=semaphore.availablePermits();//可用资源数
if(availablePermits>0){
logger.info("抢到资源");
}else{
logger.info("资源已被占用,稍后再试");
return Result.error("1100","BOM审批资源正在被使用,请稍后再试");
}
try {
semaphore.acquire(1); //请求占用一个资源
logger.info("资源正在被使用");
Thread.sleep(30000);//放大资源占用时间,便于观察
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
semaphore.release(1);//释放一个资源
}
return Result.ok();
}
@RequestMapping(value = "bomversion",method ={RequestMethod.POST})
public @ResponseBody Result postBOMVersion( //@RequestParam(ServiceParam.TOKEN) String token,
@RequestBody BillOfMaterial bom){
Result rt;
int availablePermits=semaphore.availablePermits();//可用资源数
if(availablePermits<=0){
logger.info("BOM审批资源已被占用");
return Result.error("1100","BOM审批资源正在被使用,请稍后再试");
}
try
{
semaphore.acquire(1); //请求占用一个资源
logger.info("接收BOM信息》》》》》"+ bom.toString());
if(bom.getProject() == null || bom.getProject().isEmpty())
rt = Result.error("1001","项目信息为空");
else if(bom.getWorkOrderNo() == null || bom.getWorkOrderNo().isEmpty())
rt = Result.error("1002","工单号信息为空");
else if(bom.getCompontOfMaterialListItems().stream().filter(c->c.getIsLocked().equals("Y")).count() <= 0){
rt = Result.error("1003","冻结明细未空");
}else if (bom.getCompontOfMaterialListItems().stream().filter(c->c.getIsLocked().equals("Y") && c.getQuantity() == 0).collect(Collectors.toList()).size() > 0){
rt = Result.error("1004","冻结明细行数量不能为0");
}else{
SyncResult results = billOfMaterialService.syncBOM(bom);
rt = Result.ok(results);
}
}catch (ServiceException e){
logger.error(bom.toString(),e);
rt = Result.error("-1",e);
}
catch (Exception e){
logger.error(bom.toString(),e);
rt = Result.error("-1",e);
}finally {
semaphore.release(1);//释放一个资源
}
logger.info("BOM推送返回信息》》》》》"+ rt.toString());
return rt;
}
}
| 4,334 | 0.631184 | 0.618191 | 105 | 37.114285 | 28.143278 | 171 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.685714 | false | false | 2 |
063540ad538a81350efdafa6f18dee663b72c564 | 12,000,138,633,695 | 2ecb06ed46f2a5d3d0921822018288652ca94134 | /src/main/java/com/linkyway/controller/service/TweetController.java | dd273690c69ee04b4253ad6e9d77dd7f02d58717 | [
"MIT"
] | permissive | SWE-574-Spring-2018/Spring2018-SWE574 | https://github.com/SWE-574-Spring-2018/Spring2018-SWE574 | ede536c068c0751a7c6cc3fac6a3aa17eec00a2a | 89a779917b650e85010243263c6838943db32c37 | refs/heads/master | 2021-05-01T14:53:13.370000 | 2018-06-03T20:46:37 | 2018-06-03T20:46:37 | 121,026,149 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.linkyway.controller.service;
import com.linkyway.service.NodeService;
import com.linkyway.service.TweetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.social.twitter.api.Tweet;
import org.springframework.social.twitter.api.Twitter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.validation.constraints.NotNull;
/**
* @author acersoz
*/
@Controller
@RequestMapping("/linkyway/api/tweet")
public class TweetController {
@Autowired
private NodeService nodeService;
@Autowired
private TweetService tweetService;
@Autowired
private Twitter twitter;
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public ResponseEntity searchTweet(@NotNull String url)
throws org.springframework.social.ApiException {
// boolean isTweetConnected = false;
//for (Node node : nodeService.getAllNodes()) {
// if (node.)
//}
Tweet searchResult = tweetService.searchTweets(url);
return ResponseEntity.status(HttpStatus.OK).body(searchResult);
}
}
| UTF-8 | Java | 1,400 | java | TweetController.java | Java | [
{
"context": "x.validation.constraints.NotNull;\n\n\n/**\n * @author acersoz\n */\n\n@Controller\n@RequestMapping(\"/linkyway/api/t",
"end": 694,
"score": 0.9993078112602234,
"start": 687,
"tag": "USERNAME",
"value": "acersoz"
}
] | null | [] | package com.linkyway.controller.service;
import com.linkyway.service.NodeService;
import com.linkyway.service.TweetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.social.twitter.api.Tweet;
import org.springframework.social.twitter.api.Twitter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.validation.constraints.NotNull;
/**
* @author acersoz
*/
@Controller
@RequestMapping("/linkyway/api/tweet")
public class TweetController {
@Autowired
private NodeService nodeService;
@Autowired
private TweetService tweetService;
@Autowired
private Twitter twitter;
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public ResponseEntity searchTweet(@NotNull String url)
throws org.springframework.social.ApiException {
// boolean isTweetConnected = false;
//for (Node node : nodeService.getAllNodes()) {
// if (node.)
//}
Tweet searchResult = tweetService.searchTweets(url);
return ResponseEntity.status(HttpStatus.OK).body(searchResult);
}
}
| 1,400 | 0.762143 | 0.762143 | 46 | 29.434782 | 23.157919 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.413043 | false | false | 2 |
9427b2dfc8679ff26082bd96ddf59d11958e92fa | 18,365,280,160,610 | 473cf2eb972b8df3a03442bb607b72e9bd014879 | /src/test/java/com/imooc/sell/SellApplicationTests.java | ba8e8833d0f1d6c8d12dfda8f8464a3bc42f98f3 | [] | no_license | 3pacccccc/sell2 | https://github.com/3pacccccc/sell2 | 314466fd6d4115aafb12a5962f7b8bd60d89aff0 | 79c3d1b0f48d5eb1be26d7a29ce768a3376b2ed7 | refs/heads/master | 2021-04-20T16:13:26.961000 | 2020-03-24T12:13:34 | 2020-03-24T12:13:34 | 249,698,343 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.imooc.sell;
| UTF-8 | Java | 26 | java | SellApplicationTests.java | Java | [] | null | [] | package com.imooc.sell;
| 26 | 0.730769 | 0.730769 | 1 | 23 | 0 | 23 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 2 |
5e6f08340bf68eab15473b3bf0568da2e319e0f6 | 24,197,845,747,368 | de783b9b8ccc79d4ef63e4d3e22b6784f1dfc4c6 | /src/main/java/ua/com/tervola/jdbc/model/Employee.java | eaeeb06c66d1a825e8d54e55f274cbec3e833942 | [] | no_license | tervola/goit-jdbc-project | https://github.com/tervola/goit-jdbc-project | 5a598c7f28bbc2ee5df710e801820e26b719fde5 | 551b4f8de2f16129d7a304d1785a4003e3e2f635 | refs/heads/master | 2020-12-24T12:12:47.970000 | 2017-06-19T11:06:52 | 2017-06-19T11:06:52 | 73,069,627 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ua.com.tervola.jdbc.model;
/**
* Created by user on 11/7/2016.
*/
public class Employee {
private int id;
private String name;
private String surName;
private String birthday;
private String phone;
private float salary;
private String position;
@Override
public String toString() {
return "EmployeeDao{" +
"id=" + id +
", name='" + name + '\'' +
", surName='" + surName + '\'' +
", birthday='" + birthday + '\'' +
", phone='" + phone + '\'' +
", salary=" + salary +
", position='" + position + '\'' +
'}';
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getSurName() {
return surName;
}
public String getBirthday() {
return birthday;
}
public String getPhone() {
return phone;
}
public float getSalary() {
return salary;
}
public String getPosition() {
return position;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setSurName(String surName) {
this.surName = surName;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public void setPhone(String phone) {
this.phone = phone;
}
public void setSalary(float salary) {
this.salary = salary;
}
public void setPosition(String position) {
this.position = position;
}
}
| UTF-8 | Java | 1,674 | java | Employee.java | Java | [] | null | [] | package ua.com.tervola.jdbc.model;
/**
* Created by user on 11/7/2016.
*/
public class Employee {
private int id;
private String name;
private String surName;
private String birthday;
private String phone;
private float salary;
private String position;
@Override
public String toString() {
return "EmployeeDao{" +
"id=" + id +
", name='" + name + '\'' +
", surName='" + surName + '\'' +
", birthday='" + birthday + '\'' +
", phone='" + phone + '\'' +
", salary=" + salary +
", position='" + position + '\'' +
'}';
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getSurName() {
return surName;
}
public String getBirthday() {
return birthday;
}
public String getPhone() {
return phone;
}
public float getSalary() {
return salary;
}
public String getPosition() {
return position;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setSurName(String surName) {
this.surName = surName;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public void setPhone(String phone) {
this.phone = phone;
}
public void setSalary(float salary) {
this.salary = salary;
}
public void setPosition(String position) {
this.position = position;
}
}
| 1,674 | 0.514337 | 0.510155 | 85 | 18.694118 | 15.688905 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.341176 | false | false | 2 |
df99f15a61e01b8f00936ebc3eb6a3850f95f442 | 6,519,760,379,648 | e5b8c9f9a5062360312d61daa242e34ac87f9f73 | /WAREHOUSEAPP/src/main/java/com/sathyatech/app/model/Uom.java | fdb8e1a37c0c62f60a95340daa354381eaaa25b2 | [] | no_license | balakrishnakothapally/Spring-Boot-Project | https://github.com/balakrishnakothapally/Spring-Boot-Project | a597d30303f20edb4b144f3af0664423123091dd | 1152d572da34bc34743e87fc289e2aa7fc4297ec | refs/heads/master | 2023-07-10T01:30:24.539000 | 2021-08-06T07:15:38 | 2021-08-06T07:15:38 | 393,278,608 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.sathyatech.app.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.springframework.format.annotation.DateTimeFormat;
/**
* This is model class for Uom[Unit of Measurement]
*
* @author Ram'sSoft
*
*/
@Entity
@Table(name = "uom_tab")
@EntityListeners(AuditingEntityListener.class)
public class Uom {
// -----primary key ---------
@Id
@Column(name = "u_id")
@GeneratedValue(generator = "uom_gen")
@GenericGenerator(name = "uom_gen", strategy = "increment")
private Long uomId;
// -------Dates for Records--------
@Column(name = "c_dte")
@Temporal(TemporalType.TIMESTAMP)
@CreatedDate
@DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss")
private Date createdOn;
@Column(name = "m_dte")
@Temporal(TemporalType.TIMESTAMP)
@LastModifiedDate
@DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss")
private Date modifiedOn;
// --------UI INPUTS-------
@Column(name = "u_type")
private String uomType;
@Column(name = "u_model")
private String uomModel;
@Column(name = "u_desc")
private String description;
// ----------constructors-----------
// 1. default const
public Uom() {
System.out.println("Uom::default-constructor");
}
// 2. one param PK based const
public Uom(Long uomId) {
System.out.println("Uom::1-param constructor");
this.uomId = uomId;
}
// 3. multipart Import const
public Uom(String uomType, String uomModel, String description) {
this.uomType = uomType;
this.uomModel = uomModel;
this.description = description;
}
// ------------methods----------
public Long getUomId() {
return uomId;
}
public void setUomId(Long uomId) {
this.uomId = uomId;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
public Date getModifiedOn() {
return modifiedOn;
}
public void setModifiedOn(Date modifiedOn) {
this.modifiedOn = modifiedOn;
}
public String getUomType() {
return uomType;
}
public void setUomType(String uomType) {
this.uomType = uomType;
}
public String getUomModel() {
return uomModel;
}
public void setUomModel(String uomModel) {
this.uomModel = uomModel;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
// ----------toString--------
@Override
public String toString() {
return "Uom [uomId=" + uomId + ", createdOn=" + createdOn + ", modifiedOn=" + modifiedOn + ", uomType="
+ uomType + ", uomModel=" + uomModel + ", description=" + description + "]";
}// method
}// class
| UTF-8 | Java | 3,238 | java | Uom.java | Java | [
{
"context": "lass for Uom[Unit of Measurement]\r\n * \r\n * @author Ram'sSoft\r\n *\r\n */\r\n\r\n@Entity\r\n@Table(name = \"uom_tab\")\r\n@E",
"end": 753,
"score": 0.9877958297729492,
"start": 744,
"tag": "NAME",
"value": "Ram'sSoft"
}
] | null | [] |
package com.sathyatech.app.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.springframework.format.annotation.DateTimeFormat;
/**
* This is model class for Uom[Unit of Measurement]
*
* @author Ram'sSoft
*
*/
@Entity
@Table(name = "uom_tab")
@EntityListeners(AuditingEntityListener.class)
public class Uom {
// -----primary key ---------
@Id
@Column(name = "u_id")
@GeneratedValue(generator = "uom_gen")
@GenericGenerator(name = "uom_gen", strategy = "increment")
private Long uomId;
// -------Dates for Records--------
@Column(name = "c_dte")
@Temporal(TemporalType.TIMESTAMP)
@CreatedDate
@DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss")
private Date createdOn;
@Column(name = "m_dte")
@Temporal(TemporalType.TIMESTAMP)
@LastModifiedDate
@DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss")
private Date modifiedOn;
// --------UI INPUTS-------
@Column(name = "u_type")
private String uomType;
@Column(name = "u_model")
private String uomModel;
@Column(name = "u_desc")
private String description;
// ----------constructors-----------
// 1. default const
public Uom() {
System.out.println("Uom::default-constructor");
}
// 2. one param PK based const
public Uom(Long uomId) {
System.out.println("Uom::1-param constructor");
this.uomId = uomId;
}
// 3. multipart Import const
public Uom(String uomType, String uomModel, String description) {
this.uomType = uomType;
this.uomModel = uomModel;
this.description = description;
}
// ------------methods----------
public Long getUomId() {
return uomId;
}
public void setUomId(Long uomId) {
this.uomId = uomId;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
public Date getModifiedOn() {
return modifiedOn;
}
public void setModifiedOn(Date modifiedOn) {
this.modifiedOn = modifiedOn;
}
public String getUomType() {
return uomType;
}
public void setUomType(String uomType) {
this.uomType = uomType;
}
public String getUomModel() {
return uomModel;
}
public void setUomModel(String uomModel) {
this.uomModel = uomModel;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
// ----------toString--------
@Override
public String toString() {
return "Uom [uomId=" + uomId + ", createdOn=" + createdOn + ", modifiedOn=" + modifiedOn + ", uomType="
+ uomType + ", uomModel=" + uomModel + ", description=" + description + "]";
}// method
}// class
| 3,238 | 0.670784 | 0.669549 | 136 | 21.794117 | 19.886486 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.125 | false | false | 2 |
224dadaecbc431910766f0803dd0eb9ce813193a | 6,519,760,376,192 | 04ff707e42c25883dc2f8e58812ea74384c8b866 | /org.carp/src/main/java/org/carp/type/CarpClobImpl.java | edc55b8dffd545100b145f6f124f322da4d07d39 | [
"Apache-2.0"
] | permissive | china982001/carp | https://github.com/china982001/carp | eb7595a633790ecd7a1e3a2438d8e18161bf9098 | cb9e1b4a7011f6ec350b087f4307e57a73392a3d | refs/heads/master | 2020-03-19T13:45:51.813000 | 2018-11-07T03:43:10 | 2018-11-07T03:43:10 | 136,594,129 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Copyright 2009-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.carp.type;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.sql.Clob;
import java.sql.SQLException;
/**
* Clob 接口实现类
* @author Administrator
*
*/
public class CarpClobImpl implements Clob {
private String _data = ""; //default empty string, length be 0
public CarpClobImpl(final String data) throws SQLException {
if(data == null)
throw new SQLException("Argument be null. data:"+data);
_data = data;
}
/**
* @see java.sql.Clob#length()
*/
public long length() throws SQLException {
return this._data.length();
}
/**
* @see java.sql.Clob#truncate(long)
*/
public void truncate(long pos) throws SQLException {
if(pos == this._data.length())
return;
if(pos < 0 || pos > this._data.length())
throw new SQLException("OutOfRangeArgument. pos: " +pos);
this._data = this._data.substring(0, (int)pos);
}
/**
* @see java.sql.Clob#getAsciiStream()
*/
public InputStream getAsciiStream() throws SQLException {
try {
return new ByteArrayInputStream(_data.getBytes("US-ASCII"));
} catch (UnsupportedEncodingException e) {
throw new SQLException(e);
}
}
/**
* @see java.sql.Clob#setAsciiStream(long)
*/
public OutputStream setAsciiStream(long pos) throws SQLException {
excep(); return null;
}
/**
* @see java.sql.Clob#getCharacterStream()
*/
public Reader getCharacterStream() throws SQLException {
return new StringReader(this._data);
}
/**
* @see java.sql.Clob#setCharacterStream(long)
*/
public Writer setCharacterStream(long pos) throws SQLException {
excep(); return null;
}
/**
* @see java.sql.Clob#getSubString(long, int)
*/
public String getSubString(long pos, int len) throws SQLException {
if(pos == 1 && len == this._data.length())
return this._data;
if(pos < 1 || pos > this._data.length())
throw new SQLException("OutOfRangeArgument. pos: " +pos);
int idx = (int)pos - 1; //The start index of clob is 1 more than that of string
if(len < 0 || len >_data.length() -idx)
throw new SQLException("OutOfRangeArgument. len: "+len);
return this._data.substring(idx, idx+len);
}
/**
* @see java.sql.Clob#setString(long, String)
*/
public int setString(long pos, String string) throws SQLException {
excep(); return 0;
}
/**
* @see java.sql.Clob#setString(long, String, int, int)
*/
public int setString(long pos, String string, int i, int j) throws SQLException {
excep(); return 0;
}
/**
* @see java.sql.Clob#position(String, long)
*/
public long position(String string, long pos) throws SQLException {
excep(); return 0;
}
/**
* @see java.sql.Clob#position(Clob, long)
*/
public long position(Clob colb, long pos) throws SQLException {
excep(); return 0;
}
private static void excep() {
throw new UnsupportedOperationException("Blob may not be manipulated from creating session");
}
/**
* @see java.sql.Clob#free()
*/
public void free() throws SQLException {
this._data = null;
}
/**
* @see java.sql.Clob#getCharacterStream(long, long)
*/
public Reader getCharacterStream(long pos, long length) throws SQLException {
return new StringReader(this.getSubString(pos, (int)length));
}
}
| UTF-8 | Java | 3,996 | java | CarpClobImpl.java | Java | [
{
"context": "va.sql.SQLException;\n\n/**\n * Clob 接口实现类\n * @author Administrator\n *\n */\npublic class CarpClobImpl implements Clob ",
"end": 954,
"score": 0.9889522194862366,
"start": 941,
"tag": "NAME",
"value": "Administrator"
}
] | null | [] | /**
* Copyright 2009-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.carp.type;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.sql.Clob;
import java.sql.SQLException;
/**
* Clob 接口实现类
* @author Administrator
*
*/
public class CarpClobImpl implements Clob {
private String _data = ""; //default empty string, length be 0
public CarpClobImpl(final String data) throws SQLException {
if(data == null)
throw new SQLException("Argument be null. data:"+data);
_data = data;
}
/**
* @see java.sql.Clob#length()
*/
public long length() throws SQLException {
return this._data.length();
}
/**
* @see java.sql.Clob#truncate(long)
*/
public void truncate(long pos) throws SQLException {
if(pos == this._data.length())
return;
if(pos < 0 || pos > this._data.length())
throw new SQLException("OutOfRangeArgument. pos: " +pos);
this._data = this._data.substring(0, (int)pos);
}
/**
* @see java.sql.Clob#getAsciiStream()
*/
public InputStream getAsciiStream() throws SQLException {
try {
return new ByteArrayInputStream(_data.getBytes("US-ASCII"));
} catch (UnsupportedEncodingException e) {
throw new SQLException(e);
}
}
/**
* @see java.sql.Clob#setAsciiStream(long)
*/
public OutputStream setAsciiStream(long pos) throws SQLException {
excep(); return null;
}
/**
* @see java.sql.Clob#getCharacterStream()
*/
public Reader getCharacterStream() throws SQLException {
return new StringReader(this._data);
}
/**
* @see java.sql.Clob#setCharacterStream(long)
*/
public Writer setCharacterStream(long pos) throws SQLException {
excep(); return null;
}
/**
* @see java.sql.Clob#getSubString(long, int)
*/
public String getSubString(long pos, int len) throws SQLException {
if(pos == 1 && len == this._data.length())
return this._data;
if(pos < 1 || pos > this._data.length())
throw new SQLException("OutOfRangeArgument. pos: " +pos);
int idx = (int)pos - 1; //The start index of clob is 1 more than that of string
if(len < 0 || len >_data.length() -idx)
throw new SQLException("OutOfRangeArgument. len: "+len);
return this._data.substring(idx, idx+len);
}
/**
* @see java.sql.Clob#setString(long, String)
*/
public int setString(long pos, String string) throws SQLException {
excep(); return 0;
}
/**
* @see java.sql.Clob#setString(long, String, int, int)
*/
public int setString(long pos, String string, int i, int j) throws SQLException {
excep(); return 0;
}
/**
* @see java.sql.Clob#position(String, long)
*/
public long position(String string, long pos) throws SQLException {
excep(); return 0;
}
/**
* @see java.sql.Clob#position(Clob, long)
*/
public long position(Clob colb, long pos) throws SQLException {
excep(); return 0;
}
private static void excep() {
throw new UnsupportedOperationException("Blob may not be manipulated from creating session");
}
/**
* @see java.sql.Clob#free()
*/
public void free() throws SQLException {
this._data = null;
}
/**
* @see java.sql.Clob#getCharacterStream(long, long)
*/
public Reader getCharacterStream(long pos, long length) throws SQLException {
return new StringReader(this.getSubString(pos, (int)length));
}
}
| 3,996 | 0.691516 | 0.685492 | 152 | 25.171053 | 25.305183 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.394737 | false | false | 2 |
b187baf126ddea61b8575ce1095ed1923739f708 | 2,104,534,020,367 | 75a3a8af19c84dc04d85c9d60155aed902f1a548 | /src/main/java/io/ffreedom/polaris/indicators/api/IndicatorEvent.java | aff8c7835303f46dc9deec6faca93eff60d2a59b | [
"ICU",
"Apache-2.0"
] | permissive | Sahanduiuc/polaris | https://github.com/Sahanduiuc/polaris | 238a3fc20ce7c0821cd7a0d45c453ca3be807805 | 0a9fd3104e1d900e1be7d2f08145d9f31022aa4c | refs/heads/master | 2020-06-19T03:07:56.943000 | 2019-07-09T08:53:34 | 2019-07-09T08:53:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.ffreedom.polaris.indicators.api;
public interface IndicatorEvent {
String getEventName();
}
| UTF-8 | Java | 108 | java | IndicatorEvent.java | Java | [] | null | [] | package io.ffreedom.polaris.indicators.api;
public interface IndicatorEvent {
String getEventName();
}
| 108 | 0.777778 | 0.777778 | 7 | 14.428572 | 16.952515 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 2 |
9d2fafc0a08b364e655f616694426342531b8f8b | 7,112,465,858,758 | b705de68ac7e0091d183c5cfe316049b1a5e3fd1 | /src/main/java/com/cheeseind/blogenginewebflux/security/LoginJsonAuthConverter.java | 7eb44173d85a44972ee60ea6058facd1e38d28de | [] | no_license | FitzgeraldMouseton/blog-webflux | https://github.com/FitzgeraldMouseton/blog-webflux | bf5a86e9efb0f7b176c9a3c08cdf3c7350180a1d | b4cc3a342fa2606bc2c3f1fbd46583c3cb50d1ca | refs/heads/master | 2023-03-20T11:38:16.170000 | 2021-03-16T08:18:25 | 2021-03-16T08:18:25 | 331,213,331 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cheeseind.blogenginewebflux.security;
import com.cheeseind.blogenginewebflux.models.dto.authdto.LoginRequest;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.authentication.ServerAuthenticationConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Slf4j
@Component
@RequiredArgsConstructor
public class LoginJsonAuthConverter implements ServerAuthenticationConverter {
private final ObjectMapper mapper;
@Override
public Mono<Authentication> convert(ServerWebExchange exchange) {
return exchange.getRequest().getBody()
.next()
.flatMap(buffer ->
Mono.fromCallable(() -> mapper.readValue(buffer.asInputStream(), LoginRequest.class)))
.map(request -> new UsernamePasswordAuthenticationToken(request.getEmail(), request.getPassword()));
}
} | UTF-8 | Java | 1,218 | java | LoginJsonAuthConverter.java | Java | [] | null | [] | package com.cheeseind.blogenginewebflux.security;
import com.cheeseind.blogenginewebflux.models.dto.authdto.LoginRequest;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.authentication.ServerAuthenticationConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Slf4j
@Component
@RequiredArgsConstructor
public class LoginJsonAuthConverter implements ServerAuthenticationConverter {
private final ObjectMapper mapper;
@Override
public Mono<Authentication> convert(ServerWebExchange exchange) {
return exchange.getRequest().getBody()
.next()
.flatMap(buffer ->
Mono.fromCallable(() -> mapper.readValue(buffer.asInputStream(), LoginRequest.class)))
.map(request -> new UsernamePasswordAuthenticationToken(request.getEmail(), request.getPassword()));
}
} | 1,218 | 0.781609 | 0.779146 | 30 | 39.633335 | 33.585197 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 2 |
d88bbaf1f0c767f3fc3b87e5dc97f0a46c322d09 | 10,084,583,225,570 | 548c82b3acfadf712b635e3533347a09198c1364 | /src/com/newPrograms/test/MultiplyTwoMatrices.java | 9bb9f646b5e5965a77b9813e9ac2f0900c29ae4e | [] | no_license | samirsukla/JavaInterviewPrograms | https://github.com/samirsukla/JavaInterviewPrograms | 34e54e6d97da15e9cee47d439ecd2fdec87e7cd9 | 2fb3685026b8c3fadb889926c2a3905a49b2b1ab | refs/heads/master | 2023-02-28T20:56:38.236000 | 2021-02-05T06:07:51 | 2021-02-05T06:07:51 | 336,179,372 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.newPrograms.test;
public class MultiplyTwoMatrices {
public static void main(String[] args) {
int arr1[][] = {{1,2,3},{7,8,9},{4,5,6}};
int arr2[][] = {{2,3,5},{7,1,2},{3,6,4}};
int result[][] = new int[3][3];
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++) {
result[i][j] =0;
for (int k=0;k<3;k++) {
result[i][j]+=arr1[i][k] * arr2[k][j];
}
System.out.print(result[i][j]+" ");
}
System.out.println();
}
}
}
| UTF-8 | Java | 475 | java | MultiplyTwoMatrices.java | Java | [] | null | [] | package com.newPrograms.test;
public class MultiplyTwoMatrices {
public static void main(String[] args) {
int arr1[][] = {{1,2,3},{7,8,9},{4,5,6}};
int arr2[][] = {{2,3,5},{7,1,2},{3,6,4}};
int result[][] = new int[3][3];
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++) {
result[i][j] =0;
for (int k=0;k<3;k++) {
result[i][j]+=arr1[i][k] * arr2[k][j];
}
System.out.print(result[i][j]+" ");
}
System.out.println();
}
}
}
| 475 | 0.492632 | 0.427368 | 24 | 18.791666 | 16.286444 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.458333 | false | false | 2 |
4daafcf74b517819b257b52fc52590432b2a0740 | 2,310,692,425,482 | 7789e94612d336fe8ad6be591acba9a346cc446c | /src/main/Java/GUI/bookSearchInterFrm.java | f84e9c4b7aac52c4c358476684f408e89f875b6c | [] | no_license | Cookies-Yan/LibraryDatabaseSearchEngine | https://github.com/Cookies-Yan/LibraryDatabaseSearchEngine | a591daef3e2564735a3afd4ed3625f3dc7bb617d | fecd7836e13c7fcb4f8a572675dbdf6f5ce59d53 | refs/heads/master | 2022-12-12T13:33:31.169000 | 2020-09-10T21:12:07 | 2020-09-10T21:12:07 | 294,523,369 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package GUI;
import Dao.BookMngDao;
import Dao.LoanMngDao;
import Model.BookMng;
import Model.LoanMng;
import Util.DbUtil;
import org.apache.commons.lang.StringUtils;
import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;
public class bookSearchInterFrm extends JInternalFrame {
private JTable Book_Table;
private JTextField Search_Txt;
private JTextField IsbnShowTxt;
private JTextField AuthorShowTxt;
private JTextField TitleShowTxt;
private JTextField idInputTxt;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
private DbUtil dbUtil = new DbUtil();
private BookMngDao bookMngDao = new BookMngDao();
private LoanMngDao loanMngDao = new LoanMngDao();
private JTextField txtNoResult;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
bookSearchInterFrm frame = new bookSearchInterFrm();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public bookSearchInterFrm() {
setClosable(true);
setIconifiable(true);
setTitle("Check out");
setBounds(100, 100, 713, 669);
JScrollPane scrollPane = new JScrollPane();
Search_Txt = new JTextField();
Search_Txt.setColumns(10);
JButton Search_button = new JButton("Search");
Search_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bookSearchActionPerformed(e);
}
});
JPanel panel = new JPanel();
panel.setToolTipText("");
panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Book Information", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
JLabel lblSearchAndChoose = new JLabel("Search and choose a book to check out.");
txtNoResult = new JTextField();
txtNoResult.setForeground(new Color(255, 0, 0));
txtNoResult.setText("");
txtNoResult.setEditable(false);
txtNoResult.setBackground(UIManager.getColor("CheckBox.background"));
txtNoResult.setColumns(10);
txtNoResult.setBorder(new EmptyBorder(0,0,0,0));
GroupLayout groupLayout = new GroupLayout(getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.TRAILING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(43)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 608, Short.MAX_VALUE)
.addComponent(panel, GroupLayout.DEFAULT_SIZE, 608, Short.MAX_VALUE)
.addGroup(groupLayout.createSequentialGroup()
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(lblSearchAndChoose)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(Search_Txt, GroupLayout.PREFERRED_SIZE, 492, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(Search_button, GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE))
.addComponent(txtNoResult, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))))
.addGap(46))
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.TRAILING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(33)
.addComponent(lblSearchAndChoose)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(Search_Txt, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE)
.addComponent(Search_button))
.addGap(4)
.addComponent(txtNoResult, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 224, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(panel, GroupLayout.PREFERRED_SIZE, 243, GroupLayout.PREFERRED_SIZE)
.addGap(62))
);
JLabel lblNewLabel = new JLabel("ISBN :");
IsbnShowTxt = new JTextField();
IsbnShowTxt.setEditable(false);
IsbnShowTxt.setColumns(10);
JLabel lblNewLabel_1 = new JLabel("Author(s):");
AuthorShowTxt = new JTextField();
AuthorShowTxt.setEditable(false);
AuthorShowTxt.setColumns(10);
JLabel lblNewLabel_2 = new JLabel("Title:");
TitleShowTxt = new JTextField();
TitleShowTxt.setEditable(false);
TitleShowTxt.setColumns(10);
JLabel lblNewLabel_3 = new JLabel("Card_id:");
idInputTxt = new JTextField();
idInputTxt.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
int keyChar=e.getKeyChar();
if (keyChar>=KeyEvent.VK_0 && keyChar<=KeyEvent.VK_9) {
} else {
e.consume();
}
String s = idInputTxt.getText();
if(s.length() >= 10) e.consume();
}
});
idInputTxt.setColumns(10);
JButton btnNewButton = new JButton("Check Out");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
checkOutActionPerformed(e);
}
});
JLabel lblrequaired = new JLabel("*requaired");
lblrequaired.setForeground(new Color(255, 0, 0));
GroupLayout gl_panel = new GroupLayout(panel);
gl_panel.setHorizontalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addGap(57)
.addGroup(gl_panel.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
.addComponent(lblNewLabel)
.addComponent(lblNewLabel_2))
.addComponent(lblNewLabel_3))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(gl_panel.createParallelGroup(Alignment.TRAILING)
.addGroup(Alignment.LEADING, gl_panel.createSequentialGroup()
.addComponent(idInputTxt, GroupLayout.PREFERRED_SIZE, 181, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(lblrequaired)
.addContainerGap())
.addGroup(gl_panel.createSequentialGroup()
.addGroup(gl_panel.createParallelGroup(Alignment.TRAILING)
.addComponent(TitleShowTxt, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 402, Short.MAX_VALUE)
.addGroup(gl_panel.createSequentialGroup()
.addComponent(IsbnShowTxt, GroupLayout.PREFERRED_SIZE, 96, GroupLayout.PREFERRED_SIZE)
.addGap(44)
.addComponent(lblNewLabel_1)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(AuthorShowTxt, GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE))
.addComponent(btnNewButton, GroupLayout.PREFERRED_SIZE, 113, GroupLayout.PREFERRED_SIZE))
.addGap(59))))
);
gl_panel.setVerticalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addGap(26)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(lblNewLabel)
.addComponent(IsbnShowTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(lblNewLabel_1)
.addComponent(AuthorShowTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(31)
.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
.addComponent(lblNewLabel_2)
.addComponent(TitleShowTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED, 19, Short.MAX_VALUE)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(lblNewLabel_3)
.addComponent(idInputTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(lblrequaired))
.addGap(18)
.addComponent(btnNewButton)
.addGap(23))
);
panel.setLayout(gl_panel);
Book_Table = new JTable();
// TableColumn column12 = Book_Table.getColumnModel().getColumn(3);
// column12.setCellEditor(Book_Table.getDefaultEditor(Boolean.class));
// column12.setCellRenderer(Book_Table.getDefaultRenderer(Boolean.class));
Book_Table.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent me) {
Book_TableMousePressed(me);
}
});
Book_Table.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"ISBN", "Title", "Author", "Availability"
}
) {
boolean[] columnEditables = new boolean[] {
false, false, false, false
};
public boolean isCellEditable(int row, int column) {
return columnEditables[column];
}
});
Book_Table.getColumnModel().getColumn(1).setPreferredWidth(250);
Book_Table.getColumnModel().getColumn(2).setPreferredWidth(160);
Book_Table.getColumnModel().getColumn(3).setPreferredWidth(110);
scrollPane.setViewportView(Book_Table);
getContentPane().setLayout(groupLayout);
}
/**
* table click event
* @param me
*/
private void Book_TableMousePressed(MouseEvent me) {
int row=this.Book_Table.getSelectedRow();
this.IsbnShowTxt.setText((String)(Book_Table.getValueAt(row,0)));
this.TitleShowTxt.setText((String)(Book_Table.getValueAt(row,1)));
this.AuthorShowTxt.setText((String)(Book_Table.getValueAt(row,2)));
}
/**
* check out event(check in button pressed)
* @param e
*/
private void checkOutActionPerformed(ActionEvent e) {
String isbn=this.IsbnShowTxt.getText();
String card_id=this.idInputTxt.getText();
Calendar cal = Calendar.getInstance();
Date date_out = cal.getTime();
String dateOut=df.format(date_out);
cal.add(Calendar.DATE, 14);
Date due_date= (Date) cal.getTime();
String dueDate=df.format(due_date);
boolean countPass=true,availPass=true;
int idExit=0;
if(StringUtils.isEmpty(isbn)) {
JOptionPane.showMessageDialog(null,"Please select a book", "Warning!",JOptionPane.ERROR_MESSAGE);
return;
}
if(StringUtils.isEmpty(card_id)) {
JOptionPane.showMessageDialog(null,"Card_id is requaired, please input again!", "Warning!",JOptionPane.ERROR_MESSAGE);
return;
}
LoanMng loanMng = new LoanMng(isbn, Integer.parseInt(card_id), dateOut, dueDate);
Connection con =null;
try {
con=dbUtil.getCon();
ResultSet rs_id = loanMngDao.checkId(con,loanMng);
while(rs_id.next()) {
idExit++;
}
if(idExit==0){
JOptionPane.showMessageDialog(null,"Not an available card_id, please check again!", "Error!",JOptionPane.ERROR_MESSAGE);
}
else {
ResultSet rs_count = loanMngDao.checkCount(con, loanMng);
while(rs_count.next()) {
if(rs_count.getInt("count(*)") >= 3) {
JOptionPane.showMessageDialog(null,"You have already 3 loans, cann't borrow another book!", "Warning!", JOptionPane.ERROR_MESSAGE);
countPass=false;
break;
}
}
if(countPass) {
ResultSet rs_avail = loanMngDao.checkAvail(con, loanMng);
while(rs_avail.next()) {
if(rs_avail.getInt("Avail")==1) {
JOptionPane.showMessageDialog(null, "This book has been checked out!", "Warning!", JOptionPane.ERROR_MESSAGE);
availPass=false;
break;
}
if(rs_avail.getInt("avail")==0) {
availPass=true;
}
}
if(availPass) {
int n = loanMngDao.addLoan(con,loanMng);
if( n == 1 ) {
ResultSet rs_LoanId = loanMngDao.getLoan_id(con,loanMng);
int ID = 0;
// System.out.println(rs_LoanId);
while(rs_LoanId.next()){
ID = rs_LoanId.getInt("Loan_id") + 10000;
// System.out.println(ID);
}
loanMngDao.addFine(con,ID);
JOptionPane.showMessageDialog(null,"Check out successful.");
this.resetValue();
this.searchBook();
}
else {
JOptionPane.showMessageDialog(null,"Check out failed.", "Error!",JOptionPane.ERROR_MESSAGE);
}
}
}
}
}catch(Exception evt) {
evt.printStackTrace();
JOptionPane.showMessageDialog(null,"Fail to connect to the library database.","Error!", JOptionPane.ERROR_MESSAGE);
}finally {
try {
dbUtil.closeCon(con);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
/**
* Search event
* @param evt
*/
private void bookSearchActionPerformed(ActionEvent evt) {
this.resetValue();
this.searchBook();
}
private void searchBook() {
this.txtNoResult.setText("");
String search=this.Search_Txt.getText();
BookMng bookMng=new BookMng();
bookMng.setSearchTxt(search);
this.fillTable(bookMng);
}
/**
* fill result table
* @param bookMng
*/
private void fillTable(BookMng bookMng) {
DefaultTableModel dtm=(DefaultTableModel) Book_Table.getModel();
dtm.setRowCount(0);
Connection con =null;
int i =0;
try {
con=dbUtil.getCon();
ResultSet rs=bookMngDao.list(con,bookMng);
while(rs.next()) {
i++;
Vector<String> v=new Vector();
v.add(rs.getString("Isbn"));
v.add(rs.getString("Title"));
v.add(rs.getString("a"));
if(rs.getInt("Avail")==1) {
v.add("Check Out");
}else {
}
dtm.addRow(v);
}
if(i == 0) {
this.txtNoResult.setText("No result !");
}
}catch(Exception e) {
e.printStackTrace();
}finally {
try {
dbUtil.closeCon(con);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void resetValue() {
this.IsbnShowTxt.setText("");
this.AuthorShowTxt.setText("");
this.TitleShowTxt.setText("");
this.idInputTxt.setText("");
}
}
| UTF-8 | Java | 14,774 | java | bookSearchInterFrm.java | Java | [] | null | [] | package GUI;
import Dao.BookMngDao;
import Dao.LoanMngDao;
import Model.BookMng;
import Model.LoanMng;
import Util.DbUtil;
import org.apache.commons.lang.StringUtils;
import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;
public class bookSearchInterFrm extends JInternalFrame {
private JTable Book_Table;
private JTextField Search_Txt;
private JTextField IsbnShowTxt;
private JTextField AuthorShowTxt;
private JTextField TitleShowTxt;
private JTextField idInputTxt;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
private DbUtil dbUtil = new DbUtil();
private BookMngDao bookMngDao = new BookMngDao();
private LoanMngDao loanMngDao = new LoanMngDao();
private JTextField txtNoResult;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
bookSearchInterFrm frame = new bookSearchInterFrm();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public bookSearchInterFrm() {
setClosable(true);
setIconifiable(true);
setTitle("Check out");
setBounds(100, 100, 713, 669);
JScrollPane scrollPane = new JScrollPane();
Search_Txt = new JTextField();
Search_Txt.setColumns(10);
JButton Search_button = new JButton("Search");
Search_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bookSearchActionPerformed(e);
}
});
JPanel panel = new JPanel();
panel.setToolTipText("");
panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Book Information", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
JLabel lblSearchAndChoose = new JLabel("Search and choose a book to check out.");
txtNoResult = new JTextField();
txtNoResult.setForeground(new Color(255, 0, 0));
txtNoResult.setText("");
txtNoResult.setEditable(false);
txtNoResult.setBackground(UIManager.getColor("CheckBox.background"));
txtNoResult.setColumns(10);
txtNoResult.setBorder(new EmptyBorder(0,0,0,0));
GroupLayout groupLayout = new GroupLayout(getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.TRAILING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(43)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 608, Short.MAX_VALUE)
.addComponent(panel, GroupLayout.DEFAULT_SIZE, 608, Short.MAX_VALUE)
.addGroup(groupLayout.createSequentialGroup()
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(lblSearchAndChoose)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(Search_Txt, GroupLayout.PREFERRED_SIZE, 492, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(Search_button, GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE))
.addComponent(txtNoResult, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))))
.addGap(46))
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.TRAILING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(33)
.addComponent(lblSearchAndChoose)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(Search_Txt, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE)
.addComponent(Search_button))
.addGap(4)
.addComponent(txtNoResult, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 224, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(panel, GroupLayout.PREFERRED_SIZE, 243, GroupLayout.PREFERRED_SIZE)
.addGap(62))
);
JLabel lblNewLabel = new JLabel("ISBN :");
IsbnShowTxt = new JTextField();
IsbnShowTxt.setEditable(false);
IsbnShowTxt.setColumns(10);
JLabel lblNewLabel_1 = new JLabel("Author(s):");
AuthorShowTxt = new JTextField();
AuthorShowTxt.setEditable(false);
AuthorShowTxt.setColumns(10);
JLabel lblNewLabel_2 = new JLabel("Title:");
TitleShowTxt = new JTextField();
TitleShowTxt.setEditable(false);
TitleShowTxt.setColumns(10);
JLabel lblNewLabel_3 = new JLabel("Card_id:");
idInputTxt = new JTextField();
idInputTxt.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
int keyChar=e.getKeyChar();
if (keyChar>=KeyEvent.VK_0 && keyChar<=KeyEvent.VK_9) {
} else {
e.consume();
}
String s = idInputTxt.getText();
if(s.length() >= 10) e.consume();
}
});
idInputTxt.setColumns(10);
JButton btnNewButton = new JButton("Check Out");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
checkOutActionPerformed(e);
}
});
JLabel lblrequaired = new JLabel("*requaired");
lblrequaired.setForeground(new Color(255, 0, 0));
GroupLayout gl_panel = new GroupLayout(panel);
gl_panel.setHorizontalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addGap(57)
.addGroup(gl_panel.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
.addComponent(lblNewLabel)
.addComponent(lblNewLabel_2))
.addComponent(lblNewLabel_3))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(gl_panel.createParallelGroup(Alignment.TRAILING)
.addGroup(Alignment.LEADING, gl_panel.createSequentialGroup()
.addComponent(idInputTxt, GroupLayout.PREFERRED_SIZE, 181, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(lblrequaired)
.addContainerGap())
.addGroup(gl_panel.createSequentialGroup()
.addGroup(gl_panel.createParallelGroup(Alignment.TRAILING)
.addComponent(TitleShowTxt, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 402, Short.MAX_VALUE)
.addGroup(gl_panel.createSequentialGroup()
.addComponent(IsbnShowTxt, GroupLayout.PREFERRED_SIZE, 96, GroupLayout.PREFERRED_SIZE)
.addGap(44)
.addComponent(lblNewLabel_1)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(AuthorShowTxt, GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE))
.addComponent(btnNewButton, GroupLayout.PREFERRED_SIZE, 113, GroupLayout.PREFERRED_SIZE))
.addGap(59))))
);
gl_panel.setVerticalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addGap(26)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(lblNewLabel)
.addComponent(IsbnShowTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(lblNewLabel_1)
.addComponent(AuthorShowTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(31)
.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
.addComponent(lblNewLabel_2)
.addComponent(TitleShowTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED, 19, Short.MAX_VALUE)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(lblNewLabel_3)
.addComponent(idInputTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(lblrequaired))
.addGap(18)
.addComponent(btnNewButton)
.addGap(23))
);
panel.setLayout(gl_panel);
Book_Table = new JTable();
// TableColumn column12 = Book_Table.getColumnModel().getColumn(3);
// column12.setCellEditor(Book_Table.getDefaultEditor(Boolean.class));
// column12.setCellRenderer(Book_Table.getDefaultRenderer(Boolean.class));
Book_Table.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent me) {
Book_TableMousePressed(me);
}
});
Book_Table.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"ISBN", "Title", "Author", "Availability"
}
) {
boolean[] columnEditables = new boolean[] {
false, false, false, false
};
public boolean isCellEditable(int row, int column) {
return columnEditables[column];
}
});
Book_Table.getColumnModel().getColumn(1).setPreferredWidth(250);
Book_Table.getColumnModel().getColumn(2).setPreferredWidth(160);
Book_Table.getColumnModel().getColumn(3).setPreferredWidth(110);
scrollPane.setViewportView(Book_Table);
getContentPane().setLayout(groupLayout);
}
/**
* table click event
* @param me
*/
private void Book_TableMousePressed(MouseEvent me) {
int row=this.Book_Table.getSelectedRow();
this.IsbnShowTxt.setText((String)(Book_Table.getValueAt(row,0)));
this.TitleShowTxt.setText((String)(Book_Table.getValueAt(row,1)));
this.AuthorShowTxt.setText((String)(Book_Table.getValueAt(row,2)));
}
/**
* check out event(check in button pressed)
* @param e
*/
private void checkOutActionPerformed(ActionEvent e) {
String isbn=this.IsbnShowTxt.getText();
String card_id=this.idInputTxt.getText();
Calendar cal = Calendar.getInstance();
Date date_out = cal.getTime();
String dateOut=df.format(date_out);
cal.add(Calendar.DATE, 14);
Date due_date= (Date) cal.getTime();
String dueDate=df.format(due_date);
boolean countPass=true,availPass=true;
int idExit=0;
if(StringUtils.isEmpty(isbn)) {
JOptionPane.showMessageDialog(null,"Please select a book", "Warning!",JOptionPane.ERROR_MESSAGE);
return;
}
if(StringUtils.isEmpty(card_id)) {
JOptionPane.showMessageDialog(null,"Card_id is requaired, please input again!", "Warning!",JOptionPane.ERROR_MESSAGE);
return;
}
LoanMng loanMng = new LoanMng(isbn, Integer.parseInt(card_id), dateOut, dueDate);
Connection con =null;
try {
con=dbUtil.getCon();
ResultSet rs_id = loanMngDao.checkId(con,loanMng);
while(rs_id.next()) {
idExit++;
}
if(idExit==0){
JOptionPane.showMessageDialog(null,"Not an available card_id, please check again!", "Error!",JOptionPane.ERROR_MESSAGE);
}
else {
ResultSet rs_count = loanMngDao.checkCount(con, loanMng);
while(rs_count.next()) {
if(rs_count.getInt("count(*)") >= 3) {
JOptionPane.showMessageDialog(null,"You have already 3 loans, cann't borrow another book!", "Warning!", JOptionPane.ERROR_MESSAGE);
countPass=false;
break;
}
}
if(countPass) {
ResultSet rs_avail = loanMngDao.checkAvail(con, loanMng);
while(rs_avail.next()) {
if(rs_avail.getInt("Avail")==1) {
JOptionPane.showMessageDialog(null, "This book has been checked out!", "Warning!", JOptionPane.ERROR_MESSAGE);
availPass=false;
break;
}
if(rs_avail.getInt("avail")==0) {
availPass=true;
}
}
if(availPass) {
int n = loanMngDao.addLoan(con,loanMng);
if( n == 1 ) {
ResultSet rs_LoanId = loanMngDao.getLoan_id(con,loanMng);
int ID = 0;
// System.out.println(rs_LoanId);
while(rs_LoanId.next()){
ID = rs_LoanId.getInt("Loan_id") + 10000;
// System.out.println(ID);
}
loanMngDao.addFine(con,ID);
JOptionPane.showMessageDialog(null,"Check out successful.");
this.resetValue();
this.searchBook();
}
else {
JOptionPane.showMessageDialog(null,"Check out failed.", "Error!",JOptionPane.ERROR_MESSAGE);
}
}
}
}
}catch(Exception evt) {
evt.printStackTrace();
JOptionPane.showMessageDialog(null,"Fail to connect to the library database.","Error!", JOptionPane.ERROR_MESSAGE);
}finally {
try {
dbUtil.closeCon(con);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
/**
* Search event
* @param evt
*/
private void bookSearchActionPerformed(ActionEvent evt) {
this.resetValue();
this.searchBook();
}
private void searchBook() {
this.txtNoResult.setText("");
String search=this.Search_Txt.getText();
BookMng bookMng=new BookMng();
bookMng.setSearchTxt(search);
this.fillTable(bookMng);
}
/**
* fill result table
* @param bookMng
*/
private void fillTable(BookMng bookMng) {
DefaultTableModel dtm=(DefaultTableModel) Book_Table.getModel();
dtm.setRowCount(0);
Connection con =null;
int i =0;
try {
con=dbUtil.getCon();
ResultSet rs=bookMngDao.list(con,bookMng);
while(rs.next()) {
i++;
Vector<String> v=new Vector();
v.add(rs.getString("Isbn"));
v.add(rs.getString("Title"));
v.add(rs.getString("a"));
if(rs.getInt("Avail")==1) {
v.add("Check Out");
}else {
}
dtm.addRow(v);
}
if(i == 0) {
this.txtNoResult.setText("No result !");
}
}catch(Exception e) {
e.printStackTrace();
}finally {
try {
dbUtil.closeCon(con);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void resetValue() {
this.IsbnShowTxt.setText("");
this.AuthorShowTxt.setText("");
this.TitleShowTxt.setText("");
this.idInputTxt.setText("");
}
}
| 14,774 | 0.666847 | 0.656288 | 422 | 33.00948 | 27.197451 | 166 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.658768 | false | false | 2 |
d0f0403cb383cfb58ea65b0f48b25232f49495ba | 9,491,877,734,040 | a19ca438798ce54d6be33ce1fd4adb03b4280943 | /src/main/java/kz/kazgisa/data/entity/user/UserMenu.java | bc86a43efab2ee1c8220bcb4772d640a4e485bac | [] | no_license | Adil-web/sedbpmn_last | https://github.com/Adil-web/sedbpmn_last | 73c472222cc81b0feeb9f166b98f1a260efc0313 | 79889a34439c82c6e98fbdef3953f562b75d56f3 | refs/heads/main | 2023-03-30T04:35:07.941000 | 2021-03-31T03:52:43 | 2021-03-31T03:52:43 | 353,217,723 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package kz.kazgisa.data.entity.user;
import kz.kazgisa.data.entity.base.BaseEntity;
import kz.kazgisa.data.entity.dict.Menu;
import kz.kazgisa.data.enums.MenuCode;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.ManyToOne;
@Entity
public class UserMenu extends BaseEntity {
private User user;
private Menu menu;
@ManyToOne
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@ManyToOne
public Menu getMenu() {
return menu;
}
public void setMenu(Menu menu) {
this.menu = menu;
}
}
| UTF-8 | Java | 688 | java | UserMenu.java | Java | [] | null | [] | package kz.kazgisa.data.entity.user;
import kz.kazgisa.data.entity.base.BaseEntity;
import kz.kazgisa.data.entity.dict.Menu;
import kz.kazgisa.data.enums.MenuCode;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.ManyToOne;
@Entity
public class UserMenu extends BaseEntity {
private User user;
private Menu menu;
@ManyToOne
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@ManyToOne
public Menu getMenu() {
return menu;
}
public void setMenu(Menu menu) {
this.menu = menu;
}
}
| 688 | 0.6875 | 0.6875 | 33 | 19.848484 | 15.105931 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.424242 | false | false | 2 |
698dbe55b78d305c53a7da7811a7309e7830902b | 30,906,584,716,071 | b267f1013314010178eacc2f0a9fde744aedc6a6 | /src/test/java/CucumberFramework/Pages/BasePage.java | 4cfacd202017edb52a068120e8ce050563d4fc10 | [] | no_license | recepalioglu1/MusterAutomationFramework | https://github.com/recepalioglu1/MusterAutomationFramework | c444bf12512f33d03ca25b8ab054a32397b3e992 | da79851cb8f41c104eafdbb0e93d6386ac4a1560 | refs/heads/master | 2022-12-27T15:36:03.452000 | 2020-10-04T14:00:49 | 2020-10-04T14:00:49 | 301,142,417 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package CucumberFramework.Pages;
import CucumberFramework.Utilities.WebDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.List;
public abstract class BasePage {
public BasePage() {
PageFactory.initElements(WebDriver.get(), this);
}
}
| UTF-8 | Java | 566 | java | BasePage.java | Java | [] | null | [] | package CucumberFramework.Pages;
import CucumberFramework.Utilities.WebDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.List;
public abstract class BasePage {
public BasePage() {
PageFactory.initElements(WebDriver.get(), this);
}
}
| 566 | 0.777385 | 0.777385 | 22 | 24.318182 | 21.194738 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false | 2 |
3b923b04423542f0f8cea21a4b45f827fd7e120f | 7,722,351,251,344 | a0d338bd4a9eb575b66a1d7b853d27daab6e6680 | /src/main/java/com/yang/netty/server/HandleServer.java | 1df773b1defb5b415e5b2d622dbde95771cbd853 | [] | no_license | yyy7400/netty-tools | https://github.com/yyy7400/netty-tools | 2b91f2fce6fd7c490fe93e3b6a849960775b2bca | d6fa7ac400458a685b6d9f62d045be769a002843 | refs/heads/master | 2022-06-30T09:00:19.746000 | 2020-01-08T01:20:24 | 2020-01-08T01:20:24 | 214,418,180 | 3 | 0 | null | false | 2022-06-17T02:32:31 | 2019-10-11T11:24:38 | 2020-01-08T01:20:34 | 2022-06-17T02:32:31 | 62 | 2 | 0 | 2 | Java | false | false | package com.yang.netty.server;
import org.springframework.stereotype.Component;
/**
* 服务端消息处理
* @author yangyuyang
* @date 2019-11-03
*/
@Component
public class HandleServer extends MessageHandleFactory {
@Override
public void recvHandle() {
// Do nothing.
}
}
| UTF-8 | Java | 302 | java | HandleServer.java | Java | [
{
"context": "k.stereotype.Component;\n\n/**\n * 服务端消息处理\n * @author yangyuyang\n * @date 2019-11-03\n */\n@Component\npublic class H",
"end": 118,
"score": 0.9994566440582275,
"start": 108,
"tag": "USERNAME",
"value": "yangyuyang"
}
] | null | [] | package com.yang.netty.server;
import org.springframework.stereotype.Component;
/**
* 服务端消息处理
* @author yangyuyang
* @date 2019-11-03
*/
@Component
public class HandleServer extends MessageHandleFactory {
@Override
public void recvHandle() {
// Do nothing.
}
}
| 302 | 0.690972 | 0.663194 | 17 | 15.941176 | 16.483398 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.117647 | false | false | 2 |
3c3cc37f5220becb223f6d88a0e7121abefc6e37 | 32,693,291,110,206 | 4fc58d299eebc83fcec018131dfd0942095ff949 | /src/drawing/model/Pen.java | d41c147d3c10d4acabf478f31c6df115dce72002 | [] | no_license | yun0000/Drawing | https://github.com/yun0000/Drawing | cc326d85348f615a7c4204caaf084a963a04b166 | 88b1945d2a0bb37ec909b972993f09a40355e9de | refs/heads/master | 2020-03-20T23:17:07.069000 | 2018-06-19T04:23:53 | 2018-06-19T04:23:53 | 137,839,187 | 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 drawing.model;
import java.awt.BasicStroke;
import java.awt.Graphics;
import java.util.ArrayList;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
public class Pen extends Figure {
ArrayList<Line> lines = new ArrayList<>();
Line eachLine;
double formerLineX;
double formerLineY;
double smallestX;
double smallestY;
double biggestX;
double biggestY;
double movedX;
double movedY;
public Pen(Color currentColor) {
super(currentColor);
}
public void setPoints (double startX, double startY, double endX, double endY) {
eachLine = new Line(this.color);
eachLine.setStartX(startX);
eachLine.setStartY(startY);
eachLine.setEndX(endX);
eachLine.setEndY(endY);
lines.add(eachLine);
}
public boolean isInside (int x, int y) {
if (x>=this.getSmallestX() && x<=this.getBiggestX())
if(y>=this.getSmallestY() && y<=this.getBiggestY())
return true;
return false;
}
public void draw(Graphics g) {
g.setColor(color);
for(Line eachLine:lines) {
Graphics2D g2d = (Graphics2D)g;
g2d.setStroke(new BasicStroke(this.thickness));
AffineTransform transform = g2d.getTransform();
if(this.isRotated())
g2d.rotate(angle*2, this.getCenterX() ,this.getCenterY());
g.drawLine((int)(eachLine.startX), (int)(eachLine.startY), (int)(eachLine.endX), (int)(eachLine.endY));
g2d.setTransform(transform);
}
}
public double getCenterX() {
return (this.getSmallestX()+this.getBiggestX())/2;
}
public double getSmallestX() {
biggestX = 0;
smallestX = 20000;
for(Line eachLine:lines)
if(eachLine.startX < smallestX)
smallestX = eachLine.startX;
return smallestX;
}
public double getBiggestX() {
biggestX = 0;
for(Line eachLine:lines)
if (eachLine.startX > biggestX)
biggestX = eachLine.startX;
return biggestX;
}
public double getCenterY() {
return (this.getSmallestY()+this.getBiggestY())/2;
}
public double getSmallestY() {
smallestY = 20000;
for(Line eachLine:lines)
if(eachLine.startY < smallestY)
smallestY = eachLine.startY;
return smallestY;
}
public double getBiggestY() {
biggestY = 0;
for(Line eachLine:lines)
if (eachLine.startY > biggestY)
biggestY = eachLine.startY;
return biggestY;
}
@Override
public void move(double movedX, double movedY) {
for(Line eachLine:lines) {
eachLine.startX += movedX;
eachLine.endX += movedX;
eachLine.startY += movedY;
eachLine.endY += movedY;
}
}
@Override
public void resize(double movedX, double movedY) {
Line firstLine = lines.get(0);
firstLine.startX -= movedX/10;
firstLine.startY -= movedX/10;
firstLine.endX += movedX/10;
firstLine.endY += movedX/10;
for(int i=1;i<lines.size();i++) {
Line eachLine = lines.get(i);
eachLine.startX = firstLine.endX;
eachLine.startY = firstLine.endY;
eachLine.endX += movedX*i/10;
eachLine.endY += movedX*i/10;
firstLine = eachLine;
}
}
}
| UTF-8 | Java | 3,905 | java | Pen.java | Java | [] | 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 drawing.model;
import java.awt.BasicStroke;
import java.awt.Graphics;
import java.util.ArrayList;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
public class Pen extends Figure {
ArrayList<Line> lines = new ArrayList<>();
Line eachLine;
double formerLineX;
double formerLineY;
double smallestX;
double smallestY;
double biggestX;
double biggestY;
double movedX;
double movedY;
public Pen(Color currentColor) {
super(currentColor);
}
public void setPoints (double startX, double startY, double endX, double endY) {
eachLine = new Line(this.color);
eachLine.setStartX(startX);
eachLine.setStartY(startY);
eachLine.setEndX(endX);
eachLine.setEndY(endY);
lines.add(eachLine);
}
public boolean isInside (int x, int y) {
if (x>=this.getSmallestX() && x<=this.getBiggestX())
if(y>=this.getSmallestY() && y<=this.getBiggestY())
return true;
return false;
}
public void draw(Graphics g) {
g.setColor(color);
for(Line eachLine:lines) {
Graphics2D g2d = (Graphics2D)g;
g2d.setStroke(new BasicStroke(this.thickness));
AffineTransform transform = g2d.getTransform();
if(this.isRotated())
g2d.rotate(angle*2, this.getCenterX() ,this.getCenterY());
g.drawLine((int)(eachLine.startX), (int)(eachLine.startY), (int)(eachLine.endX), (int)(eachLine.endY));
g2d.setTransform(transform);
}
}
public double getCenterX() {
return (this.getSmallestX()+this.getBiggestX())/2;
}
public double getSmallestX() {
biggestX = 0;
smallestX = 20000;
for(Line eachLine:lines)
if(eachLine.startX < smallestX)
smallestX = eachLine.startX;
return smallestX;
}
public double getBiggestX() {
biggestX = 0;
for(Line eachLine:lines)
if (eachLine.startX > biggestX)
biggestX = eachLine.startX;
return biggestX;
}
public double getCenterY() {
return (this.getSmallestY()+this.getBiggestY())/2;
}
public double getSmallestY() {
smallestY = 20000;
for(Line eachLine:lines)
if(eachLine.startY < smallestY)
smallestY = eachLine.startY;
return smallestY;
}
public double getBiggestY() {
biggestY = 0;
for(Line eachLine:lines)
if (eachLine.startY > biggestY)
biggestY = eachLine.startY;
return biggestY;
}
@Override
public void move(double movedX, double movedY) {
for(Line eachLine:lines) {
eachLine.startX += movedX;
eachLine.endX += movedX;
eachLine.startY += movedY;
eachLine.endY += movedY;
}
}
@Override
public void resize(double movedX, double movedY) {
Line firstLine = lines.get(0);
firstLine.startX -= movedX/10;
firstLine.startY -= movedX/10;
firstLine.endX += movedX/10;
firstLine.endY += movedX/10;
for(int i=1;i<lines.size();i++) {
Line eachLine = lines.get(i);
eachLine.startX = firstLine.endX;
eachLine.startY = firstLine.endY;
eachLine.endX += movedX*i/10;
eachLine.endY += movedX*i/10;
firstLine = eachLine;
}
}
}
| 3,905 | 0.561844 | 0.552113 | 146 | 25.746574 | 19.836597 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.541096 | false | false | 2 |
64a4bb794b6cd2dbca9a7dd9ad4bf3c9b7125477 | 2,405,181,749,574 | 60384d7047a01fb2794d4c9bf14072f2e57cad84 | /app/src/main/java/com/btetop/bean/AccountInfoBean.java | 731d358a831cd5a215916245ca4793d3ba31e4f7 | [
"MIT"
] | permissive | sophiemarceau/bte_Android | https://github.com/sophiemarceau/bte_Android | d88703209aa2a2d9f473938d9c6aadcad590a0f6 | e950ca0bc5a7f6b6386af1e7614a5bf8d70cf66e | refs/heads/master | 2020-08-27T11:03:35.250000 | 2019-10-25T02:05:14 | 2019-10-25T02:05:14 | 217,342,335 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.btetop.bean;
import java.io.Serializable;
/**
* Created by Administrator on 2018/3/13.
*/
public class AccountInfoBean {
public static class AccountInfoData implements Serializable {
private double allAmount;
private String tel;
private String point;//积分
private String friends;//邀请好友个数
private String holdCount;//邀请好友个数
private String settleCount;//邀请好友个数
private double totalAsset;//资产
public double getTotalAsset() {
return totalAsset;
}
public void setTotalAsset(double totalAsset) {
this.totalAsset = totalAsset;
}
public String getHoldCount() {
return holdCount;
}
public void setHoldCount(String holdCount) {
this.holdCount = holdCount;
}
public String getSettleCount() {
return settleCount;
}
public void setSettleCount(String settleCount) {
this.settleCount = settleCount;
}
public String getFriends() {
return friends;
}
public void setFriends(String friends) {
this.friends = friends;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getPoint() {
return point;
}
public void setPoint(String point) {
this.point = point;
}
private AccountInfo legalAccount;//币种
private AccountInfo btcAccount;//btc
public double getAllAmount() {
return allAmount;
}
public void setAllAmount(double allAmount) {
this.allAmount = allAmount;
}
public AccountInfo getLegalAccount() {
return legalAccount;
}
public void setLegalAccount(AccountInfo legalAccount) {
this.legalAccount = legalAccount;
}
public AccountInfo getBtcAccount() {
return btcAccount;
}
public void setBtcAccount(AccountInfo btcAccount) {
this.btcAccount = btcAccount;
}
public static class AccountInfo implements Serializable {
private String type;
private double balance;
private double legalBalance;//金额
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public double getLegalBalance() {
return legalBalance;
}
public void setLegalBalance(double legalBalance) {
this.legalBalance = legalBalance;
}
}
}
}
| UTF-8 | Java | 3,057 | java | AccountInfoBean.java | Java | [
{
"context": ";\n\nimport java.io.Serializable;\n\n/**\n * Created by Administrator on 2018/3/13.\n */\n\npublic class AccountInfoBean {",
"end": 87,
"score": 0.5363160371780396,
"start": 74,
"tag": "NAME",
"value": "Administrator"
}
] | null | [] | package com.btetop.bean;
import java.io.Serializable;
/**
* Created by Administrator on 2018/3/13.
*/
public class AccountInfoBean {
public static class AccountInfoData implements Serializable {
private double allAmount;
private String tel;
private String point;//积分
private String friends;//邀请好友个数
private String holdCount;//邀请好友个数
private String settleCount;//邀请好友个数
private double totalAsset;//资产
public double getTotalAsset() {
return totalAsset;
}
public void setTotalAsset(double totalAsset) {
this.totalAsset = totalAsset;
}
public String getHoldCount() {
return holdCount;
}
public void setHoldCount(String holdCount) {
this.holdCount = holdCount;
}
public String getSettleCount() {
return settleCount;
}
public void setSettleCount(String settleCount) {
this.settleCount = settleCount;
}
public String getFriends() {
return friends;
}
public void setFriends(String friends) {
this.friends = friends;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getPoint() {
return point;
}
public void setPoint(String point) {
this.point = point;
}
private AccountInfo legalAccount;//币种
private AccountInfo btcAccount;//btc
public double getAllAmount() {
return allAmount;
}
public void setAllAmount(double allAmount) {
this.allAmount = allAmount;
}
public AccountInfo getLegalAccount() {
return legalAccount;
}
public void setLegalAccount(AccountInfo legalAccount) {
this.legalAccount = legalAccount;
}
public AccountInfo getBtcAccount() {
return btcAccount;
}
public void setBtcAccount(AccountInfo btcAccount) {
this.btcAccount = btcAccount;
}
public static class AccountInfo implements Serializable {
private String type;
private double balance;
private double legalBalance;//金额
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public double getLegalBalance() {
return legalBalance;
}
public void setLegalBalance(double legalBalance) {
this.legalBalance = legalBalance;
}
}
}
}
| 3,057 | 0.54609 | 0.54376 | 127 | 22.661417 | 19.411913 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.299213 | false | false | 2 |
bc7e9ff32f118378928d8c49e912a3eb3ac771cd | 26,963,804,696,424 | ec9bf57a07b7b06134ec7a21407a11f69cc644f7 | /src/com/ubercab/client/core/network/TunesApi.java | 1bcc84a46eea2acfa099344c35f76622b98905fe | [] | no_license | jzarca01/com.ubercab | https://github.com/jzarca01/com.ubercab | f95c12cab7a28f05e8f1d1a9d8a12a5ac7fbf4b1 | e6b454fb0ad547287ae4e71e59d6b9482369647a | refs/heads/master | 2020-06-21T04:37:43.723000 | 2016-07-19T16:30:34 | 2016-07-19T16:30:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ubercab.client.core.network;
import com.ubercab.client.core.model.TunesProvider;
import com.ubercab.rider.realtime.model.Group;
import com.ubercab.rider.realtime.model.Playlist;
import java.util.Map;
import retrofit.Callback;
import retrofit.http.Body;
import retrofit.http.GET;
import retrofit.http.Header;
import retrofit.http.POST;
import retrofit.http.Path;
import retrofit.http.Query;
public abstract interface TunesApi
{
@POST("/rt/utunes/rider/handshake")
public abstract void handshake(@Header("accept-language") String paramString, @Body Map<String, String> paramMap, Callback<Object> paramCallback);
@GET("/rt/utunes/providers/{provider_id}/playlists/{playlist_id}")
public abstract void playlist(@Path("provider_id") String paramString1, @Path("playlist_id") String paramString2, @Header("accept-language") String paramString3, @Query("latitude") Double paramDouble1, @Query("longitude") Double paramDouble2, @Query("city_name") String paramString4, @Query("country_code_iso2") String paramString5, Callback<Playlist> paramCallback);
@GET("/rt/utunes/providers/{provider_id}")
public abstract void provider(@Path("provider_id") String paramString1, @Header("accept-language") String paramString2, @Query("check_trial") Boolean paramBoolean, @Query("latitude") Double paramDouble1, @Query("longitude") Double paramDouble2, @Query("city_name") String paramString3, @Query("country_code_iso2") String paramString4, Callback<TunesProvider> paramCallback);
@GET("/rt/utunes/providers/{provider_id}/search")
public abstract void search(@Path("provider_id") String paramString1, @Query("city_name") String paramString2, @Query("country_code_iso2") String paramString3, @Query("query") String paramString4, Callback<Group> paramCallback);
@POST("/rt/utunes/providers/{id}/start_trial")
public abstract void startTrial(@Path("id") String paramString1, @Header("accept-language") String paramString2, @Body Map<String, Object> paramMap, Callback<TunesProvider> paramCallback);
}
/* Location:
* Qualified Name: com.ubercab.client.core.network.TunesApi
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | UTF-8 | Java | 2,168 | java | TunesApi.java | Java | [] | null | [] | package com.ubercab.client.core.network;
import com.ubercab.client.core.model.TunesProvider;
import com.ubercab.rider.realtime.model.Group;
import com.ubercab.rider.realtime.model.Playlist;
import java.util.Map;
import retrofit.Callback;
import retrofit.http.Body;
import retrofit.http.GET;
import retrofit.http.Header;
import retrofit.http.POST;
import retrofit.http.Path;
import retrofit.http.Query;
public abstract interface TunesApi
{
@POST("/rt/utunes/rider/handshake")
public abstract void handshake(@Header("accept-language") String paramString, @Body Map<String, String> paramMap, Callback<Object> paramCallback);
@GET("/rt/utunes/providers/{provider_id}/playlists/{playlist_id}")
public abstract void playlist(@Path("provider_id") String paramString1, @Path("playlist_id") String paramString2, @Header("accept-language") String paramString3, @Query("latitude") Double paramDouble1, @Query("longitude") Double paramDouble2, @Query("city_name") String paramString4, @Query("country_code_iso2") String paramString5, Callback<Playlist> paramCallback);
@GET("/rt/utunes/providers/{provider_id}")
public abstract void provider(@Path("provider_id") String paramString1, @Header("accept-language") String paramString2, @Query("check_trial") Boolean paramBoolean, @Query("latitude") Double paramDouble1, @Query("longitude") Double paramDouble2, @Query("city_name") String paramString3, @Query("country_code_iso2") String paramString4, Callback<TunesProvider> paramCallback);
@GET("/rt/utunes/providers/{provider_id}/search")
public abstract void search(@Path("provider_id") String paramString1, @Query("city_name") String paramString2, @Query("country_code_iso2") String paramString3, @Query("query") String paramString4, Callback<Group> paramCallback);
@POST("/rt/utunes/providers/{id}/start_trial")
public abstract void startTrial(@Path("id") String paramString1, @Header("accept-language") String paramString2, @Body Map<String, Object> paramMap, Callback<TunesProvider> paramCallback);
}
/* Location:
* Qualified Name: com.ubercab.client.core.network.TunesApi
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | 2,168 | 0.766605 | 0.753229 | 37 | 57.62162 | 89.957451 | 376 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.135135 | false | false | 2 |
57a48783696f2b62d8580779d56253d76b412ac5 | 18,897,856,170,285 | 69daddae6ebb18635adbf7dd5a240654e9abc42f | /ESBComponents/LabCore/src/main/java/net/aegis/lab/dao/pojo/Questionnairetestplan.java | 6ab63ba6bc0922be398f6f24da92229ffaef103d | [] | no_license | Developer-Integration-Lab/InterOp-SOA | https://github.com/Developer-Integration-Lab/InterOp-SOA | 01c5f73dfa366f25e9a61c675a42bfbdcb697cf1 | 7661b3d8c1bdf9260e908b52235962bed37a8bd8 | refs/heads/master | 2021-01-17T11:56:07.998000 | 2012-09-20T20:10:35 | 2012-09-20T20:10:35 | 5,890,626 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.aegis.lab.dao.pojo;
import java.io.Serializable;
/**
* <p>Pojo mapping table questionnairetestplan</p>
* <p></p>
*
* <p>Generated at Thu Jun 16 10:48:01 EDT 2011</p>
* @author Salto-db Generator Ant v1.0.15 / Hibernate pojos and xml mapping files.
*
*/
public class Questionnairetestplan implements Serializable {
public static final String STATUS_ACTIVE = "ACTIVE";
/**
* Attribute questionnairetestplanId.
*/
private Integer questionnairetestplanId;
/**
* Attribute questionnaireresponse
*/
private Questionnaireresponse questionnaireresponse;
/**
* Attribute testcase
*/
private Testcase testcase;
/**
* Attribute status.
*/
private String status;
/**
* @return questionnairetestplanId
*/
public Integer getQuestionnairetestplanId() {
return questionnairetestplanId;
}
/**
* @param questionnairetestplanId new value for questionnairetestplanId
*/
public void setQuestionnairetestplanId(Integer questionnairetestplanId) {
this.questionnairetestplanId = questionnairetestplanId;
}
/**
* get questionnaireresponse
*/
public Questionnaireresponse getQuestionnaireresponse() {
return this.questionnaireresponse;
}
/**
* set questionnaireresponse
*/
public void setQuestionnaireresponse(Questionnaireresponse questionnaireresponse) {
this.questionnaireresponse = questionnaireresponse;
}
/**
* get testcase
*/
public Testcase getTestcase() {
return this.testcase;
}
/**
* set testcase
*/
public void setTestcase(Testcase testcase) {
this.testcase = testcase;
}
/**
* @return status
*/
public String getStatus() {
return status;
}
/**
* @param status new value for status
*/
public void setStatus(String status) {
this.status = status;
}
} | UTF-8 | Java | 1,795 | java | Questionnairetestplan.java | Java | [] | null | [] | package net.aegis.lab.dao.pojo;
import java.io.Serializable;
/**
* <p>Pojo mapping table questionnairetestplan</p>
* <p></p>
*
* <p>Generated at Thu Jun 16 10:48:01 EDT 2011</p>
* @author Salto-db Generator Ant v1.0.15 / Hibernate pojos and xml mapping files.
*
*/
public class Questionnairetestplan implements Serializable {
public static final String STATUS_ACTIVE = "ACTIVE";
/**
* Attribute questionnairetestplanId.
*/
private Integer questionnairetestplanId;
/**
* Attribute questionnaireresponse
*/
private Questionnaireresponse questionnaireresponse;
/**
* Attribute testcase
*/
private Testcase testcase;
/**
* Attribute status.
*/
private String status;
/**
* @return questionnairetestplanId
*/
public Integer getQuestionnairetestplanId() {
return questionnairetestplanId;
}
/**
* @param questionnairetestplanId new value for questionnairetestplanId
*/
public void setQuestionnairetestplanId(Integer questionnairetestplanId) {
this.questionnairetestplanId = questionnairetestplanId;
}
/**
* get questionnaireresponse
*/
public Questionnaireresponse getQuestionnaireresponse() {
return this.questionnaireresponse;
}
/**
* set questionnaireresponse
*/
public void setQuestionnaireresponse(Questionnaireresponse questionnaireresponse) {
this.questionnaireresponse = questionnaireresponse;
}
/**
* get testcase
*/
public Testcase getTestcase() {
return this.testcase;
}
/**
* set testcase
*/
public void setTestcase(Testcase testcase) {
this.testcase = testcase;
}
/**
* @return status
*/
public String getStatus() {
return status;
}
/**
* @param status new value for status
*/
public void setStatus(String status) {
this.status = status;
}
} | 1,795 | 0.708635 | 0.699721 | 96 | 17.708334 | 21.768152 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.989583 | false | false | 2 |
519a49dc1920d988c6a0690baad14d22355dee9f | 32,057,635,960,078 | 3ff2e67934b81665974b2dc1db1522eb3a5c77b0 | /a_plugin_target_process/src/main/java/views/sap/SAPEntriesComponent.java | 9e87c01f00abc404e76fe8b4ca6f0423f330b05b | [] | no_license | jonnytest1/eclipse-plugin | https://github.com/jonnytest1/eclipse-plugin | 97b8e2a4e9d4a4e24cc5a0c882a5c2eb7f315aa7 | 928bc2d4b00df293136ade0df7f5bb74b6c3af7a | refs/heads/master | 2020-06-25T12:00:43.437000 | 2020-05-28T11:41:54 | 2020-05-28T11:41:54 | 199,302,440 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package views.sap;
import java.awt.BorderLayout;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.eclipse.core.resources.IProject;
import model.WorkDurationEntry;
import model.WorkEntry;
import service.SAPListener;
import socialdear.logging.SystemProperties;
import socialdear.util.ExecutionException;
import socialdear.views.component.CustomElementPanel;
import socialdear.views.component.filter.implemented.FilterScrollComponent;
/**
* @since 2.1
*/
public class SAPEntriesComponent extends CustomElementPanel {
/**
*
*/
private static final long serialVersionUID = -3749494737769171500L;
private transient IProject project;
private transient Map<String, WorkDurationEntry> times = new ConcurrentHashMap<>();
private SAPControlComponent sapControlComponent;
private static final ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);
private transient ScheduledFuture<?> scheduleAtFixedRate;
public SAPEntriesComponent(IProject project) {
this.project = project;
setLayout(new BorderLayout());
scheduleAtFixedRate = scheduledThreadPoolExecutor.scheduleAtFixedRate(() -> {
try {
calculateTimes();
updateTimeSum();
} catch (Exception e) {
SystemProperties.print(e);
}
}, 0, 50, TimeUnit.SECONDS);
}
@Override
protected void cleanup() {
scheduleAtFixedRate.cancel(false);
}
@Override
protected void addElements() {
calculateTimes();
add(new FilterScrollComponent<WorkDurationEntry, SAPEntryComponent>(times.values(), SAPEntryComponent.class),
BorderLayout.CENTER);
sapControlComponent = new SAPControlComponent(this, project);
add(sapControlComponent, BorderLayout.SOUTH);
updateTimeSum();
}
private void calculateTimes() {
WorkEntry previous = null;
List<WorkEntry> filteredEntries = SAPListener.getEntries().stream() //
.filter(entry -> entry.getProject() == project)//
.collect(Collectors.toList());
try {
filteredEntries.add(SAPListener.getWorkEntry(project, null));
} catch (ExecutionException e) {
SystemProperties.print(e);
}
for (int i = 0; i < filteredEntries.size(); i++) {
WorkEntry entry = filteredEntries.get(i);
if (previous == null) {
previous = entry;
} else {
if (!previous.getSapId().equals(entry.getSapId()) || i == filteredEntries.size() - 1) {
addTime(previous, entry);
previous = entry;
}
}
}
}
private void addTime(WorkEntry previous, WorkEntry newEntry) {
WorkDurationEntry duration = times.computeIfAbsent(previous.getSapId(), key -> new WorkDurationEntry(previous));
duration.setNew(newEntry);
}
public void updateTimeSum() {
if (sapControlComponent != null) {
Long sum = times.values().stream()//
.mapToLong(WorkDurationEntry::getDuration)//
.sum();
sapControlComponent.setTimeText(WorkDurationEntry.getDurationString(sum));
}
}
public void addCustom(WorkDurationEntry entry) {
times.put(entry.getSapId(), entry);
recreate();
}
}
| UTF-8 | Java | 3,344 | java | SAPEntriesComponent.java | Java | [] | null | [] | package views.sap;
import java.awt.BorderLayout;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.eclipse.core.resources.IProject;
import model.WorkDurationEntry;
import model.WorkEntry;
import service.SAPListener;
import socialdear.logging.SystemProperties;
import socialdear.util.ExecutionException;
import socialdear.views.component.CustomElementPanel;
import socialdear.views.component.filter.implemented.FilterScrollComponent;
/**
* @since 2.1
*/
public class SAPEntriesComponent extends CustomElementPanel {
/**
*
*/
private static final long serialVersionUID = -3749494737769171500L;
private transient IProject project;
private transient Map<String, WorkDurationEntry> times = new ConcurrentHashMap<>();
private SAPControlComponent sapControlComponent;
private static final ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);
private transient ScheduledFuture<?> scheduleAtFixedRate;
public SAPEntriesComponent(IProject project) {
this.project = project;
setLayout(new BorderLayout());
scheduleAtFixedRate = scheduledThreadPoolExecutor.scheduleAtFixedRate(() -> {
try {
calculateTimes();
updateTimeSum();
} catch (Exception e) {
SystemProperties.print(e);
}
}, 0, 50, TimeUnit.SECONDS);
}
@Override
protected void cleanup() {
scheduleAtFixedRate.cancel(false);
}
@Override
protected void addElements() {
calculateTimes();
add(new FilterScrollComponent<WorkDurationEntry, SAPEntryComponent>(times.values(), SAPEntryComponent.class),
BorderLayout.CENTER);
sapControlComponent = new SAPControlComponent(this, project);
add(sapControlComponent, BorderLayout.SOUTH);
updateTimeSum();
}
private void calculateTimes() {
WorkEntry previous = null;
List<WorkEntry> filteredEntries = SAPListener.getEntries().stream() //
.filter(entry -> entry.getProject() == project)//
.collect(Collectors.toList());
try {
filteredEntries.add(SAPListener.getWorkEntry(project, null));
} catch (ExecutionException e) {
SystemProperties.print(e);
}
for (int i = 0; i < filteredEntries.size(); i++) {
WorkEntry entry = filteredEntries.get(i);
if (previous == null) {
previous = entry;
} else {
if (!previous.getSapId().equals(entry.getSapId()) || i == filteredEntries.size() - 1) {
addTime(previous, entry);
previous = entry;
}
}
}
}
private void addTime(WorkEntry previous, WorkEntry newEntry) {
WorkDurationEntry duration = times.computeIfAbsent(previous.getSapId(), key -> new WorkDurationEntry(previous));
duration.setNew(newEntry);
}
public void updateTimeSum() {
if (sapControlComponent != null) {
Long sum = times.values().stream()//
.mapToLong(WorkDurationEntry::getDuration)//
.sum();
sapControlComponent.setTimeText(WorkDurationEntry.getDurationString(sum));
}
}
public void addCustom(WorkDurationEntry entry) {
times.put(entry.getSapId(), entry);
recreate();
}
}
| 3,344 | 0.717703 | 0.709629 | 124 | 24.967741 | 26.898535 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.830645 | false | false | 2 |
6b566678251d0bce3e699a2c9d4ccb576b231a7e | 6,193,342,908,874 | 92aae8f9caeeefb5780a941e915cc45b71a582c1 | /easyexcel-core/src/main/java/com/alibaba/excel/context/csv/CsvReadContext.java | 00bcd54ae3ba93bc3a4702be14334f538f39753e | [
"Apache-2.0"
] | permissive | alibaba/easyexcel | https://github.com/alibaba/easyexcel | 2ba39bb5a410e218d3f85d0fd2b150df0699cc65 | 3effe20084d4b6cae929027b0483184fd6559902 | refs/heads/master | 2023-09-03T21:56:35.331000 | 2023-08-31T02:08:20 | 2023-08-31T02:08:20 | 120,395,176 | 30,634 | 7,900 | Apache-2.0 | false | 2023-08-31T02:08:22 | 2018-02-06T03:14:08 | 2023-08-31T01:09:50 | 2023-08-31T02:08:20 | 26,459 | 28,841 | 7,197 | 318 | Java | false | false | package com.alibaba.excel.context.csv;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.metadata.holder.csv.CsvReadSheetHolder;
import com.alibaba.excel.read.metadata.holder.csv.CsvReadWorkbookHolder;
/**
* A context is the main anchorage point of a ls xls reader.
*
* @author Jiaju Zhuang
**/
public interface CsvReadContext extends AnalysisContext {
/**
* All information about the workbook you are currently working on.
*
* @return Current workbook holder
*/
CsvReadWorkbookHolder csvReadWorkbookHolder();
/**
* All information about the sheet you are currently working on.
*
* @return Current sheet holder
*/
CsvReadSheetHolder csvReadSheetHolder();
}
| UTF-8 | Java | 750 | java | CsvReadContext.java | Java | [
{
"context": " anchorage point of a ls xls reader.\n *\n * @author Jiaju Zhuang\n **/\npublic interface CsvReadContext extends Anal",
"end": 325,
"score": 0.9998372197151184,
"start": 313,
"tag": "NAME",
"value": "Jiaju Zhuang"
}
] | null | [] | package com.alibaba.excel.context.csv;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.metadata.holder.csv.CsvReadSheetHolder;
import com.alibaba.excel.read.metadata.holder.csv.CsvReadWorkbookHolder;
/**
* A context is the main anchorage point of a ls xls reader.
*
* @author <NAME>
**/
public interface CsvReadContext extends AnalysisContext {
/**
* All information about the workbook you are currently working on.
*
* @return Current workbook holder
*/
CsvReadWorkbookHolder csvReadWorkbookHolder();
/**
* All information about the sheet you are currently working on.
*
* @return Current sheet holder
*/
CsvReadSheetHolder csvReadSheetHolder();
}
| 744 | 0.726667 | 0.726667 | 26 | 27.846153 | 26.366779 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.230769 | false | false | 2 |
d5af4f446fe8049fdd61e69a97db844461d2c912 | 25,623,774,892,083 | ee1c66583cf33ddef546a0325e45d556308f1fb4 | /src/main/java/com/partofa/domain/Region.java | 2176111bebef8114264c4beee3d3cca0b758f75c | [] | no_license | mtust/partofa | https://github.com/mtust/partofa | c268a4c0a36c6d3b133466f96b68bc48f429e8e3 | 413623ecbed0d981b937444f26fd24cd0b314520 | refs/heads/master | 2020-04-18T23:05:21.071000 | 2017-02-25T15:52:53 | 2017-02-25T15:52:53 | 67,824,872 | 4 | 0 | null | false | 2016-10-04T22:35:45 | 2016-09-09T19:02:31 | 2016-09-21T09:17:30 | 2016-10-04T22:35:45 | 41,214 | 1 | 0 | 0 | HTML | null | null | package com.partofa.domain;
import lombok.*;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
* Created by tust on 19.09.2016.
*/
@lombok.Data
@Entity
public class Region {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}
| UTF-8 | Java | 392 | java | Region.java | Java | [
{
"context": "e;\nimport javax.persistence.Id;\n\n/**\n * Created by tust on 19.09.2016.\n */\n@lombok.Data\n@Entity\npublic cl",
"end": 214,
"score": 0.999116063117981,
"start": 210,
"tag": "USERNAME",
"value": "tust"
}
] | null | [] | package com.partofa.domain;
import lombok.*;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
* Created by tust on 19.09.2016.
*/
@lombok.Data
@Entity
public class Region {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}
| 392 | 0.742347 | 0.721939 | 23 | 16.043478 | 15.96866 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.347826 | false | false | 2 |
7b58cf32b4065b652d4737a42e8f28ab815c9c02 | 33,595,234,257,599 | cfe8169a8c4032d49eae984224d94222dea923d6 | /src/main/java/guynir/pypath/services/FileNotFoundException.java | faaa3e99fc5177eafe575bc2ca8bf0a860ddb340 | [
"Apache-2.0"
] | permissive | guynir/pypath | https://github.com/guynir/pypath | 696fd10d7335a923c986a17809a7a88cb4b2274a | d9e456b3230d4c9fcdccf59c613c7401739f87a6 | refs/heads/master | 2021-01-02T17:39:03.152000 | 2020-02-18T16:45:29 | 2020-02-18T16:45:29 | 239,726,365 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package guynir.pypath.services;
import guynir.pypath.PyPathException;
/**
* This exception indicates that an attempt was made to access non-existing file.
*
* @author Guy Raz Nir
* @since 2020/02/08
*/
public class FileNotFoundException extends PyPathException {
public FileNotFoundException() {
}
public FileNotFoundException(String message) {
super(message);
}
public FileNotFoundException(String message, Throwable cause) {
super(message, cause);
}
}
| UTF-8 | Java | 504 | java | FileNotFoundException.java | Java | [
{
"context": "as made to access non-existing file.\n *\n * @author Guy Raz Nir\n * @since 2020/02/08\n */\npublic class FileNotFoun",
"end": 183,
"score": 0.9998837113380432,
"start": 172,
"tag": "NAME",
"value": "Guy Raz Nir"
}
] | null | [] | package guynir.pypath.services;
import guynir.pypath.PyPathException;
/**
* This exception indicates that an attempt was made to access non-existing file.
*
* @author <NAME>
* @since 2020/02/08
*/
public class FileNotFoundException extends PyPathException {
public FileNotFoundException() {
}
public FileNotFoundException(String message) {
super(message);
}
public FileNotFoundException(String message, Throwable cause) {
super(message, cause);
}
}
| 499 | 0.708333 | 0.69246 | 23 | 20.913044 | 23.8909 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.26087 | false | false | 2 |
b238cc4119004975c126c52f6c6e4b6839994866 | 3,186,865,760,764 | bf3532bb08853a19c8fb3655500be8cf4d494f49 | /designpatternconcurrent/src/main/java/com/bruce/producerConsumer/WorkStealingEnabledChannel.java | 2488fb512dbf8b8f4ab0280d22b23f3ba8ad1c0e | [] | no_license | wuxuebin529/practice | https://github.com/wuxuebin529/practice | 502a7f72ae9112d8782400bb3e3e7ca2976d9947 | 7b949acb7c6f97e01a4286b560ac5e895860c9be | refs/heads/master | 2022-01-26T03:19:09.594000 | 2019-06-06T07:34:39 | 2019-06-06T07:34:39 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bruce.producerConsumer;
import java.util.concurrent.BlockingDeque;
/**
* @Author: Bruce
* @Date: 2019/6/4 17:36
* @Version 1.0
*/
public interface WorkStealingEnabledChannel<P> extends Channel<P> {
P take(BlockingDeque<P> preferredQueue) throws InterruptedException;
}
| UTF-8 | Java | 292 | java | WorkStealingEnabledChannel.java | Java | [
{
"context": "va.util.concurrent.BlockingDeque;\n\n/**\n * @Author: Bruce\n * @Date: 2019/6/4 17:36\n * @Version 1.0\n */\npubl",
"end": 102,
"score": 0.8326603770256042,
"start": 97,
"tag": "NAME",
"value": "Bruce"
}
] | null | [] | package com.bruce.producerConsumer;
import java.util.concurrent.BlockingDeque;
/**
* @Author: Bruce
* @Date: 2019/6/4 17:36
* @Version 1.0
*/
public interface WorkStealingEnabledChannel<P> extends Channel<P> {
P take(BlockingDeque<P> preferredQueue) throws InterruptedException;
}
| 292 | 0.746575 | 0.705479 | 13 | 21.461538 | 24.468552 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.230769 | false | false | 2 |
31ffe6e7d9170bb543cf40b6a1da7fa6a172e85b | 3,186,865,758,449 | 52cd5b1c6703e12fdce3f2c0e9cf29b22febf584 | /app/src/main/java/com/chatapp/firebaseproject/chatapplication/RequestsFragment.java | 41286088b4ee2f33e7e5c028741d79a18a8a8c2d | [] | no_license | VrajalModi/ChatApplication1 | https://github.com/VrajalModi/ChatApplication1 | 846d8d15c715fa8a9c48ad764b48a2e84b60ac1f | 383f8a655c38daaf26e9a8b7954d2bceeeeff47d | refs/heads/master | 2020-04-16T23:00:12.952000 | 2019-01-16T07:14:23 | 2019-01-16T07:14:23 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.chatapp.firebaseproject.chatapplication;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
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 com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
/**
* A simple {@link Fragment} subclass.
*/
public class RequestsFragment extends Fragment {
private RecyclerView mFriendList;
private DatabaseReference mRequestDatabase;
private DatabaseReference mUserDatabase;
private FirebaseAuth mAuth;
private String mCurrent_User_Id;
private View myView;
private FirebaseRecyclerOptions<Requests> firebaseRecyclerOptions;
private FirebaseRecyclerAdapter<Requests, ReqestsViewHolder> recyclerAdapter;
public RequestsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.fragment_friends, container, false);
mAuth = FirebaseAuth.getInstance();
mCurrent_User_Id = mAuth.getCurrentUser().getUid();
mRequestDatabase = FirebaseDatabase.getInstance().getReference().child("Friend_Request").child(mCurrent_User_Id);
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mRequestDatabase.keepSynced(true);
mUserDatabase.keepSynced(true);
mFriendList = myView.findViewById(R.id.friend_list);
mFriendList.setHasFixedSize(true);
mFriendList.setLayoutManager(new LinearLayoutManager(getContext()));
firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<Requests>()
.setQuery(mRequestDatabase, Requests.class)
.build();
recyclerAdapter = new FirebaseRecyclerAdapter<Requests, ReqestsViewHolder>(firebaseRecyclerOptions) {
@Override
protected void onBindViewHolder(final ReqestsViewHolder holder, int position, final Requests model) {
// holder.itemView.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
//
// Intent profileIntent = new Intent(UserActivity.this,ProfileActivity.class);
// profileIntent.putExtra("user_id",user_id);
// startActivity(profileIntent);
//
// }
// });
final String list_user_id = getRef(position).getKey();
mRequestDatabase.child(list_user_id).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String type = dataSnapshot.child("request_type").getValue().toString();
holder.mUserTimeView.setText(type);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
mUserDatabase.child(list_user_id).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
final String userName = dataSnapshot.child("name").getValue().toString();
String userThumb = dataSnapshot.child("thumb_image").getValue().toString();
if (dataSnapshot.hasChild("online")) {
String userOnline = dataSnapshot.child("online").getValue().toString();
holder.setUserOnline(userOnline);
}
// holder.mUserTimeView.setText(model.getDate());
holder.mUserNameView.setText(userName);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), ProfileActivity.class);
intent.putExtra("user_id", list_user_id);
startActivity(intent);
// CharSequence option[] = new CharSequence[]{"Open Profile", "Send Message"};
//
// AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
// builder.setTitle("Select Options");
// builder.setItems(option, new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
//
// if (which == 0) {
// Intent intent = new Intent(getContext(), ProfileActivity.class);
// intent.putExtra("user_id", list_user_id);
// startActivity(intent);
// }
// if (which == 1) {
// Intent chatIntent = new Intent(getContext(), ChatActivity.class);
// chatIntent.putExtra("user_id", list_user_id);
// chatIntent.putExtra("user_name", userName);
// startActivity(chatIntent);
// }
//
// }
// });
// builder.show();
}
});
Picasso.get().load(userThumb).placeholder(R.drawable.om).into(holder.mUserCircleViewImage, new Callback() {
@Override
public void onSuccess() {
// Toast.makeText(UserActivity.this, "SuccessFully", Toast.LENGTH_LONG).show();
}
@Override
public void onError(Exception e) {
// Toast.makeText(UserActivity.this, "Error In Image load" + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
@NonNull
@Override
public ReqestsViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.user_single_layout, viewGroup, false);
ReqestsViewHolder friendsViewHolder = new ReqestsViewHolder(view);
return friendsViewHolder;
}
};
mFriendList.setAdapter(recyclerAdapter);
return myView;
}
public static class ReqestsViewHolder extends RecyclerView.ViewHolder {
public TextView mUserNameView;
public TextView mUserTimeView;
public CircleImageView mUserCircleViewImage;
// public ImageView mUserOnlineView;
public ReqestsViewHolder(@NonNull View itemView) {
super(itemView);
mUserNameView = (TextView) itemView.findViewById(R.id.user_single_name);
mUserTimeView = (TextView) itemView.findViewById(R.id.user_single_status);
mUserCircleViewImage = (CircleImageView) itemView.findViewById(R.id.user_single_image);
// mUserOnlineView = (ImageView)itemView.findViewById(R.id.user_single_online_icon);
}
public void setUserOnline(String online_status) {
ImageView userOnlineView = (ImageView) itemView.findViewById(R.id.user_single_online_icon);
if (online_status.equals("true")) {
userOnlineView.setVisibility(View.VISIBLE);
} else {
userOnlineView.setVisibility(View.INVISIBLE);
}
}
}
@Override
public void onStart() {
super.onStart();
if (recyclerAdapter != null) {
recyclerAdapter.startListening();
}
}
@Override
public void onStop() {
if (recyclerAdapter != null) {
recyclerAdapter.stopListening();
}
super.onStop();
}
@Override
public void onResume() {
super.onResume();
if (recyclerAdapter != null) {
recyclerAdapter.startListening();
}
}
}
| UTF-8 | Java | 9,689 | java | RequestsFragment.java | Java | [
{
"context": " chatIntent.putExtra(\"user_name\", userName);\n// s",
"end": 6388,
"score": 0.9503232836723328,
"start": 6380,
"tag": "USERNAME",
"value": "userName"
}
] | null | [] | package com.chatapp.firebaseproject.chatapplication;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
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 com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
/**
* A simple {@link Fragment} subclass.
*/
public class RequestsFragment extends Fragment {
private RecyclerView mFriendList;
private DatabaseReference mRequestDatabase;
private DatabaseReference mUserDatabase;
private FirebaseAuth mAuth;
private String mCurrent_User_Id;
private View myView;
private FirebaseRecyclerOptions<Requests> firebaseRecyclerOptions;
private FirebaseRecyclerAdapter<Requests, ReqestsViewHolder> recyclerAdapter;
public RequestsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.fragment_friends, container, false);
mAuth = FirebaseAuth.getInstance();
mCurrent_User_Id = mAuth.getCurrentUser().getUid();
mRequestDatabase = FirebaseDatabase.getInstance().getReference().child("Friend_Request").child(mCurrent_User_Id);
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mRequestDatabase.keepSynced(true);
mUserDatabase.keepSynced(true);
mFriendList = myView.findViewById(R.id.friend_list);
mFriendList.setHasFixedSize(true);
mFriendList.setLayoutManager(new LinearLayoutManager(getContext()));
firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<Requests>()
.setQuery(mRequestDatabase, Requests.class)
.build();
recyclerAdapter = new FirebaseRecyclerAdapter<Requests, ReqestsViewHolder>(firebaseRecyclerOptions) {
@Override
protected void onBindViewHolder(final ReqestsViewHolder holder, int position, final Requests model) {
// holder.itemView.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
//
// Intent profileIntent = new Intent(UserActivity.this,ProfileActivity.class);
// profileIntent.putExtra("user_id",user_id);
// startActivity(profileIntent);
//
// }
// });
final String list_user_id = getRef(position).getKey();
mRequestDatabase.child(list_user_id).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String type = dataSnapshot.child("request_type").getValue().toString();
holder.mUserTimeView.setText(type);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
mUserDatabase.child(list_user_id).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
final String userName = dataSnapshot.child("name").getValue().toString();
String userThumb = dataSnapshot.child("thumb_image").getValue().toString();
if (dataSnapshot.hasChild("online")) {
String userOnline = dataSnapshot.child("online").getValue().toString();
holder.setUserOnline(userOnline);
}
// holder.mUserTimeView.setText(model.getDate());
holder.mUserNameView.setText(userName);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), ProfileActivity.class);
intent.putExtra("user_id", list_user_id);
startActivity(intent);
// CharSequence option[] = new CharSequence[]{"Open Profile", "Send Message"};
//
// AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
// builder.setTitle("Select Options");
// builder.setItems(option, new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
//
// if (which == 0) {
// Intent intent = new Intent(getContext(), ProfileActivity.class);
// intent.putExtra("user_id", list_user_id);
// startActivity(intent);
// }
// if (which == 1) {
// Intent chatIntent = new Intent(getContext(), ChatActivity.class);
// chatIntent.putExtra("user_id", list_user_id);
// chatIntent.putExtra("user_name", userName);
// startActivity(chatIntent);
// }
//
// }
// });
// builder.show();
}
});
Picasso.get().load(userThumb).placeholder(R.drawable.om).into(holder.mUserCircleViewImage, new Callback() {
@Override
public void onSuccess() {
// Toast.makeText(UserActivity.this, "SuccessFully", Toast.LENGTH_LONG).show();
}
@Override
public void onError(Exception e) {
// Toast.makeText(UserActivity.this, "Error In Image load" + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
@NonNull
@Override
public ReqestsViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.user_single_layout, viewGroup, false);
ReqestsViewHolder friendsViewHolder = new ReqestsViewHolder(view);
return friendsViewHolder;
}
};
mFriendList.setAdapter(recyclerAdapter);
return myView;
}
public static class ReqestsViewHolder extends RecyclerView.ViewHolder {
public TextView mUserNameView;
public TextView mUserTimeView;
public CircleImageView mUserCircleViewImage;
// public ImageView mUserOnlineView;
public ReqestsViewHolder(@NonNull View itemView) {
super(itemView);
mUserNameView = (TextView) itemView.findViewById(R.id.user_single_name);
mUserTimeView = (TextView) itemView.findViewById(R.id.user_single_status);
mUserCircleViewImage = (CircleImageView) itemView.findViewById(R.id.user_single_image);
// mUserOnlineView = (ImageView)itemView.findViewById(R.id.user_single_online_icon);
}
public void setUserOnline(String online_status) {
ImageView userOnlineView = (ImageView) itemView.findViewById(R.id.user_single_online_icon);
if (online_status.equals("true")) {
userOnlineView.setVisibility(View.VISIBLE);
} else {
userOnlineView.setVisibility(View.INVISIBLE);
}
}
}
@Override
public void onStart() {
super.onStart();
if (recyclerAdapter != null) {
recyclerAdapter.startListening();
}
}
@Override
public void onStop() {
if (recyclerAdapter != null) {
recyclerAdapter.stopListening();
}
super.onStop();
}
@Override
public void onResume() {
super.onResume();
if (recyclerAdapter != null) {
recyclerAdapter.startListening();
}
}
}
| 9,689 | 0.567654 | 0.567138 | 254 | 37.145668 | 34.438213 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.515748 | false | false | 2 |
71389e80e7a2521df70fa86ee2bdec4edd7199d5 | 3,186,865,759,575 | 4686c6a5db1d83344be69e10964523790112a030 | /src/test/java/br/com/caelum/casadocodigo/builders/CompraBuilder.java | ccc3d367e1b7f0b3e07d8530fa46149e5ba7203a | [] | no_license | rafael-rollo/casadocodigo-mobile-backend | https://github.com/rafael-rollo/casadocodigo-mobile-backend | 160d5660b6f13d6f0e4c7907a4d25e13160a6a83 | ec596b00bd0a8be2ddfca60e737e2da9d033ea80 | refs/heads/master | 2021-01-01T17:43:07.742000 | 2015-08-17T20:23:14 | 2015-08-17T20:23:14 | 39,892,560 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.caelum.casadocodigo.builders;
import br.com.caelum.casadocodigo.modelo.Compra;
import br.com.caelum.casadocodigo.modelo.Item;
import br.com.caelum.casadocodigo.modelo.Usuario;
public class CompraBuilder {
private Compra compra;
public CompraBuilder setId(int id){
this.compra.setId(id);
return this;
}
public CompraBuilder addItem(Item item){
compra.addItem(item);
return this;
}
public CompraBuilder setUsuario(Usuario usuario) {
this.compra.setUsuario(usuario);
return this;
}
public CompraBuilder novaCompra(){
this.compra = new Compra();
return this;
}
public Compra build(){
return this.compra;
}
}
| UTF-8 | Java | 662 | java | CompraBuilder.java | Java | [] | null | [] | package br.com.caelum.casadocodigo.builders;
import br.com.caelum.casadocodigo.modelo.Compra;
import br.com.caelum.casadocodigo.modelo.Item;
import br.com.caelum.casadocodigo.modelo.Usuario;
public class CompraBuilder {
private Compra compra;
public CompraBuilder setId(int id){
this.compra.setId(id);
return this;
}
public CompraBuilder addItem(Item item){
compra.addItem(item);
return this;
}
public CompraBuilder setUsuario(Usuario usuario) {
this.compra.setUsuario(usuario);
return this;
}
public CompraBuilder novaCompra(){
this.compra = new Compra();
return this;
}
public Compra build(){
return this.compra;
}
}
| 662 | 0.741692 | 0.741692 | 35 | 17.914286 | 17.339256 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.371429 | false | false | 2 |
2cb10b8e81e7098984d29d266b77216d1ffae4c3 | 19,387,482,436,168 | f11f71761132c225db0febc2e6d17b5d507926ec | /src/CtaCte.java | f448286926e66d538624463f02b52595666d49ba | [] | no_license | rmargeli/TPFinal_IOO | https://github.com/rmargeli/TPFinal_IOO | 26118fa7525915d378b831ce8687b2a685c2a69c | b7e97ea08f36b156e8e3f386bd76540e5a65d054 | refs/heads/master | 2021-01-17T12:59:06.846000 | 2017-06-29T02:32:37 | 2017-06-29T02:32:37 | 95,730,781 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.ArrayList;
public class CtaCte {
private String estado;
private float saldo;
private ArrayList <Movimiento> movimientos;
public CtaCte(String estado, float saldo){
this.estado = estado;
this.saldo = saldo;
ArrayList <Movimiento> movimientos = new ArrayList <Movimiento>();
}
public void generarDeuda(float importe, int numero, MediosPago mp) {
saldo = saldo - importe;
Movimiento m = new Movimiento(importe, numero, mp);
movimientos.add(m);
}
public float getSaldo() {
return saldo;
}
public void agregarMovimiento(float importe, int numero, MediosPago mediospago) {
saldo = saldo + importe;
Movimiento m = new Movimiento(importe, numero, mediospago);
movimientos.add(m);
}
}
| UTF-8 | Java | 777 | java | CtaCte.java | Java | [] | null | [] | import java.util.ArrayList;
public class CtaCte {
private String estado;
private float saldo;
private ArrayList <Movimiento> movimientos;
public CtaCte(String estado, float saldo){
this.estado = estado;
this.saldo = saldo;
ArrayList <Movimiento> movimientos = new ArrayList <Movimiento>();
}
public void generarDeuda(float importe, int numero, MediosPago mp) {
saldo = saldo - importe;
Movimiento m = new Movimiento(importe, numero, mp);
movimientos.add(m);
}
public float getSaldo() {
return saldo;
}
public void agregarMovimiento(float importe, int numero, MediosPago mediospago) {
saldo = saldo + importe;
Movimiento m = new Movimiento(importe, numero, mediospago);
movimientos.add(m);
}
}
| 777 | 0.684685 | 0.684685 | 33 | 21.545454 | 23.211924 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.939394 | false | false | 2 |
94e51102a2e894b668de9559e078d6a0921cbf6f | 20,633,022,906,937 | dc7c687680e71a58b31ee853c53d8a6d81aad2a0 | /com.vmware.in.testframework.htmlparser/src/com/vmware/in/testframework/util/Constants.java | 9cd894b537b62697db68600c455aeef8d431654e | [] | no_license | Girish-Venkatesh/XTextSelenium | https://github.com/Girish-Venkatesh/XTextSelenium | 9f39e5b1ca274a9490d04aa0453ef0146dbb2e38 | cd829f2ce54af847c2a494cebf02d255b60fd3b7 | refs/heads/master | 2021-01-01T20:48:13.249000 | 2014-11-16T14:16:43 | 2014-11-16T14:16:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.vmware.in.testframework.util;
public class Constants {
public final static String HTML_FILE = "page8.html";
public final static String JSON_FILE = ".//src/Sample.json";
}
| UTF-8 | Java | 191 | java | Constants.java | Java | [] | null | [] | package com.vmware.in.testframework.util;
public class Constants {
public final static String HTML_FILE = "page8.html";
public final static String JSON_FILE = ".//src/Sample.json";
}
| 191 | 0.727749 | 0.722513 | 9 | 20.222221 | 23.827051 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.777778 | false | false | 2 |
13b6235ef4c31493782d87810de8fca0804c73dc | 18,391,049,962,598 | dd294c9f858e6b5ee73c30ae651b8ded4d775da2 | /icaopan-rebuld-dao/src/main/java/com/icaopan/trade/model/ComplianceResult.java | 9d057031051274c57264a1dd11e89231b94ed69a | [] | no_license | Wzhenshuai/peizi-funding | https://github.com/Wzhenshuai/peizi-funding | db4fafbd794849d2ccc3ea2c4cabf5a954660494 | 4734d3b7f75a1bb10c97134c9075a18a6972c7c5 | refs/heads/master | 2021-05-13T19:40:26.845000 | 2019-03-12T07:37:13 | 2019-03-12T07:37:13 | 116,896,616 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.icaopan.trade.model;
import java.util.Date;
import com.icaopan.util.DateUtils;
public class ComplianceResult {
private Integer id;
private String userName;
private String customerName;
private String opType;
private String stockCode;
private String stockName;
private String quantity;
private String reason;
private Date createTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getOpType() {
return opType;
}
public void setOpType(String opType) {
this.opType = opType == null ? null : opType.trim();
}
public String getStockCode() {
return stockCode;
}
public void setStockCode(String stockCode) {
this.stockCode = stockCode == null ? null : stockCode.trim();
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason == null ? null : reason.trim();
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getCreateTimeStr() {
return DateUtils.formatDateTime(createTime);
}
public String getStockName() {
return stockName;
}
public void setStockName(String stockName) {
this.stockName = stockName;
}
} | UTF-8 | Java | 1,958 | java | ComplianceResult.java | Java | [] | null | [] | package com.icaopan.trade.model;
import java.util.Date;
import com.icaopan.util.DateUtils;
public class ComplianceResult {
private Integer id;
private String userName;
private String customerName;
private String opType;
private String stockCode;
private String stockName;
private String quantity;
private String reason;
private Date createTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getOpType() {
return opType;
}
public void setOpType(String opType) {
this.opType = opType == null ? null : opType.trim();
}
public String getStockCode() {
return stockCode;
}
public void setStockCode(String stockCode) {
this.stockCode = stockCode == null ? null : stockCode.trim();
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason == null ? null : reason.trim();
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getCreateTimeStr() {
return DateUtils.formatDateTime(createTime);
}
public String getStockName() {
return stockName;
}
public void setStockName(String stockName) {
this.stockName = stockName;
}
} | 1,958 | 0.635853 | 0.635853 | 103 | 18.019417 | 18.445396 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.485437 | false | false | 2 |
0ec9dc96671f22dab5b2a01d6659dc64ac0bf5e0 | 13,228,499,271,945 | 0f1b4929ee26a450f8d9852b2479217aedcd3d84 | /src/main/java/com/github/abigail830/timeticket/infrastructure/client/WxLoginResponse.java | 721a2ed8374fd1eada30cdc3e56ebfade180d539 | [] | no_license | abigail830/time-ticket | https://github.com/abigail830/time-ticket | 4a494bdbf2cdd3243d99ffa1d07fea825ef7ac31 | 462118b46b37633d64de2d108b83c89505f4aa7e | refs/heads/master | 2020-05-05T02:23:11.114000 | 2019-04-22T12:57:38 | 2019-04-22T12:57:38 | 179,635,663 | 0 | 0 | null | false | 2019-04-06T15:15:18 | 2019-04-05T07:16:33 | 2019-04-06T15:07:46 | 2019-04-06T15:15:18 | 26 | 0 | 0 | 0 | Java | false | false | package com.github.abigail830.timeticket.infrastructure.client;
import com.github.abigail830.timeticket.domain.user.User;
import lombok.*;
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class WxLoginResponse {
private String session_key;
private String openid;
public boolean isValidResponse() {
return this.openid != null && this.session_key != null;
}
public User toUser() {
return new User(this.openid, this.session_key);
}
}
| UTF-8 | Java | 501 | java | WxLoginResponse.java | Java | [
{
"context": "package com.github.abigail830.timeticket.infrastructure.client;\n\nimport com.git",
"end": 29,
"score": 0.9994099140167236,
"start": 19,
"tag": "USERNAME",
"value": "abigail830"
},
{
"context": "eticket.infrastructure.client;\n\nimport com.github.abigail830.timeticket.d... | null | [] | package com.github.abigail830.timeticket.infrastructure.client;
import com.github.abigail830.timeticket.domain.user.User;
import lombok.*;
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class WxLoginResponse {
private String session_key;
private String openid;
public boolean isValidResponse() {
return this.openid != null && this.session_key != null;
}
public User toUser() {
return new User(this.openid, this.session_key);
}
}
| 501 | 0.716567 | 0.704591 | 25 | 19.040001 | 20.954197 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.32 | false | false | 2 |
9eb15f5d2925b87bf9438268b5b3a92875b4b663 | 9,663,676,470,783 | bf9a6d075ce99945c22479eb581c13b5a3bf76d0 | /library/src/main/java/cn/shyman/library/scan/OnScanListener.java | e47bf7d80cd6a22ca749095c81b98766610529d7 | [] | no_license | abshyer/scan | https://github.com/abshyer/scan | ccd977fc4617f56efb31cd514375a110a9a6179f | 9f4b21da23bb059a773af22945e55d67558a0a33 | refs/heads/master | 2021-07-22T22:21:51.670000 | 2017-10-30T00:53:31 | 2017-10-30T00:53:31 | 108,784,558 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.shyman.library.scan;
public interface OnScanListener {
/**
* 扫描成功
*
* @param result 结果信息
*/
void scanSuccess(String result);
}
| UTF-8 | Java | 165 | java | OnScanListener.java | Java | [] | null | [] | package cn.shyman.library.scan;
public interface OnScanListener {
/**
* 扫描成功
*
* @param result 结果信息
*/
void scanSuccess(String result);
}
| 165 | 0.677852 | 0.677852 | 10 | 13.9 | 13.40485 | 33 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 2 |
1e8285c69f9818bc84f8cc752473079bf24583ef | 12,378,095,808,549 | e7a0958b00729249598130ce60ebc9cb7abb2376 | /src/main/java/com/example/spring/Application.java | 1df6ba4fe7ca3a1c040b085e7e535b82f4c4f6c2 | [] | no_license | asahinadev/springboo-demo-recruit-api | https://github.com/asahinadev/springboo-demo-recruit-api | debf1bfc13830413ba07f6817273483f6c87fa26 | 7b9f40737368330a60affc6bfb01bac51410e753 | refs/heads/master | 2022-11-14T15:49:06.788000 | 2020-07-08T14:55:00 | 2020-07-08T14:55:00 | 267,440,153 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.spring;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FullyQualifiedAnnotationBeanNameGenerator;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@SpringBootApplication
@ComponentScan(nameGenerator = FullyQualifiedAnnotationBeanNameGenerator.class)
public class Application {
public static void main(String[] args) {
if (log.isDebugEnabled()) {
ToStringBuilder.setDefaultStyle(ToStringStyle.JSON_STYLE);
}
SpringApplication.run(Application.class, args);
}
}
| UTF-8 | Java | 779 | java | Application.java | Java | [] | null | [] | package com.example.spring;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FullyQualifiedAnnotationBeanNameGenerator;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@SpringBootApplication
@ComponentScan(nameGenerator = FullyQualifiedAnnotationBeanNameGenerator.class)
public class Application {
public static void main(String[] args) {
if (log.isDebugEnabled()) {
ToStringBuilder.setDefaultStyle(ToStringStyle.JSON_STYLE);
}
SpringApplication.run(Application.class, args);
}
}
| 779 | 0.835687 | 0.829268 | 24 | 31.458334 | 27.900089 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.916667 | false | false | 2 |
bb6593b42a8d8f58bfe9371effd03dbcd050dc1c | 30,485,677,931,820 | 574a6414c5b5f75d22d1e0d0e9a171bad5dd1434 | /src/main/java/me/bottleofglass/SmithingTweak/Main.java | 22d68a094ba384ae3083e930034a88d0966f3090 | [] | no_license | ItsmeFawaz/SmithingTweak | https://github.com/ItsmeFawaz/SmithingTweak | 8afd5dba988835dc4916c6f3dd0f74522953c47a | 5337a0a3b9e7ed7c559a93b3aac51b3821e1b2c6 | refs/heads/master | 2022-11-21T12:08:58.777000 | 2020-07-13T03:42:38 | 2020-07-13T03:42:38 | 279,202,275 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package me.bottleofglass.SmithingTweak;
import me.bottleofglass.SmithingTweak.listeners.SmithingTableListener;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin {
private static Main instance;
@Override
public void onEnable() {
instance = this;
getServer().getPluginManager().registerEvents(new SmithingTableListener(), this);
}
public static Main getInstance() {return instance;}
}
| UTF-8 | Java | 450 | java | Main.java | Java | [] | null | [] | package me.bottleofglass.SmithingTweak;
import me.bottleofglass.SmithingTweak.listeners.SmithingTableListener;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin {
private static Main instance;
@Override
public void onEnable() {
instance = this;
getServer().getPluginManager().registerEvents(new SmithingTableListener(), this);
}
public static Main getInstance() {return instance;}
}
| 450 | 0.748889 | 0.748889 | 14 | 31.142857 | 26.128412 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.